blob: 310b68eaeb5ee86be9fb3cbe24d67e7564c30fce [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) {
Argyrios Kyrtzidisa4288c42011-12-10 01:38:26 +000074 if (B == Buffer.getPointer()) {
75 assert(0 && "Replacing with the same buffer");
76 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
77 return;
78 }
Douglas Gregor29684422009-12-02 06:49:09 +000079
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000080 if (shouldFreeBuffer())
81 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000082 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000083 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000084}
85
David Blaikied6471f72011-09-25 23:23:43 +000086const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000087 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000088 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000089 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000090 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000091 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000092 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000093 if (Invalid)
94 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000095
Chris Lattnerb088cd32010-11-23 08:50:03 +000096 return Buffer.getPointer();
97 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000098
Chris Lattnerb088cd32010-11-23 08:50:03 +000099 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000100 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +0000101
102 // If we were unable to open the file, then we are in an inconsistent
103 // situation where the content cache referenced a file which no longer
104 // exists. Most likely, we were using a stat cache with an invalid entry but
105 // the file could also have been removed during processing. Since we can't
106 // really deal with this situation, just create an empty buffer.
107 //
108 // FIXME: This is definitely not ideal, but our immediate clients can't
109 // currently handle returning a null entry here. Ideally we should detect
110 // that we are in an inconsistent situation and error out as quickly as
111 // possible.
112 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000113 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000114 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000115 "<invalid>"));
116 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 Ptr[i] = FillStr[i % FillStr.size()];
119
120 if (Diag.isDiagnosticInFlight())
121 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000122 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000123 else
124 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000125 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000126
127 Buffer.setInt(Buffer.getInt() | InvalidFlag);
128
129 if (Invalid) *Invalid = true;
130 return Buffer.getPointer();
131 }
132
133 // Check that the file's size is the same as in the file entry (which may
134 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000135 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000136 if (Diag.isDiagnosticInFlight())
137 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000138 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000139 else
140 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000141 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000142
143 Buffer.setInt(Buffer.getInt() | InvalidFlag);
144 if (Invalid) *Invalid = true;
145 return Buffer.getPointer();
146 }
Eric Christopher156119d2011-04-09 00:01:04 +0000147
Chris Lattnerb088cd32010-11-23 08:50:03 +0000148 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000149 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000150 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000151 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000152 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000153 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
154 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
155 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
156 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
157 .StartsWith("\x2B\x2F\x76", "UTF-7")
158 .StartsWith("\xF7\x64\x4C", "UTF-1")
159 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
160 .StartsWith("\x0E\xFE\xFF", "SDSU")
161 .StartsWith("\xFB\xEE\x28", "BOCU-1")
162 .StartsWith("\x84\x31\x95\x33", "GB-18030")
163 .Default(0);
164
Eric Christopher156119d2011-04-09 00:01:04 +0000165 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000166 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000167 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000168 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000169 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000170
Douglas Gregorc8151082010-03-16 22:53:51 +0000171 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000172 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000173
174 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000175}
176
Chris Lattner5f9e2722011-07-23 10:55:15 +0000177unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000178 // Look up the filename in the string table, returning the pre-existing value
179 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000180 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000181 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000182 if (Entry.getValue() != ~0U)
183 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner5b9a5042009-01-26 07:57:50 +0000185 // Otherwise, assign this the next available ID.
186 Entry.setValue(FilenamesByID.size());
187 FilenamesByID.push_back(&Entry);
188 return FilenamesByID.size()-1;
189}
190
Chris Lattnerac50e342009-02-03 22:13:05 +0000191/// AddLineNote - Add a line note to the line table that indicates that there
192/// is a #line at the specified FID/Offset location which changes the presumed
193/// location to LineNo/FilenameID.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000194void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000195 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000196 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner23b5dc62009-02-04 00:40:31 +0000198 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
199 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner9d79eba2009-02-04 05:21:58 +0000201 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000202 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner9d79eba2009-02-04 05:21:58 +0000204 if (!Entries.empty()) {
205 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
206 // that we are still in "foo.h".
207 if (FilenameID == -1)
208 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner137b6a62009-02-04 06:25:26 +0000210 // If we are after a line marker that switched us to system header mode, or
211 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000212 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000213 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattner137b6a62009-02-04 06:25:26 +0000216 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
217 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000218}
219
Chris Lattner9d79eba2009-02-04 05:21:58 +0000220/// AddLineNote This is the same as the previous version of AddLineNote, but is
221/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
222/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
223/// this is a file exit. FileKind specifies whether this is a system header or
224/// extern C system header.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000225void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000226 unsigned LineNo, int FilenameID,
227 unsigned EntryExit,
228 SrcMgr::CharacteristicKind FileKind) {
229 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattner9d79eba2009-02-04 05:21:58 +0000231 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Chris Lattner9d79eba2009-02-04 05:21:58 +0000233 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
234 "Adding line entries out of order!");
235
Chris Lattner137b6a62009-02-04 06:25:26 +0000236 unsigned IncludeOffset = 0;
237 if (EntryExit == 0) { // No #include stack change.
238 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
239 } else if (EntryExit == 1) {
240 IncludeOffset = Offset-1;
241 } else if (EntryExit == 2) {
242 assert(!Entries.empty() && Entries.back().IncludeOffset &&
243 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner137b6a62009-02-04 06:25:26 +0000245 // Get the include loc of the last entries' include loc as our include loc.
246 IncludeOffset = 0;
247 if (const LineEntry *PrevEntry =
248 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
249 IncludeOffset = PrevEntry->IncludeOffset;
250 }
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner137b6a62009-02-04 06:25:26 +0000252 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
253 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000254}
255
256
Chris Lattner3cd949c2009-02-04 01:55:42 +0000257/// FindNearestLineEntry - Find the line entry nearest to FID that is before
258/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000259const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000260 unsigned Offset) {
261 const std::vector<LineEntry> &Entries = LineEntries[FID];
262 assert(!Entries.empty() && "No #line entries for this FID after all!");
263
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000264 // It is very common for the query to be after the last #line, check this
265 // first.
266 if (Entries.back().FileOffset <= Offset)
267 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000268
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000269 // Do a binary search to find the maximal element that is still before Offset.
270 std::vector<LineEntry>::const_iterator I =
271 std::upper_bound(Entries.begin(), Entries.end(), Offset);
272 if (I == Entries.begin()) return 0;
273 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000274}
Chris Lattnerac50e342009-02-03 22:13:05 +0000275
Douglas Gregorbd945002009-04-13 16:31:14 +0000276/// \brief Add a new line entry that has already been encoded into
277/// the internal representation of the line table.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000278void LineTableInfo::AddEntry(int FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000279 const std::vector<LineEntry> &Entries) {
280 LineEntries[FID] = Entries;
281}
Chris Lattnerac50e342009-02-03 22:13:05 +0000282
Chris Lattner5b9a5042009-01-26 07:57:50 +0000283/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000284///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000285unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000286 if (LineTable == 0)
287 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000288 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000289}
290
291
Chris Lattner4c4ea172009-02-03 21:52:55 +0000292/// AddLineNote - Add a line note to the line table for the FileID and offset
293/// specified by Loc. If FilenameID is -1, it is considered to be
294/// unspecified.
295void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
296 int FilenameID) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000297 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Douglas Gregore23ac652011-04-20 00:21:03 +0000299 bool Invalid = false;
300 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
301 if (!Entry.isFile() || Invalid)
302 return;
303
304 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000305
306 // Remember that this file has #line directives now if it doesn't already.
307 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattnerac50e342009-02-03 22:13:05 +0000309 if (LineTable == 0)
310 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000311 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000312}
313
Chris Lattner9d79eba2009-02-04 05:21:58 +0000314/// AddLineNote - Add a GNU line marker to the line table.
315void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
316 int FilenameID, bool IsFileEntry,
317 bool IsFileExit, bool IsSystemHeader,
318 bool IsExternCHeader) {
319 // If there is no filename and no flags, this is treated just like a #line,
320 // which does not change the flags of the previous line marker.
321 if (FilenameID == -1) {
322 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
323 "Can't set flags without setting the filename!");
324 return AddLineNote(Loc, LineNo, FilenameID);
325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000327 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000328
329 bool Invalid = false;
330 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
331 if (!Entry.isFile() || Invalid)
332 return;
333
334 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Chris Lattner9d79eba2009-02-04 05:21:58 +0000336 // Remember that this file has #line directives now if it doesn't already.
337 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner9d79eba2009-02-04 05:21:58 +0000339 if (LineTable == 0)
340 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner9d79eba2009-02-04 05:21:58 +0000342 SrcMgr::CharacteristicKind FileKind;
343 if (IsExternCHeader)
344 FileKind = SrcMgr::C_ExternCSystem;
345 else if (IsSystemHeader)
346 FileKind = SrcMgr::C_System;
347 else
348 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattner9d79eba2009-02-04 05:21:58 +0000350 unsigned EntryExit = 0;
351 if (IsFileEntry)
352 EntryExit = 1;
353 else if (IsFileExit)
354 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Chris Lattner9d79eba2009-02-04 05:21:58 +0000356 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
357 EntryExit, FileKind);
358}
359
Douglas Gregorbd945002009-04-13 16:31:14 +0000360LineTableInfo &SourceManager::getLineTable() {
361 if (LineTable == 0)
362 LineTable = new LineTableInfo();
363 return *LineTable;
364}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000365
Chris Lattner23b5dc62009-02-04 00:40:31 +0000366//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000367// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000368//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000369
David Blaikied6471f72011-09-25 23:23:43 +0000370SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000371 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000372 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000373 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000374 clearIDTables();
375 Diag.setSourceManager(this);
376}
377
Chris Lattner5b9a5042009-01-26 07:57:50 +0000378SourceManager::~SourceManager() {
379 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000381 // Delete FileEntry objects corresponding to content caches. Since the actual
382 // content cache objects are bump pointer allocated, we just have to run the
383 // dtors, but we call the deallocate method for completeness.
384 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000385 if (MemBufferInfos[i]) {
386 MemBufferInfos[i]->~ContentCache();
387 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
388 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000389 }
390 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
391 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000392 if (I->second) {
393 I->second->~ContentCache();
394 ContentCacheAlloc.Deallocate(I->second);
395 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000396 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000397
398 delete FakeBufferForRecovery;
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +0000399
400 for (llvm::DenseMap<FileID, MacroArgsMap *>::iterator
401 I = MacroArgsCacheMap.begin(),E = MacroArgsCacheMap.end(); I!=E; ++I) {
402 delete I->second;
403 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000404}
405
406void SourceManager::clearIDTables() {
407 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000408 LocalSLocEntryTable.clear();
409 LoadedSLocEntryTable.clear();
410 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000411 LastLineNoFileIDQuery = FileID();
412 LastLineNoContentCache = 0;
413 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5b9a5042009-01-26 07:57:50 +0000415 if (LineTable)
416 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chandler Carruth3201f382011-07-26 05:17:23 +0000418 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000419 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000420 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000421 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000422}
423
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000424/// getOrCreateContentCache - Create or return a cached ContentCache for the
425/// specified file.
426const ContentCache *
427SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000431 ContentCache *&Entry = FileInfos[FileEnt];
432 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner00282d62009-02-03 07:41:46 +0000434 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
435 // so that FileInfo can use the low 3 bits of the pointer for its own
436 // nefarious purposes.
437 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
438 EntryAlign = std::max(8U, EntryAlign);
439 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000440
441 // If the file contents are overridden with contents from another file,
442 // pass that file to ContentCache.
443 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
444 overI = OverriddenFiles.find(FileEnt);
445 if (overI == OverriddenFiles.end())
446 new (Entry) ContentCache(FileEnt);
447 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000448 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
449 : overI->second,
450 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000451
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000452 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
454
455
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000456/// createMemBufferContentCache - Create a new ContentCache for the specified
457/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000458const ContentCache*
459SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000460 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
461 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
462 // the pointer for its own nefarious purposes.
463 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
464 EntryAlign = std::max(8U, EntryAlign);
465 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000466 new (Entry) ContentCache();
467 MemBufferInfos.push_back(Entry);
468 Entry->setBuffer(Buffer);
469 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
471
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000472std::pair<int, unsigned>
473SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
474 unsigned TotalSize) {
475 assert(ExternalSLocEntries && "Don't have an external sloc source");
476 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
477 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
478 CurrentLoadedOffset -= TotalSize;
479 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
480 int ID = LoadedSLocEntryTable.size();
481 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000482}
483
Douglas Gregore23ac652011-04-20 00:21:03 +0000484/// \brief As part of recovering from missing or changed content, produce a
485/// fake, non-empty buffer.
486const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
487 if (!FakeBufferForRecovery)
488 FakeBufferForRecovery
489 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
490
491 return FakeBufferForRecovery;
492}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000493
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000494//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000495// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000496//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000497
Dan Gohman3f86b782010-08-26 21:27:06 +0000498/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000499/// include position. This works regardless of whether the ContentCache
500/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000501FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000502 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000503 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000504 int LoadedID, unsigned LoadedOffset) {
505 if (LoadedID < 0) {
506 assert(LoadedID != -1 && "Loading sentinel FileID");
507 unsigned Index = unsigned(-LoadedID) - 2;
508 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
509 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
510 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
511 FileInfo::get(IncludePos, File, FileCharacter));
512 SLocEntryLoaded[Index] = true;
513 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000514 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000515 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
516 FileInfo::get(IncludePos, File,
517 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000518 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000519 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
520 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
521 "Ran out of source locations!");
522 // We do a +1 here because we want a SourceLocation that means "the end of the
523 // file", e.g. for the "no newline at the end of the file" diagnostic.
524 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000526 // Set LastFileIDLookup to the newly created file. The next getFileID call is
527 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000528 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000529 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000530}
531
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000532SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000533SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
534 SourceLocation ExpansionLoc,
535 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000536 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
537 ExpansionLoc);
538 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000539}
540
541SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000542SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
543 SourceLocation ExpansionLocStart,
544 SourceLocation ExpansionLocEnd,
545 unsigned TokLength,
546 int LoadedID,
547 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000548 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
549 ExpansionLocEnd);
550 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000551}
552
553SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000554SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000555 unsigned TokLength,
556 int LoadedID,
557 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000558 if (LoadedID < 0) {
559 assert(LoadedID != -1 && "Loading sentinel FileID");
560 unsigned Index = unsigned(-LoadedID) - 2;
561 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
562 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000563 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000564 SLocEntryLoaded[Index] = true;
565 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000566 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000567 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000568 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
569 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
570 "Ran out of source locations!");
571 // See createFileID for that +1.
572 NextLocalOffset += TokLength + 1;
573 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000574}
575
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000576const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000577SourceManager::getMemoryBufferForFile(const FileEntry *File,
578 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000579 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000580 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000581 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000582}
583
Dan Gohman0d06e992010-10-26 20:47:28 +0000584void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000585 const llvm::MemoryBuffer *Buffer,
586 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000587 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000588 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000589
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000590 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregora081da52011-11-16 20:05:18 +0000591 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Douglas Gregor29684422009-12-02 06:49:09 +0000592}
593
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000594void SourceManager::overrideFileContents(const FileEntry *SourceFile,
595 const FileEntry *NewFile) {
596 assert(SourceFile->getSize() == NewFile->getSize() &&
597 "Different sizes, use the FileManager to create a virtual file with "
598 "the correct size");
599 assert(FileInfos.count(SourceFile) == 0 &&
600 "This function should be called at the initialization stage, before "
601 "any parsing occurs.");
602 OverriddenFiles[SourceFile] = NewFile;
603}
604
Chris Lattner5f9e2722011-07-23 10:55:15 +0000605StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000606 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000607 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000608 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000609 if (Invalid)
610 *Invalid = true;
611 return "<<<<<INVALID SOURCE LOCATION>>>>>";
612 }
613
614 const llvm::MemoryBuffer *Buf
615 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
616 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000617 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000618 *Invalid = MyInvalid;
619
620 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000621 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000622
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000623 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000624}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000625
Chris Lattner23b5dc62009-02-04 00:40:31 +0000626//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000627// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000628//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000629
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000630/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000631///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000632/// This is the cache-miss path of getFileID. Not as hot as that function, but
633/// still very important. It is responsible for finding the entry in the
634/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000635FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000636 if (!SLocOffset)
637 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000639 // Now it is time to search for the correct file. See where the SLocOffset
640 // sits in the global view and consult local or loaded buffers for it.
641 if (SLocOffset < NextLocalOffset)
642 return getFileIDLocal(SLocOffset);
643 return getFileIDLoaded(SLocOffset);
644}
645
646/// \brief Return the FileID for a SourceLocation with a low offset.
647///
648/// This function knows that the SourceLocation is in a local buffer, not a
649/// loaded one.
650FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
651 assert(SLocOffset < NextLocalOffset && "Bad function choice");
652
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000653 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000654 // behavior: 1) a lot of searched FileID's are "near" the cached file
655 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000656 // completely random and may be a very long way away.
657 //
658 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
659 // then we fall back to a less cache efficient, but more scalable, binary
660 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000662 // See if this is near the file point - worst case we start scanning from the
663 // most newly created FileID.
664 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000666 if (LastFileIDLookup.ID < 0 ||
667 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000668 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000669 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000670 } else {
671 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000672 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000673 }
674
675 // Find the FileID that contains this. "I" is an iterator that points to a
676 // FileID whose offset is known to be larger than SLocOffset.
677 unsigned NumProbes = 0;
678 while (1) {
679 --I;
680 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000681 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000682
Chandler Carruth3201f382011-07-26 05:17:23 +0000683 // If this isn't an expansion, remember it. We have good locality across
684 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000685 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000686 LastFileIDLookup = Res;
687 NumLinearScans += NumProbes+1;
688 return Res;
689 }
690 if (++NumProbes == 8)
691 break;
692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000694 // Convert "I" back into an index. We know that it is an entry whose index is
695 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000696 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000697 // LessIndex - This is the lower bound of the range that we're searching.
698 // We know that the offset corresponding to the FileID is is less than
699 // SLocOffset.
700 unsigned LessIndex = 0;
701 NumProbes = 0;
702 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000703 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000704 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000705 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000706 if (Invalid)
707 return FileID::get(0);
708
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000709 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000711 // If the offset of the midpoint is too large, chop the high side of the
712 // range to the midpoint.
713 if (MidOffset > SLocOffset) {
714 GreaterIndex = MiddleIndex;
715 continue;
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000718 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000719 // FIXME: This could be made faster by using a function that's aware of
720 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000721 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000722 FileID Res = FileID::get(MiddleIndex);
723
Chandler Carruth17287622011-07-26 04:56:51 +0000724 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000725 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000726 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000727 LastFileIDLookup = Res;
728 NumBinaryProbes += NumProbes;
729 return Res;
730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000732 // Otherwise, move the low-side up to the middle index.
733 LessIndex = MiddleIndex;
734 }
735}
736
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000737/// \brief Return the FileID for a SourceLocation with a high offset.
738///
739/// This function knows that the SourceLocation is in a loaded buffer, not a
740/// local one.
741FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000742 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000743 if (SLocOffset < CurrentLoadedOffset) {
744 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000745 return FileID();
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000746 }
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000747
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000748 // Essentially the same as the local case, but the loaded array is sorted
749 // in the other direction.
750
751 // First do a linear scan from the last lookup position, if possible.
752 unsigned I;
753 int LastID = LastFileIDLookup.ID;
754 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
755 I = 0;
756 else
757 I = (-LastID - 2) + 1;
758
759 unsigned NumProbes;
760 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
761 // Make sure the entry is loaded!
762 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
763 if (E.getOffset() <= SLocOffset) {
764 FileID Res = FileID::get(-int(I) - 2);
765
Chandler Carruth17287622011-07-26 04:56:51 +0000766 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000767 LastFileIDLookup = Res;
768 NumLinearScans += NumProbes + 1;
769 return Res;
770 }
771 }
772
773 // Linear scan failed. Do the binary search. Note the reverse sorting of the
774 // table: GreaterIndex is the one where the offset is greater, which is
775 // actually a lower index!
776 unsigned GreaterIndex = I;
777 unsigned LessIndex = LoadedSLocEntryTable.size();
778 NumProbes = 0;
779 while (1) {
780 ++NumProbes;
781 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
782 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
783
784 ++NumProbes;
785
786 if (E.getOffset() > SLocOffset) {
787 GreaterIndex = MiddleIndex;
788 continue;
789 }
790
791 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
792 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000793 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000794 LastFileIDLookup = Res;
795 NumBinaryProbes += NumProbes;
796 return Res;
797 }
798
799 LessIndex = MiddleIndex;
800 }
801}
802
Chris Lattneraddb7972009-01-26 20:04:19 +0000803SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000804getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000805 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000806 // Note: If Loc indicates an offset into a token that came from a macro
807 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000808 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000809 // location is the macro invocation, which the offset has nothing to do
810 // with. This is unlike when we get the spelling loc, because the offset
811 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000812 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000813 } while (!Loc.isFileID());
814
815 return Loc;
816}
817
818SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
819 do {
820 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000821 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000822 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattneraddb7972009-01-26 20:04:19 +0000823 } while (!Loc.isFileID());
824 return Loc;
825}
826
Argyrios Kyrtzidis796dbfb2011-10-12 07:07:40 +0000827SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
828 do {
829 if (isMacroArgExpansion(Loc))
830 Loc = getImmediateSpellingLoc(Loc);
831 else
832 Loc = getImmediateExpansionRange(Loc).first;
833 } while (!Loc.isFileID());
834 return Loc;
835}
836
Chris Lattneraddb7972009-01-26 20:04:19 +0000837
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000838std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000839SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000840 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000841 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000842 FileID FID;
843 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000844 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000845 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000846 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000848 FID = getFileID(Loc);
849 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000850 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000851 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000853 return std::make_pair(FID, Offset);
854}
855
856std::pair<FileID, unsigned>
857SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
858 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000859 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000860 FileID FID;
861 SourceLocation Loc;
862 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000863 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000864 Loc = Loc.getLocWithOffset(Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000866 FID = getFileID(Loc);
867 E = &getSLocEntry(FID);
Argyrios Kyrtzidisb6c465e2011-08-23 21:02:41 +0000868 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000869 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000871 return std::make_pair(FID, Offset);
872}
873
Chris Lattner387616e2009-02-17 08:04:48 +0000874/// getImmediateSpellingLoc - Given a SourceLocation object, return the
875/// spelling location referenced by the ID. This is the first level down
876/// towards the place where the characters that make up the lexed token can be
877/// found. This should not generally be used by clients.
878SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
879 if (Loc.isFileID()) return Loc;
880 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000881 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000882 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner387616e2009-02-17 08:04:48 +0000883}
884
885
Chandler Carruth3201f382011-07-26 05:17:23 +0000886/// getImmediateExpansionRange - Loc is required to be an expansion location.
887/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000888std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000889SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000890 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000891 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000892 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000893}
894
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000895/// getExpansionRange - Given a SourceLocation object, return the range of
896/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000897std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000898SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000899 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner66781332009-02-15 21:26:50 +0000901 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000902 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chandler Carruth3201f382011-07-26 05:17:23 +0000904 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000905 // points.
906 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000907 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +0000908 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000909 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +0000910 return Res;
911}
912
Chandler Carruth96d35892011-07-26 03:03:00 +0000913bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000914 if (!Loc.isMacroID()) return false;
915
916 FileID FID = getFileID(Loc);
917 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
Chandler Carruth17287622011-07-26 04:56:51 +0000918 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000919 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000920}
Chris Lattnere7fb4842009-02-15 20:52:18 +0000921
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000922
923//===----------------------------------------------------------------------===//
924// Queries about the code at a SourceLocation.
925//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000926
927/// getCharacterData - Return a pointer to the start of the specified location
928/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000929const char *SourceManager::getCharacterData(SourceLocation SL,
930 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 // Note that this is a hot function in the getSpelling() path, which is
932 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000933 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Ted Kremenekc16c2082009-01-06 01:55:26 +0000935 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000936 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000937 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
938 if (CharDataInvalid || !Entry.isFile()) {
939 if (Invalid)
940 *Invalid = true;
941
942 return "<<<<INVALID BUFFER>>>>";
943 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000944 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000945 = Entry.getFile().getContentCache()
946 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000947 if (Invalid)
948 *Invalid = CharDataInvalid;
949 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000950}
951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952
Chris Lattner9dc1f532007-07-20 16:37:10 +0000953/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000954/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000955unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
956 bool *Invalid) const {
957 bool MyInvalid = false;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +0000958 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000959 if (Invalid)
960 *Invalid = MyInvalid;
961
962 if (MyInvalid)
963 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Dylan Noblesmith098eaff2011-12-19 08:51:05 +0000965 if (FilePos >= MemBuf->getBufferSize()) {
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +0000966 if (Invalid)
967 *Invalid = MyInvalid;
968 return 1;
969 }
970
Dylan Noblesmith098eaff2011-12-19 08:51:05 +0000971 const char *Buf = MemBuf->getBufferStart();
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 unsigned LineStart = FilePos;
973 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
974 --LineStart;
975 return FilePos-LineStart+1;
976}
977
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000978// isInvalid - Return the result of calling loc.isInvalid(), and
979// if Invalid is not null, set its value to same.
980static bool isInvalid(SourceLocation Loc, bool *Invalid) {
981 bool MyInvalid = Loc.isInvalid();
982 if (Invalid)
983 *Invalid = MyInvalid;
984 return MyInvalid;
985}
986
Douglas Gregor50f6af72010-03-16 05:20:39 +0000987unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
988 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000989 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000990 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000991 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000992}
993
Chandler Carrutha77c0312011-07-25 20:57:57 +0000994unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
995 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000996 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000997 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000998 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000999}
1000
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001001unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1002 bool *Invalid) const {
1003 if (isInvalid(Loc, Invalid)) return 0;
1004 return getPresumedLoc(Loc).getColumn();
1005}
1006
Chandler Carruth14bd9652010-10-23 08:44:57 +00001007static LLVM_ATTRIBUTE_NOINLINE void
David Blaikied6471f72011-09-25 23:23:43 +00001008ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001009 llvm::BumpPtrAllocator &Alloc,
1010 const SourceManager &SM, bool &Invalid);
David Blaikied6471f72011-09-25 23:23:43 +00001011static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001012 llvm::BumpPtrAllocator &Alloc,
1013 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +00001014 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001015 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
1016 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001017 if (Invalid)
1018 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001020 // Find the file offsets of all of the *physical* source lines. This does
1021 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001022 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001024 // Line #1 starts at char 0.
1025 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001027 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1028 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1029 unsigned Offs = 0;
1030 while (1) {
1031 // Skip over the contents of the line.
1032 // TODO: Vectorize this? This is very performance sensitive for programs
1033 // with lots of diagnostics and in -E mode.
1034 const unsigned char *NextBuf = (const unsigned char *)Buf;
1035 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1036 ++NextBuf;
1037 Offs += NextBuf-Buf;
1038 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001040 if (Buf[0] == '\n' || Buf[0] == '\r') {
1041 // If this is \n\r or \r\n, skip both characters.
1042 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1043 ++Offs, ++Buf;
1044 ++Offs, ++Buf;
1045 LineOffsets.push_back(Offs);
1046 } else {
1047 // Otherwise, this is a null. If end of file, exit.
1048 if (Buf == End) break;
1049 // Otherwise, skip the null.
1050 ++Offs, ++Buf;
1051 }
1052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001054 // Copy the offsets into the FileInfo structure.
1055 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001056 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001057 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1058}
Reid Spencer5f016e22007-07-11 17:01:13 +00001059
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001060/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001061/// for the position indicated. This requires building and caching a table of
1062/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1063/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001064unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1065 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001066 if (FID.isInvalid()) {
1067 if (Invalid)
1068 *Invalid = true;
1069 return 1;
1070 }
1071
Chris Lattner2b2453a2009-01-17 06:22:33 +00001072 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001073 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001074 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001075 else {
1076 bool MyInvalid = false;
1077 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1078 if (MyInvalid || !Entry.isFile()) {
1079 if (Invalid)
1080 *Invalid = true;
1081 return 1;
1082 }
1083
1084 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1085 }
1086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001088 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001089 if (Content->SourceLineCache == 0) {
1090 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001091 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001092 if (Invalid)
1093 *Invalid = MyInvalid;
1094 if (MyInvalid)
1095 return 1;
1096 } else if (Invalid)
1097 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001098
1099 // Okay, we know we have a line number table. Do a binary search to find the
1100 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001101 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001102 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001103 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner30fc9332009-02-04 01:06:56 +00001105 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001106
Daniel Dunbar4106d692009-05-18 17:30:52 +00001107 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001108 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001109 //
1110 // If it is worth being optimized, then in my opinion it could be more
1111 // performant, simpler, and more obviously correct by just "galloping" outward
1112 // from the queried file position. In fact, this could be incorporated into a
1113 // generic algorithm such as lower_bound_with_hint.
1114 //
1115 // If someone gives me a test case where this matters, and I will do it! - DWD
1116
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001117 // If the previous query was to the same file, we know both the file pos from
1118 // that query and the line number returned. This allows us to narrow the
1119 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001120 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001121 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001122 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001123 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001125 // The query is likely to be nearby the previous one. Here we check to
1126 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1127 // where big comment blocks and vertical whitespace eat up lines but
1128 // contribute no tokens.
1129 if (SourceLineCache+5 < SourceLineCacheEnd) {
1130 if (SourceLineCache[5] > QueriedFilePos)
1131 SourceLineCacheEnd = SourceLineCache+5;
1132 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1133 if (SourceLineCache[10] > QueriedFilePos)
1134 SourceLineCacheEnd = SourceLineCache+10;
1135 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1136 if (SourceLineCache[20] > QueriedFilePos)
1137 SourceLineCacheEnd = SourceLineCache+20;
1138 }
1139 }
1140 }
1141 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001142 if (LastLineNoResult < Content->NumLines)
1143 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001144 }
1145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001147 // If the spread is large, do a "radix" test as our initial guess, based on
1148 // the assumption that lines average to approximately the same length.
1149 // NOTE: This is currently disabled, as it does not appear to be profitable in
1150 // initial measurements.
1151 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001152 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001154 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001155 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001157 // Check for -10 and +10 lines.
1158 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1159 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1160
1161 // If the computed lower bound is less than the query location, move it in.
1162 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1163 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1164 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001166 // If the computed upper bound is greater than the query location, move it.
1167 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1168 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1169 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001172 unsigned *Pos
1173 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001174 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner30fc9332009-02-04 01:06:56 +00001176 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001177 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001178 LastLineNoFilePos = QueriedFilePos;
1179 LastLineNoResult = LineNo;
1180 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001181}
1182
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001183unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1184 bool *Invalid) const {
1185 if (isInvalid(Loc, Invalid)) return 0;
1186 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1187 return getLineNumber(LocInfo.first, LocInfo.second);
1188}
Chandler Carruth64211622011-07-25 21:09:52 +00001189unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1190 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001191 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001192 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001193 return getLineNumber(LocInfo.first, LocInfo.second);
1194}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001195unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001196 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001197 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001198 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001199}
1200
Chris Lattner6b306672009-02-04 05:33:01 +00001201/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001202/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001203/// header, or an "implicit extern C" system header.
1204///
1205/// This state can be modified with flags on GNU linemarker directives like:
1206/// # 4 "foo.h" 3
1207/// which changes all source locations in the current file after that to be
1208/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001209SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001210SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1211 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001212 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001213 bool Invalid = false;
1214 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1215 if (Invalid || !SEntry.isFile())
1216 return C_User;
1217
1218 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001219
1220 // If there are no #line directives in this file, just return the whole-file
1221 // state.
1222 if (!FI.hasLineDirectives())
1223 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattner6b306672009-02-04 05:33:01 +00001225 assert(LineTable && "Can't have linetable entries without a LineTable!");
1226 // See if there is a #line directive before the location.
1227 const LineEntry *Entry =
1228 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Chris Lattner6b306672009-02-04 05:33:01 +00001230 // If this is before the first line marker, use the file characteristic.
1231 if (!Entry)
1232 return FI.getFileCharacteristic();
1233
1234 return Entry->FileKind;
1235}
1236
Chris Lattnerbff5c512009-02-17 08:39:06 +00001237/// Return the filename or buffer identifier of the buffer the location is in.
1238/// Note that this name does not respect #line directives. Use getPresumedLoc
1239/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001240const char *SourceManager::getBufferName(SourceLocation Loc,
1241 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001242 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Douglas Gregor50f6af72010-03-16 05:20:39 +00001244 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001245}
1246
Chris Lattner30fc9332009-02-04 01:06:56 +00001247
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001248/// getPresumedLoc - This method returns the "presumed" location of a
1249/// SourceLocation specifies. A "presumed location" can be modified by #line
1250/// or GNU line marker directives. This provides a view on the data that a
1251/// user should see in diagnostics, for example.
1252///
Chandler Carruth3201f382011-07-26 05:17:23 +00001253/// Note that a presumed location is always given as the expansion point of an
1254/// expansion location, not at the spelling location.
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001255PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1256 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chandler Carruth3201f382011-07-26 05:17:23 +00001258 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001259 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Douglas Gregore23ac652011-04-20 00:21:03 +00001261 bool Invalid = false;
1262 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1263 if (Invalid || !Entry.isFile())
1264 return PresumedLoc();
1265
1266 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001267 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattner3cd949c2009-02-04 01:55:42 +00001269 // To get the source name, first consult the FileEntry (if one exists)
1270 // before the MemBuffer as this will avoid unnecessarily paging in the
1271 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001272 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001273 if (C->OrigEntry)
1274 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001275 else
1276 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001277
Douglas Gregorc417fa02010-11-02 00:39:22 +00001278 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1279 if (Invalid)
1280 return PresumedLoc();
1281 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1282 if (Invalid)
1283 return PresumedLoc();
1284
Chris Lattner3cd949c2009-02-04 01:55:42 +00001285 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Chris Lattner3cd949c2009-02-04 01:55:42 +00001287 // If we have #line directives in this file, update and overwrite the physical
1288 // location info if appropriate.
1289 if (FI.hasLineDirectives()) {
1290 assert(LineTable && "Can't have linetable entries without a LineTable!");
1291 // See if there is a #line directive before this. If so, get it.
1292 if (const LineEntry *Entry =
1293 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001294 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001295 if (Entry->FilenameID != -1)
1296 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001297
1298 // Use the line number specified by the LineEntry. This line number may
1299 // be multiple lines down from the line entry. Add the difference in
1300 // physical line numbers from the query point and the line marker to the
1301 // total.
1302 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1303 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001305 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Chris Lattner137b6a62009-02-04 06:25:26 +00001307 // Handle virtual #include manipulation.
1308 if (Entry->IncludeOffset) {
1309 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001310 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner137b6a62009-02-04 06:25:26 +00001311 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001312 }
1313 }
1314
1315 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001316}
1317
Argyrios Kyrtzidis984e42c2011-08-23 21:02:28 +00001318/// \brief The size of the SLocEnty that \arg FID represents.
1319unsigned SourceManager::getFileIDSize(FileID FID) const {
1320 bool Invalid = false;
1321 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1322 if (Invalid)
1323 return 0;
1324
1325 int ID = FID.ID;
1326 unsigned NextOffset;
1327 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1328 NextOffset = getNextLocalOffset();
1329 else if (ID+1 == -1)
1330 NextOffset = MaxLoadedOffset;
1331 else
1332 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1333
1334 return NextOffset - Entry.getOffset() - 1;
1335}
1336
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001337//===----------------------------------------------------------------------===//
1338// Other miscellaneous methods.
1339//===----------------------------------------------------------------------===//
1340
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001341/// \brief Retrieve the inode for the given file entry, if possible.
1342///
1343/// This routine involves a system call, and therefore should only be used
1344/// in non-performance-critical code.
1345static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1346 if (!File)
1347 return llvm::Optional<ino_t>();
1348
1349 struct stat StatBuf;
1350 if (::stat(File->getName(), &StatBuf))
1351 return llvm::Optional<ino_t>();
1352
1353 return StatBuf.st_ino;
1354}
1355
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001356/// \brief Get the source location for the given file:line:col triplet.
1357///
1358/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001359/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001360SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001361 unsigned Line,
1362 unsigned Col) const {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001363 assert(SourceFile && "Null source file!");
1364 assert(Line && Col && "Line and column should start from 1!");
1365
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001366 FileID FirstFID = translateFile(SourceFile);
1367 return translateLineCol(FirstFID, Line, Col);
1368}
1369
1370/// \brief Get the FileID for the given file.
1371///
1372/// If the source file is included multiple times, the FileID will be the
1373/// first inclusion.
1374FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1375 assert(SourceFile && "Null source file!");
1376
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001377 // Find the first file ID that corresponds to the given file.
1378 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001380 // First, check the main file ID, since it is common to look for a
1381 // location in the main file.
1382 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001383 llvm::Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001384 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001385 bool Invalid = false;
1386 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1387 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001388 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001389
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001390 if (MainSLoc.isFile()) {
1391 const ContentCache *MainContentCache
1392 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001393 if (!MainContentCache) {
1394 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001395 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001396 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001397 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001398 // Fall back: check whether we have the same base name and inode
1399 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001400 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001401 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1402 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1403 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001404 if (SourceFileInode) {
1405 if (llvm::Optional<ino_t> MainFileInode
1406 = getActualFileInode(MainFile)) {
1407 if (*SourceFileInode == *MainFileInode) {
1408 FirstFID = MainFileID;
1409 SourceFile = MainFile;
1410 }
1411 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001412 }
1413 }
1414 }
1415 }
1416 }
1417
1418 if (FirstFID.isInvalid()) {
1419 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001420 // through all of the local source locations.
1421 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001422 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001423 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001424 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001425 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001426
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001427 if (SLoc.isFile() &&
1428 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001429 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001430 FirstFID = FileID::get(I);
1431 break;
1432 }
1433 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001434 // If that still didn't help, try the modules.
1435 if (FirstFID.isInvalid()) {
1436 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1437 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1438 if (SLoc.isFile() &&
1439 SLoc.getFile().getContentCache() &&
1440 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1441 FirstFID = FileID::get(-int(I) - 2);
1442 break;
1443 }
1444 }
1445 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001446 }
1447
1448 // If we haven't found what we want yet, try again, but this time stat()
1449 // each of the files in case the files have changed since we originally
1450 // parsed the file.
1451 if (FirstFID.isInvalid() &&
1452 (SourceFileName ||
1453 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1454 (SourceFileInode ||
1455 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001456 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001457 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1458 FileID IFileID;
1459 IFileID.ID = I;
1460 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001461 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001462 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001463
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001464 if (SLoc.isFile()) {
1465 const ContentCache *FileContentCache
1466 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001467 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001468 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001469 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1470 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1471 if (*SourceFileInode == *EntryInode) {
1472 FirstFID = FileID::get(I);
1473 SourceFile = Entry;
1474 break;
1475 }
1476 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001477 }
1478 }
1479 }
1480 }
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001481
1482 return FirstFID;
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001483}
1484
1485/// \brief Get the source location in \arg FID for the given line:col.
1486/// Returns null location if \arg FID is not a file SLocEntry.
1487SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001488 unsigned Line,
1489 unsigned Col) const {
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001490 if (FID.isInvalid())
1491 return SourceLocation();
1492
1493 bool Invalid = false;
1494 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1495 if (Invalid)
1496 return SourceLocation();
1497
1498 if (!Entry.isFile())
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001499 return SourceLocation();
1500
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001501 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1502
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001503 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001504 return FileLoc;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001505
1506 ContentCache *Content
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001507 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001508 if (!Content)
1509 return SourceLocation();
1510
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001511 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001512 // SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001513 if (Content->SourceLineCache == 0) {
1514 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001515 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001516 if (MyInvalid)
1517 return SourceLocation();
1518 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001519
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001520 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001521 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001522 if (Size > 0)
1523 --Size;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001524 return FileLoc.getLocWithOffset(Size);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001525 }
1526
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001527 const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001528 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001529 const char *Buf = Buffer->getBufferStart() + FilePos;
1530 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001531 if (BufLength == 0)
1532 return FileLoc.getLocWithOffset(FilePos);
1533
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001534 unsigned i = 0;
1535
1536 // Check that the given column is valid.
1537 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1538 ++i;
1539 if (i < Col-1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001540 return FileLoc.getLocWithOffset(FilePos + i);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001541
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001542 return FileLoc.getLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001543}
1544
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001545/// \brief Compute a map of macro argument chunks to their expanded source
1546/// location. Chunks that are not part of a macro argument will map to an
1547/// invalid source location. e.g. if a file contains one macro argument at
1548/// offset 100 with length 10, this is how the map will be formed:
1549/// 0 -> SourceLocation()
1550/// 100 -> Expanded macro arg location
1551/// 110 -> SourceLocation()
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001552void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001553 FileID FID) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001554 assert(!FID.isInvalid());
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001555 assert(!CachePtr);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001556
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001557 CachePtr = new MacroArgsMap();
1558 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001559 // Initially no macro argument chunk is present.
1560 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1561
1562 int ID = FID.ID;
1563 while (1) {
1564 ++ID;
1565 // Stop if there are no more FileIDs to check.
1566 if (ID > 0) {
1567 if (unsigned(ID) >= local_sloc_entry_size())
1568 return;
1569 } else if (ID == -1) {
1570 return;
1571 }
1572
1573 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
1574 if (Entry.isFile()) {
1575 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1576 if (IncludeLoc.isInvalid())
1577 continue;
1578 if (!isInFileID(IncludeLoc, FID))
1579 return; // No more files/macros that may be "contained" in this file.
1580
1581 // Skip the files/macros of the #include'd file, we only care about macros
1582 // that lexed macro arguments from our file.
1583 if (Entry.getFile().NumCreatedFIDs)
1584 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1585 continue;
1586 }
1587
1588 if (!Entry.getExpansion().isMacroArgExpansion())
1589 continue;
1590
1591 SourceLocation SpellLoc =
1592 getSpellingLoc(Entry.getExpansion().getSpellingLoc());
1593 unsigned BeginOffs;
1594 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1595 return; // No more files/macros that may be "contained" in this file.
1596 unsigned EndOffs = BeginOffs + getFileIDSize(FileID::get(ID));
1597
1598 // Add a new chunk for this macro argument. A previous macro argument chunk
1599 // may have been lexed again, so e.g. if the map is
1600 // 0 -> SourceLocation()
1601 // 100 -> Expanded loc #1
1602 // 110 -> SourceLocation()
1603 // and we found a new macro FileID that lexed from offet 105 with length 3,
1604 // the new map will be:
1605 // 0 -> SourceLocation()
1606 // 100 -> Expanded loc #1
1607 // 105 -> Expanded loc #2
1608 // 108 -> Expanded loc #1
1609 // 110 -> SourceLocation()
1610 //
1611 // Since re-lexed macro chunks will always be the same size or less of
1612 // previous chunks, we only need to find where the ending of the new macro
1613 // chunk is mapped to and update the map with new begin/end mappings.
1614
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001615 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001616 --I;
1617 SourceLocation EndOffsMappedLoc = I->second;
1618 MacroArgsCache[BeginOffs] = SourceLocation::getMacroLoc(Entry.getOffset());
1619 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1620 }
1621}
1622
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001623/// \brief If \arg Loc points inside a function macro argument, the returned
1624/// location will be the macro location in which the argument was expanded.
1625/// If a macro argument is used multiple times, the expanded location will
1626/// be at the first expansion of the argument.
1627/// e.g.
1628/// MY_MACRO(foo);
1629/// ^
1630/// Passing a file location pointing at 'foo', will yield a macro location
1631/// where 'foo' was expanded into.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001632SourceLocation
1633SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001634 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001635 return Loc;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001636
1637 FileID FID;
1638 unsigned Offset;
1639 llvm::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001640 if (FID.isInvalid())
1641 return Loc;
1642
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001643 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1644 if (!MacroArgsCache)
1645 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001646
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001647 assert(!MacroArgsCache->empty());
1648 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001649 --I;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001650
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001651 unsigned MacroArgBeginOffs = I->first;
1652 SourceLocation MacroArgExpandedLoc = I->second;
1653 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001654 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001655
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001656 return Loc;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001657}
1658
Chandler Carruth3201f382011-07-26 05:17:23 +00001659/// Given a decomposed source location, move it up the include/expansion stack
1660/// to the parent source location. If this is possible, return the decomposed
1661/// version of the parent in Loc and return false. If Loc is the top-level
1662/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001663static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1664 const SourceManager &SM) {
1665 SourceLocation UpperLoc;
1666 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
Chandler Carruth17287622011-07-26 04:56:51 +00001667 if (Entry.isExpansion())
Argyrios Kyrtzidis50402472011-09-19 20:39:57 +00001668 UpperLoc = Entry.getExpansion().getExpansionLocEnd();
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001669 else
1670 UpperLoc = Entry.getFile().getIncludeLoc();
1671
1672 if (UpperLoc.isInvalid())
1673 return true; // We reached the top.
1674
1675 Loc = SM.getDecomposedLoc(UpperLoc);
1676 return false;
1677}
1678
1679
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001680/// \brief Determines the order of 2 source locations in the translation unit.
1681///
1682/// \returns true if LHS source location comes before RHS, false otherwise.
1683bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1684 SourceLocation RHS) const {
1685 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1686 if (LHS == RHS)
1687 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001689 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1690 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001692 // If the source locations are in the same file, just compare offsets.
1693 if (LOffs.first == ROffs.first)
1694 return LOffs.second < ROffs.second;
1695
1696 // If we are comparing a source location with multiple locations in the same
1697 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001698 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1699 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001701 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001702 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
1703 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001705 // We need to find the common ancestor. The only way of doing this is to
1706 // build the complete include chain for one and then walking up the chain
1707 // of the other looking for a match.
1708 // We use a map from FileID to Offset to store the chain. Easier than writing
1709 // a custom set hash info that only depends on the first part of a pair.
1710 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1711 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00001712 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001713 LChain.insert(LOffs);
1714 // We catch the case where LOffs is in a file included by ROffs and
1715 // quit early. The other way round unfortunately remains suboptimal.
1716 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1717 LocSet::iterator I;
1718 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1719 if (MoveUpIncludeHierarchy(ROffs, *this))
1720 break; // Met at topmost file.
1721 }
1722 if (I != LChain.end())
1723 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner48296ba2010-05-07 05:51:13 +00001725 // If we exited because we found a nearest common ancestor, compare the
1726 // locations within the common file and cache them.
1727 if (LOffs.first == ROffs.first) {
1728 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1729 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001732 // This can happen if a location is in a built-ins buffer.
1733 // But see PR5662.
1734 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001735 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001736 bool LIsBuiltins = strcmp("<built-in>",
1737 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1738 bool RIsBuiltins = strcmp("<built-in>",
1739 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1740 // built-in is before non-built-in
1741 if (LIsBuiltins != RIsBuiltins)
1742 return LIsBuiltins;
1743 assert(LIsBuiltins && RIsBuiltins &&
1744 "Non-built-in locations must be rooted in the main file");
1745 // Both are in built-in buffers, but from different files. We just claim that
1746 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001747 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001748}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750/// PrintStats - Print statistics to stderr.
1751///
1752void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001753 llvm::errs() << "\n*** Source Manager Stats:\n";
1754 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1755 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001756 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00001757 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001758 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001759 << NextLocalOffset << "B of Sloc address space used.\n";
1760 llvm::errs() << LoadedSLocEntryTable.size()
1761 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001762 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001763 << "B of Sloc address space used.\n";
1764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 unsigned NumLineNumsComputed = 0;
1766 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001767 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1768 NumLineNumsComputed += I->second->SourceLineCache != 0;
1769 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001771 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001773 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001774 << NumLineNumsComputed << " files with line #'s computed, "
1775 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001776 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1777 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001778}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001779
1780ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001781
1782/// Return the amount of memory used by memory buffers, breaking down
1783/// by heap-backed versus mmap'ed memory.
1784SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1785 size_t malloc_bytes = 0;
1786 size_t mmap_bytes = 0;
1787
1788 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1789 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1790 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1791 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1792 mmap_bytes += sized_mapped;
1793 break;
1794 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1795 malloc_bytes += sized_mapped;
1796 break;
1797 }
1798
1799 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1800}
1801
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001802size_t SourceManager::getDataStructureSizes() const {
Ted Kremenek6e36c122011-07-27 18:41:16 +00001803 return llvm::capacity_in_bytes(MemBufferInfos)
1804 + llvm::capacity_in_bytes(LocalSLocEntryTable)
1805 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
1806 + llvm::capacity_in_bytes(SLocEntryLoaded)
1807 + llvm::capacity_in_bytes(FileInfos)
1808 + llvm::capacity_in_bytes(OverriddenFiles);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001809}