blob: 137da0d87ada88ddbb662b91343b4a8289b88549 [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
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +000014#include "clang/Lex/Lexer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000016#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000017#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Basic/FileManager.h"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000019#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000020#include "llvm/ADT/Optional.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000026#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000027#include <cstring>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000028#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000029
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31using namespace SrcMgr;
32using llvm::MemoryBuffer;
33
Chris Lattner23b5dc62009-02-04 00:40:31 +000034//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000035// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000036//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000037
Ted Kremenek78d85f52007-10-30 21:08:08 +000038ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000039 if (shouldFreeBuffer())
40 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Ted Kremenekc16c2082009-01-06 01:55:26 +000043/// getSizeBytesMapped - Returns the number of bytes actually mapped for
44/// this ContentCache. This can be 0 if the MemBuffer was not actually
45/// instantiated.
46unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000047 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000048}
49
Ted Kremenekf61b8312011-04-28 20:36:42 +000050/// Returns the kind of memory used to back the memory buffer for
51/// this content cache. This is used for performance analysis.
52llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
53 assert(Buffer.getPointer());
54
55 // Should be unreachable, but keep for sanity.
56 if (!Buffer.getPointer())
57 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
58
59 const llvm::MemoryBuffer *buf = Buffer.getPointer();
60 return buf->getBufferKind();
61}
62
Ted Kremenekc16c2082009-01-06 01:55:26 +000063/// getSize - Returns the size of the content encapsulated by this ContentCache.
64/// This can be the size of the source file or the size of an arbitrary
65/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000066/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000067unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000068 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000069 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000070}
71
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000072void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
73 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000074 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000075
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000076 if (shouldFreeBuffer())
77 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000078 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000079 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000080}
81
Douglas Gregor36c35ba2010-03-16 00:35:39 +000082const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000083 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000084 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000085 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000086 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000087 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000088 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000089 if (Invalid)
90 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000091
Chris Lattnerb088cd32010-11-23 08:50:03 +000092 return Buffer.getPointer();
93 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000094
Chris Lattnerb088cd32010-11-23 08:50:03 +000095 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000096 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000097
98 // If we were unable to open the file, then we are in an inconsistent
99 // situation where the content cache referenced a file which no longer
100 // exists. Most likely, we were using a stat cache with an invalid entry but
101 // the file could also have been removed during processing. Since we can't
102 // really deal with this situation, just create an empty buffer.
103 //
104 // FIXME: This is definitely not ideal, but our immediate clients can't
105 // currently handle returning a null entry here. Ideally we should detect
106 // that we are in an inconsistent situation and error out as quickly as
107 // possible.
108 if (!Buffer.getPointer()) {
109 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000110 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000111 "<invalid>"));
112 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000113 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000114 Ptr[i] = FillStr[i % FillStr.size()];
115
116 if (Diag.isDiagnosticInFlight())
117 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000118 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000119 else
120 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000121 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000122
123 Buffer.setInt(Buffer.getInt() | InvalidFlag);
124
125 if (Invalid) *Invalid = true;
126 return Buffer.getPointer();
127 }
128
129 // Check that the file's size is the same as in the file entry (which may
130 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000131 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000132 if (Diag.isDiagnosticInFlight())
133 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000134 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000135 else
136 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000137 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000138
139 Buffer.setInt(Buffer.getInt() | InvalidFlag);
140 if (Invalid) *Invalid = true;
141 return Buffer.getPointer();
142 }
Eric Christopher156119d2011-04-09 00:01:04 +0000143
Chris Lattnerb088cd32010-11-23 08:50:03 +0000144 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000145 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000146 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
147 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000148 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000149 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
150 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
151 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
152 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
153 .StartsWith("\x2B\x2F\x76", "UTF-7")
154 .StartsWith("\xF7\x64\x4C", "UTF-1")
155 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
156 .StartsWith("\x0E\xFE\xFF", "SDSU")
157 .StartsWith("\xFB\xEE\x28", "BOCU-1")
158 .StartsWith("\x84\x31\x95\x33", "GB-18030")
159 .Default(0);
160
Eric Christopher156119d2011-04-09 00:01:04 +0000161 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000162 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000163 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000164 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000165 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000166
Douglas Gregorc8151082010-03-16 22:53:51 +0000167 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000168 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000169
170 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000171}
172
Jay Foad65aa6882011-06-21 15:13:30 +0000173unsigned LineTableInfo::getLineTableFilenameID(llvm::StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000174 // Look up the filename in the string table, returning the pre-existing value
175 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000176 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000177 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000178 if (Entry.getValue() != ~0U)
179 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner5b9a5042009-01-26 07:57:50 +0000181 // Otherwise, assign this the next available ID.
182 Entry.setValue(FilenamesByID.size());
183 FilenamesByID.push_back(&Entry);
184 return FilenamesByID.size()-1;
185}
186
Chris Lattnerac50e342009-02-03 22:13:05 +0000187/// AddLineNote - Add a line note to the line table that indicates that there
188/// is a #line at the specified FID/Offset location which changes the presumed
189/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000190void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000191 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000192 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner23b5dc62009-02-04 00:40:31 +0000194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner9d79eba2009-02-04 05:21:58 +0000197 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000198 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattner9d79eba2009-02-04 05:21:58 +0000200 if (!Entries.empty()) {
201 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202 // that we are still in "foo.h".
203 if (FilenameID == -1)
204 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattner137b6a62009-02-04 06:25:26 +0000206 // If we are after a line marker that switched us to system header mode, or
207 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000208 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000209 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattner137b6a62009-02-04 06:25:26 +0000212 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
213 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000214}
215
Chris Lattner9d79eba2009-02-04 05:21:58 +0000216/// AddLineNote This is the same as the previous version of AddLineNote, but is
217/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
218/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
219/// this is a file exit. FileKind specifies whether this is a system header or
220/// extern C system header.
221void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
222 unsigned LineNo, int FilenameID,
223 unsigned EntryExit,
224 SrcMgr::CharacteristicKind FileKind) {
225 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattner9d79eba2009-02-04 05:21:58 +0000229 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230 "Adding line entries out of order!");
231
Chris Lattner137b6a62009-02-04 06:25:26 +0000232 unsigned IncludeOffset = 0;
233 if (EntryExit == 0) { // No #include stack change.
234 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235 } else if (EntryExit == 1) {
236 IncludeOffset = Offset-1;
237 } else if (EntryExit == 2) {
238 assert(!Entries.empty() && Entries.back().IncludeOffset &&
239 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattner137b6a62009-02-04 06:25:26 +0000241 // Get the include loc of the last entries' include loc as our include loc.
242 IncludeOffset = 0;
243 if (const LineEntry *PrevEntry =
244 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245 IncludeOffset = PrevEntry->IncludeOffset;
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattner137b6a62009-02-04 06:25:26 +0000248 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
249 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000250}
251
252
Chris Lattner3cd949c2009-02-04 01:55:42 +0000253/// FindNearestLineEntry - Find the line entry nearest to FID that is before
254/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000255const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000256 unsigned Offset) {
257 const std::vector<LineEntry> &Entries = LineEntries[FID];
258 assert(!Entries.empty() && "No #line entries for this FID after all!");
259
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000260 // It is very common for the query to be after the last #line, check this
261 // first.
262 if (Entries.back().FileOffset <= Offset)
263 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000264
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000265 // Do a binary search to find the maximal element that is still before Offset.
266 std::vector<LineEntry>::const_iterator I =
267 std::upper_bound(Entries.begin(), Entries.end(), Offset);
268 if (I == Entries.begin()) return 0;
269 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000270}
Chris Lattnerac50e342009-02-03 22:13:05 +0000271
Douglas Gregorbd945002009-04-13 16:31:14 +0000272/// \brief Add a new line entry that has already been encoded into
273/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000274void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000275 const std::vector<LineEntry> &Entries) {
276 LineEntries[FID] = Entries;
277}
Chris Lattnerac50e342009-02-03 22:13:05 +0000278
Chris Lattner5b9a5042009-01-26 07:57:50 +0000279/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000280///
Jay Foad65aa6882011-06-21 15:13:30 +0000281unsigned SourceManager::getLineTableFilenameID(llvm::StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000282 if (LineTable == 0)
283 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000284 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000285}
286
287
Chris Lattner4c4ea172009-02-03 21:52:55 +0000288/// AddLineNote - Add a line note to the line table for the FileID and offset
289/// specified by Loc. If FilenameID is -1, it is considered to be
290/// unspecified.
291void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
292 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000293 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregore23ac652011-04-20 00:21:03 +0000295 bool Invalid = false;
296 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
297 if (!Entry.isFile() || Invalid)
298 return;
299
300 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000301
302 // Remember that this file has #line directives now if it doesn't already.
303 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattnerac50e342009-02-03 22:13:05 +0000305 if (LineTable == 0)
306 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000307 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000308}
309
Chris Lattner9d79eba2009-02-04 05:21:58 +0000310/// AddLineNote - Add a GNU line marker to the line table.
311void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
312 int FilenameID, bool IsFileEntry,
313 bool IsFileExit, bool IsSystemHeader,
314 bool IsExternCHeader) {
315 // If there is no filename and no flags, this is treated just like a #line,
316 // which does not change the flags of the previous line marker.
317 if (FilenameID == -1) {
318 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
319 "Can't set flags without setting the filename!");
320 return AddLineNote(Loc, LineNo, FilenameID);
321 }
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner9d79eba2009-02-04 05:21:58 +0000323 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000324
325 bool Invalid = false;
326 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
327 if (!Entry.isFile() || Invalid)
328 return;
329
330 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner9d79eba2009-02-04 05:21:58 +0000332 // Remember that this file has #line directives now if it doesn't already.
333 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chris Lattner9d79eba2009-02-04 05:21:58 +0000335 if (LineTable == 0)
336 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner9d79eba2009-02-04 05:21:58 +0000338 SrcMgr::CharacteristicKind FileKind;
339 if (IsExternCHeader)
340 FileKind = SrcMgr::C_ExternCSystem;
341 else if (IsSystemHeader)
342 FileKind = SrcMgr::C_System;
343 else
344 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattner9d79eba2009-02-04 05:21:58 +0000346 unsigned EntryExit = 0;
347 if (IsFileEntry)
348 EntryExit = 1;
349 else if (IsFileExit)
350 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner9d79eba2009-02-04 05:21:58 +0000352 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
353 EntryExit, FileKind);
354}
355
Douglas Gregorbd945002009-04-13 16:31:14 +0000356LineTableInfo &SourceManager::getLineTable() {
357 if (LineTable == 0)
358 LineTable = new LineTableInfo();
359 return *LineTable;
360}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000361
Chris Lattner23b5dc62009-02-04 00:40:31 +0000362//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000363// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000364//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000365
Chris Lattner39b49bc2010-11-23 08:35:12 +0000366SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000367 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000368 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000369 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000370 clearIDTables();
371 Diag.setSourceManager(this);
372}
373
Chris Lattner5b9a5042009-01-26 07:57:50 +0000374SourceManager::~SourceManager() {
375 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000377 // Delete FileEntry objects corresponding to content caches. Since the actual
378 // content cache objects are bump pointer allocated, we just have to run the
379 // dtors, but we call the deallocate method for completeness.
380 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
381 MemBufferInfos[i]->~ContentCache();
382 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
383 }
384 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
385 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
386 I->second->~ContentCache();
387 ContentCacheAlloc.Deallocate(I->second);
388 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000389
390 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000391}
392
393void SourceManager::clearIDTables() {
394 MainFileID = FileID();
395 SLocEntryTable.clear();
396 LastLineNoFileIDQuery = FileID();
397 LastLineNoContentCache = 0;
398 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner5b9a5042009-01-26 07:57:50 +0000400 if (LineTable)
401 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner5b9a5042009-01-26 07:57:50 +0000403 // Use up FileID #0 as an invalid instantiation.
404 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000405 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000406}
407
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000408/// getOrCreateContentCache - Create or return a cached ContentCache for the
409/// specified file.
410const ContentCache *
411SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000415 ContentCache *&Entry = FileInfos[FileEnt];
416 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chris Lattner00282d62009-02-03 07:41:46 +0000418 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
419 // so that FileInfo can use the low 3 bits of the pointer for its own
420 // nefarious purposes.
421 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
422 EntryAlign = std::max(8U, EntryAlign);
423 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000424
425 // If the file contents are overridden with contents from another file,
426 // pass that file to ContentCache.
427 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
428 overI = OverriddenFiles.find(FileEnt);
429 if (overI == OverriddenFiles.end())
430 new (Entry) ContentCache(FileEnt);
431 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000432 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
433 : overI->second,
434 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000435
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000436 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000437}
438
439
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000440/// createMemBufferContentCache - Create a new ContentCache for the specified
441/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000442const ContentCache*
443SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000444 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
445 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
446 // the pointer for its own nefarious purposes.
447 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
448 EntryAlign = std::max(8U, EntryAlign);
449 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000450 new (Entry) ContentCache();
451 MemBufferInfos.push_back(Entry);
452 Entry->setBuffer(Buffer);
453 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000456void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
457 unsigned NumSLocEntries,
458 unsigned NextOffset) {
459 ExternalSLocEntries = Source;
460 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000461 unsigned CurPrealloc = SLocEntryLoaded.size();
462 // If we've ever preallocated, we must not count the dummy entry.
463 if (CurPrealloc) --CurPrealloc;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000464 SLocEntryLoaded.resize(NumSLocEntries + 1);
465 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000466 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000467}
468
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000469void SourceManager::ClearPreallocatedSLocEntries() {
470 unsigned I = 0;
471 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
472 if (!SLocEntryLoaded[I])
473 break;
474
475 // We've already loaded all preallocated source location entries.
476 if (I == SLocEntryLoaded.size())
477 return;
478
479 // Remove everything from location I onward.
480 SLocEntryTable.resize(I);
481 SLocEntryLoaded.clear();
482 ExternalSLocEntries = 0;
483}
484
Douglas Gregore23ac652011-04-20 00:21:03 +0000485/// \brief As part of recovering from missing or changed content, produce a
486/// fake, non-empty buffer.
487const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
488 if (!FakeBufferForRecovery)
489 FakeBufferForRecovery
490 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
491
492 return FakeBufferForRecovery;
493}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000494
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000495//===----------------------------------------------------------------------===//
496// Methods to create new FileID's and instantiations.
497//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000498
Dan Gohman3f86b782010-08-26 21:27:06 +0000499/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000500/// include position. This works regardless of whether the ContentCache
501/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000502FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000503 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000504 SrcMgr::CharacteristicKind FileCharacter,
505 unsigned PreallocatedID,
506 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000507 if (PreallocatedID) {
508 // If we're filling in a preallocated ID, just load in the file
509 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000510 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000511 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000512 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000513 "Source location entry already loaded");
514 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000515 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000516 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
517 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000518 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000519 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000520 }
521
Mike Stump1eb44332009-09-09 15:08:12 +0000522 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000523 FileInfo::get(IncludePos, File,
524 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000525 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000526 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
527 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000529 // Set LastFileIDLookup to the newly created file. The next getFileID call is
530 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000531 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000532 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000533}
534
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000535/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000536/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000537/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000538SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000539 SourceLocation ILocStart,
540 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000541 unsigned TokLength,
542 unsigned PreallocatedID,
543 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000544 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000545 if (PreallocatedID) {
546 // If we're filling in a preallocated ID, just load in the
547 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000548 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000549 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000550 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000551 "Source location entry already loaded");
552 assert(Offset && "Preallocate source location cannot have zero offset");
553 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
554 SLocEntryLoaded[PreallocatedID] = true;
555 return SourceLocation::getMacroLoc(Offset);
556 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000557 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000558 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
559 NextOffset += TokLength+1;
560 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000561}
562
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000563const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000564SourceManager::getMemoryBufferForFile(const FileEntry *File,
565 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000566 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000567 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000568 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000569}
570
Dan Gohman0d06e992010-10-26 20:47:28 +0000571void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000572 const llvm::MemoryBuffer *Buffer,
573 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000574 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000575 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000576
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000577 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000578}
579
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000580void SourceManager::overrideFileContents(const FileEntry *SourceFile,
581 const FileEntry *NewFile) {
582 assert(SourceFile->getSize() == NewFile->getSize() &&
583 "Different sizes, use the FileManager to create a virtual file with "
584 "the correct size");
585 assert(FileInfos.count(SourceFile) == 0 &&
586 "This function should be called at the initialization stage, before "
587 "any parsing occurs.");
588 OverriddenFiles[SourceFile] = NewFile;
589}
590
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000591llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000592 bool MyInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000593 const SLocEntry &SLoc = getSLocEntry(FID.ID, &MyInvalid);
594 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000595 if (Invalid)
596 *Invalid = true;
597 return "<<<<<INVALID SOURCE LOCATION>>>>>";
598 }
599
600 const llvm::MemoryBuffer *Buf
601 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
602 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000603 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000604 *Invalid = MyInvalid;
605
606 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000607 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000608
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000609 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000610}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000611
Chris Lattner23b5dc62009-02-04 00:40:31 +0000612//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000613// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000614//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000615
616/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
617/// method that is used for all SourceManager queries that start with a
618/// SourceLocation object. It is responsible for finding the entry in
619/// SLocEntryTable which contains the specified location.
620///
621FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000622 if (!SLocOffset)
623 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000625 // After the first and second level caches, I see two common sorts of
626 // behavior: 1) a lot of searched FileID's are "near" the cached file location
627 // or are "near" the cached instantiation location. 2) others are just
628 // completely random and may be a very long way away.
629 //
630 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
631 // then we fall back to a less cache efficient, but more scalable, binary
632 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000634 // See if this is near the file point - worst case we start scanning from the
635 // most newly created FileID.
636 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000638 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
639 // Neither loc prunes our search.
640 I = SLocEntryTable.end();
641 } else {
642 // Perhaps it is near the file point.
643 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
644 }
645
646 // Find the FileID that contains this. "I" is an iterator that points to a
647 // FileID whose offset is known to be larger than SLocOffset.
648 unsigned NumProbes = 0;
649 while (1) {
650 --I;
Douglas Gregore23ac652011-04-20 00:21:03 +0000651 if (ExternalSLocEntries) {
652 bool Invalid = false;
653 getSLocEntry(FileID::get(I - SLocEntryTable.begin()), &Invalid);
654 if (Invalid)
655 return FileID::get(0);
656 }
657
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000658 if (I->getOffset() <= SLocOffset) {
659#if 0
660 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
661 I-SLocEntryTable.begin(),
662 I->isInstantiation() ? "inst" : "file",
663 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
664#endif
665 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000666
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000667 // If this isn't an instantiation, remember it. We have good locality
668 // across FileID lookups.
669 if (!I->isInstantiation())
670 LastFileIDLookup = Res;
671 NumLinearScans += NumProbes+1;
672 return Res;
673 }
674 if (++NumProbes == 8)
675 break;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000678 // Convert "I" back into an index. We know that it is an entry whose index is
679 // larger than the offset we are looking for.
680 unsigned GreaterIndex = I-SLocEntryTable.begin();
681 // LessIndex - This is the lower bound of the range that we're searching.
682 // We know that the offset corresponding to the FileID is is less than
683 // SLocOffset.
684 unsigned LessIndex = 0;
685 NumProbes = 0;
686 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000687 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000688 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregore23ac652011-04-20 00:21:03 +0000689 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex), &Invalid)
690 .getOffset();
691 if (Invalid)
692 return FileID::get(0);
693
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000694 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000696 // If the offset of the midpoint is too large, chop the high side of the
697 // range to the midpoint.
698 if (MidOffset > SLocOffset) {
699 GreaterIndex = MiddleIndex;
700 continue;
701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000703 // If the middle index contains the value, succeed and return.
704 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
705#if 0
706 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
707 I-SLocEntryTable.begin(),
708 I->isInstantiation() ? "inst" : "file",
709 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
710#endif
711 FileID Res = FileID::get(MiddleIndex);
712
713 // If this isn't an instantiation, remember it. We have good locality
714 // across FileID lookups.
715 if (!I->isInstantiation())
716 LastFileIDLookup = Res;
717 NumBinaryProbes += NumProbes;
718 return Res;
719 }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000721 // Otherwise, move the low-side up to the middle index.
722 LessIndex = MiddleIndex;
723 }
724}
725
Chris Lattneraddb7972009-01-26 20:04:19 +0000726SourceLocation SourceManager::
727getInstantiationLocSlowCase(SourceLocation Loc) const {
728 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000729 // Note: If Loc indicates an offset into a token that came from a macro
730 // expansion (e.g. the 5th character of the token) we do not want to add
731 // this offset when going to the instantiation location. The instatiation
732 // location is the macro invocation, which the offset has nothing to do
733 // with. This is unlike when we get the spelling loc, because the offset
734 // directly correspond to the token whose spelling we're inspecting.
735 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000736 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000737 } while (!Loc.isFileID());
738
739 return Loc;
740}
741
742SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
743 do {
744 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
745 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
746 Loc = Loc.getFileLocWithOffset(LocInfo.second);
747 } while (!Loc.isFileID());
748 return Loc;
749}
750
751
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000752std::pair<FileID, unsigned>
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000753SourceManager::getDecomposedInstantiationLocSlowCase(
754 const SrcMgr::SLocEntry *E) const {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000755 // If this is an instantiation record, walk through all the instantiation
756 // points.
757 FileID FID;
758 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000759 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000760 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000761 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000763 FID = getFileID(Loc);
764 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000765 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000766 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000768 return std::make_pair(FID, Offset);
769}
770
771std::pair<FileID, unsigned>
772SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
773 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000774 // If this is an instantiation record, walk through all the instantiation
775 // points.
776 FileID FID;
777 SourceLocation Loc;
778 do {
779 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000781 FID = getFileID(Loc);
782 E = &getSLocEntry(FID);
783 Offset += Loc.getOffset()-E->getOffset();
784 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000786 return std::make_pair(FID, Offset);
787}
788
Chris Lattner387616e2009-02-17 08:04:48 +0000789/// getImmediateSpellingLoc - Given a SourceLocation object, return the
790/// spelling location referenced by the ID. This is the first level down
791/// towards the place where the characters that make up the lexed token can be
792/// found. This should not generally be used by clients.
793SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
794 if (Loc.isFileID()) return Loc;
795 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
796 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
797 return Loc.getFileLocWithOffset(LocInfo.second);
798}
799
800
Chris Lattnere7fb4842009-02-15 20:52:18 +0000801/// getImmediateInstantiationRange - Loc is required to be an instantiation
802/// location. Return the start/end of the instantiation information.
803std::pair<SourceLocation,SourceLocation>
804SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
805 assert(Loc.isMacroID() && "Not an instantiation loc!");
806 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
807 return II.getInstantiationLocRange();
808}
809
Chris Lattner66781332009-02-15 21:26:50 +0000810/// getInstantiationRange - Given a SourceLocation object, return the
811/// range of tokens covered by the instantiation in the ultimate file.
812std::pair<SourceLocation,SourceLocation>
813SourceManager::getInstantiationRange(SourceLocation Loc) const {
814 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner66781332009-02-15 21:26:50 +0000816 std::pair<SourceLocation,SourceLocation> Res =
817 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Chris Lattner66781332009-02-15 21:26:50 +0000819 // Fully resolve the start and end locations to their ultimate instantiation
820 // points.
821 while (!Res.first.isFileID())
822 Res.first = getImmediateInstantiationRange(Res.first).first;
823 while (!Res.second.isFileID())
824 Res.second = getImmediateInstantiationRange(Res.second).second;
825 return Res;
826}
827
Chris Lattnere7fb4842009-02-15 20:52:18 +0000828
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000829
830//===----------------------------------------------------------------------===//
831// Queries about the code at a SourceLocation.
832//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000833
834/// getCharacterData - Return a pointer to the start of the specified location
835/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000836const char *SourceManager::getCharacterData(SourceLocation SL,
837 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 // Note that this is a hot function in the getSpelling() path, which is
839 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000840 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Ted Kremenekc16c2082009-01-06 01:55:26 +0000842 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000843 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000844 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
845 if (CharDataInvalid || !Entry.isFile()) {
846 if (Invalid)
847 *Invalid = true;
848
849 return "<<<<INVALID BUFFER>>>>";
850 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000851 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000852 = Entry.getFile().getContentCache()
853 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000854 if (Invalid)
855 *Invalid = CharDataInvalid;
856 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
Chris Lattner9dc1f532007-07-20 16:37:10 +0000860/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000861/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000862unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
863 bool *Invalid) const {
864 bool MyInvalid = false;
865 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
866 if (Invalid)
867 *Invalid = MyInvalid;
868
869 if (MyInvalid)
870 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 unsigned LineStart = FilePos;
873 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
874 --LineStart;
875 return FilePos-LineStart+1;
876}
877
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000878// isInvalid - Return the result of calling loc.isInvalid(), and
879// if Invalid is not null, set its value to same.
880static bool isInvalid(SourceLocation Loc, bool *Invalid) {
881 bool MyInvalid = Loc.isInvalid();
882 if (Invalid)
883 *Invalid = MyInvalid;
884 return MyInvalid;
885}
886
Douglas Gregor50f6af72010-03-16 05:20:39 +0000887unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
888 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000889 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000890 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000891 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000892}
893
Douglas Gregor50f6af72010-03-16 05:20:39 +0000894unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
895 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000896 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000897 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000898 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000899}
900
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000901unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
902 bool *Invalid) const {
903 if (isInvalid(Loc, Invalid)) return 0;
904 return getPresumedLoc(Loc).getColumn();
905}
906
Chandler Carruth14bd9652010-10-23 08:44:57 +0000907static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000908ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
909 llvm::BumpPtrAllocator &Alloc,
910 const SourceManager &SM, bool &Invalid);
911static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
912 llvm::BumpPtrAllocator &Alloc,
913 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000914 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000915 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
916 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000917 if (Invalid)
918 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000920 // Find the file offsets of all of the *physical* source lines. This does
921 // not look at trigraphs, escaped newlines, or anything else tricky.
Benjamin Kramere8554482011-07-06 16:43:46 +0000922 llvm::SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000924 // Line #1 starts at char 0.
925 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000927 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
928 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
929 unsigned Offs = 0;
930 while (1) {
931 // Skip over the contents of the line.
932 // TODO: Vectorize this? This is very performance sensitive for programs
933 // with lots of diagnostics and in -E mode.
934 const unsigned char *NextBuf = (const unsigned char *)Buf;
935 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
936 ++NextBuf;
937 Offs += NextBuf-Buf;
938 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000940 if (Buf[0] == '\n' || Buf[0] == '\r') {
941 // If this is \n\r or \r\n, skip both characters.
942 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
943 ++Offs, ++Buf;
944 ++Offs, ++Buf;
945 LineOffsets.push_back(Offs);
946 } else {
947 // Otherwise, this is a null. If end of file, exit.
948 if (Buf == End) break;
949 // Otherwise, skip the null.
950 ++Offs, ++Buf;
951 }
952 }
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000954 // Copy the offsets into the FileInfo structure.
955 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000956 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000957 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
958}
Reid Spencer5f016e22007-07-11 17:01:13 +0000959
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000960/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000961/// for the position indicated. This requires building and caching a table of
962/// line offsets for the MemoryBuffer, so this is not cheap: use only when
963/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000964unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
965 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +0000966 if (FID.isInvalid()) {
967 if (Invalid)
968 *Invalid = true;
969 return 1;
970 }
971
Chris Lattner2b2453a2009-01-17 06:22:33 +0000972 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000973 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000974 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +0000975 else {
976 bool MyInvalid = false;
977 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
978 if (MyInvalid || !Entry.isFile()) {
979 if (Invalid)
980 *Invalid = true;
981 return 1;
982 }
983
984 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
985 }
986
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000988 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000989 if (Content->SourceLineCache == 0) {
990 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000991 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000992 if (Invalid)
993 *Invalid = MyInvalid;
994 if (MyInvalid)
995 return 1;
996 } else if (Invalid)
997 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998
999 // Okay, we know we have a line number table. Do a binary search to find the
1000 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001001 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001002 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001003 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner30fc9332009-02-04 01:06:56 +00001005 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001006
Daniel Dunbar4106d692009-05-18 17:30:52 +00001007 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001008 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001009 //
1010 // If it is worth being optimized, then in my opinion it could be more
1011 // performant, simpler, and more obviously correct by just "galloping" outward
1012 // from the queried file position. In fact, this could be incorporated into a
1013 // generic algorithm such as lower_bound_with_hint.
1014 //
1015 // If someone gives me a test case where this matters, and I will do it! - DWD
1016
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001017 // If the previous query was to the same file, we know both the file pos from
1018 // that query and the line number returned. This allows us to narrow the
1019 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001020 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001021 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001022 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001023 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001025 // The query is likely to be nearby the previous one. Here we check to
1026 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1027 // where big comment blocks and vertical whitespace eat up lines but
1028 // contribute no tokens.
1029 if (SourceLineCache+5 < SourceLineCacheEnd) {
1030 if (SourceLineCache[5] > QueriedFilePos)
1031 SourceLineCacheEnd = SourceLineCache+5;
1032 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1033 if (SourceLineCache[10] > QueriedFilePos)
1034 SourceLineCacheEnd = SourceLineCache+10;
1035 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1036 if (SourceLineCache[20] > QueriedFilePos)
1037 SourceLineCacheEnd = SourceLineCache+20;
1038 }
1039 }
1040 }
1041 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001042 if (LastLineNoResult < Content->NumLines)
1043 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001044 }
1045 }
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001047 // If the spread is large, do a "radix" test as our initial guess, based on
1048 // the assumption that lines average to approximately the same length.
1049 // NOTE: This is currently disabled, as it does not appear to be profitable in
1050 // initial measurements.
1051 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001052 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001054 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001055 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001057 // Check for -10 and +10 lines.
1058 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1059 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1060
1061 // If the computed lower bound is less than the query location, move it in.
1062 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1063 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1064 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001066 // If the computed upper bound is greater than the query location, move it.
1067 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1068 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1069 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001072 unsigned *Pos
1073 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001074 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Chris Lattner30fc9332009-02-04 01:06:56 +00001076 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001077 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001078 LastLineNoFilePos = QueriedFilePos;
1079 LastLineNoResult = LineNo;
1080 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001081}
1082
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001083unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1084 bool *Invalid) const {
1085 if (isInvalid(Loc, Invalid)) return 0;
1086 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1087 return getLineNumber(LocInfo.first, LocInfo.second);
1088}
Douglas Gregor50f6af72010-03-16 05:20:39 +00001089unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1090 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001091 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +00001092 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1093 return getLineNumber(LocInfo.first, LocInfo.second);
1094}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001095unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001096 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001097 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001098 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001099}
1100
Chris Lattner6b306672009-02-04 05:33:01 +00001101/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001102/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001103/// header, or an "implicit extern C" system header.
1104///
1105/// This state can be modified with flags on GNU linemarker directives like:
1106/// # 4 "foo.h" 3
1107/// which changes all source locations in the current file after that to be
1108/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001109SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001110SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1111 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1112 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001113 bool Invalid = false;
1114 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1115 if (Invalid || !SEntry.isFile())
1116 return C_User;
1117
1118 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001119
1120 // If there are no #line directives in this file, just return the whole-file
1121 // state.
1122 if (!FI.hasLineDirectives())
1123 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Chris Lattner6b306672009-02-04 05:33:01 +00001125 assert(LineTable && "Can't have linetable entries without a LineTable!");
1126 // See if there is a #line directive before the location.
1127 const LineEntry *Entry =
1128 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Chris Lattner6b306672009-02-04 05:33:01 +00001130 // If this is before the first line marker, use the file characteristic.
1131 if (!Entry)
1132 return FI.getFileCharacteristic();
1133
1134 return Entry->FileKind;
1135}
1136
Chris Lattnerbff5c512009-02-17 08:39:06 +00001137/// Return the filename or buffer identifier of the buffer the location is in.
1138/// Note that this name does not respect #line directives. Use getPresumedLoc
1139/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001140const char *SourceManager::getBufferName(SourceLocation Loc,
1141 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001142 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregor50f6af72010-03-16 05:20:39 +00001144 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001145}
1146
Chris Lattner30fc9332009-02-04 01:06:56 +00001147
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001148/// getPresumedLoc - This method returns the "presumed" location of a
1149/// SourceLocation specifies. A "presumed location" can be modified by #line
1150/// or GNU line marker directives. This provides a view on the data that a
1151/// user should see in diagnostics, for example.
1152///
1153/// Note that a presumed location is always given as the instantiation point
1154/// of an instantiation location, not at the spelling location.
1155PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1156 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001158 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001159 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Douglas Gregore23ac652011-04-20 00:21:03 +00001161 bool Invalid = false;
1162 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1163 if (Invalid || !Entry.isFile())
1164 return PresumedLoc();
1165
1166 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001167 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner3cd949c2009-02-04 01:55:42 +00001169 // To get the source name, first consult the FileEntry (if one exists)
1170 // before the MemBuffer as this will avoid unnecessarily paging in the
1171 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001172 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001173 if (C->OrigEntry)
1174 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001175 else
1176 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001177
Douglas Gregorc417fa02010-11-02 00:39:22 +00001178 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1179 if (Invalid)
1180 return PresumedLoc();
1181 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1182 if (Invalid)
1183 return PresumedLoc();
1184
Chris Lattner3cd949c2009-02-04 01:55:42 +00001185 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner3cd949c2009-02-04 01:55:42 +00001187 // If we have #line directives in this file, update and overwrite the physical
1188 // location info if appropriate.
1189 if (FI.hasLineDirectives()) {
1190 assert(LineTable && "Can't have linetable entries without a LineTable!");
1191 // See if there is a #line directive before this. If so, get it.
1192 if (const LineEntry *Entry =
1193 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001194 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001195 if (Entry->FilenameID != -1)
1196 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001197
1198 // Use the line number specified by the LineEntry. This line number may
1199 // be multiple lines down from the line entry. Add the difference in
1200 // physical line numbers from the query point and the line marker to the
1201 // total.
1202 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1203 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001205 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Chris Lattner137b6a62009-02-04 06:25:26 +00001207 // Handle virtual #include manipulation.
1208 if (Entry->IncludeOffset) {
1209 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1210 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1211 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001212 }
1213 }
1214
1215 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001216}
1217
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001218/// \brief Returns true if the given MacroID location points at the first
1219/// token of the macro instantiation.
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001220bool SourceManager::isAtStartOfMacroInstantiation(SourceLocation loc,
1221 const LangOptions &LangOpts) const {
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001222 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
1223
Argyrios Kyrtzidised37ab82011-06-24 17:28:26 +00001224 std::pair<FileID, unsigned> infoLoc = getDecomposedLoc(loc);
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001225 // FIXME: If the token comes from the macro token paste operator ('##')
1226 // this function will always return false;
Argyrios Kyrtzidised37ab82011-06-24 17:28:26 +00001227 if (infoLoc.second > 0)
1228 return false; // Does not point at the start of token.
1229
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001230 SourceLocation instLoc =
1231 getSLocEntry(infoLoc.first).getInstantiation().getInstantiationLocStart();
1232 if (instLoc.isFileID())
1233 return true; // No other macro instantiations, this is the first.
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001234
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001235 return isAtStartOfMacroInstantiation(instLoc, LangOpts);
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001236}
1237
1238/// \brief Returns true if the given MacroID location points at the last
1239/// token of the macro instantiation.
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001240bool SourceManager::isAtEndOfMacroInstantiation(SourceLocation loc,
1241 const LangOptions &LangOpts) const {
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001242 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
1243
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001244 SourceLocation spellLoc = getSpellingLoc(loc);
1245 unsigned tokLen = Lexer::MeasureTokenLength(spellLoc, *this, LangOpts);
1246 if (tokLen == 0)
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001247 return false;
1248
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001249 std::pair<FileID, unsigned> infoLoc = getDecomposedLoc(loc);
1250 unsigned FID = infoLoc.first.ID;
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001251
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +00001252 unsigned NextOffset;
1253 if (FID+1 == sloc_entry_size())
1254 NextOffset = getNextOffset();
1255 else
1256 NextOffset = getSLocEntry(FID+1).getOffset();
1257
1258 // FIXME: If the token comes from the macro token paste operator ('##')
1259 // or the stringify operator ('#') this function will always return false;
1260 assert(loc.getOffset() + tokLen < NextOffset);
1261 if (loc.getOffset() + tokLen < NextOffset-1)
1262 return false; // Does not point to the last token.
1263
1264 SourceLocation instLoc =
1265 getSLocEntry(infoLoc.first).getInstantiation().getInstantiationLocEnd();
1266 if (instLoc.isFileID())
1267 return true; // No other macro instantiations.
1268
1269 return isAtEndOfMacroInstantiation(instLoc, LangOpts);
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001270}
1271
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001272//===----------------------------------------------------------------------===//
1273// Other miscellaneous methods.
1274//===----------------------------------------------------------------------===//
1275
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001276/// \brief Retrieve the inode for the given file entry, if possible.
1277///
1278/// This routine involves a system call, and therefore should only be used
1279/// in non-performance-critical code.
1280static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1281 if (!File)
1282 return llvm::Optional<ino_t>();
1283
1284 struct stat StatBuf;
1285 if (::stat(File->getName(), &StatBuf))
1286 return llvm::Optional<ino_t>();
1287
1288 return StatBuf.st_ino;
1289}
1290
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001291/// \brief Get the source location for the given file:line:col triplet.
1292///
1293/// If the source file is included multiple times, the source location will
1294/// be based upon the first inclusion.
1295SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001296 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001297 assert(SourceFile && "Null source file!");
1298 assert(Line && Col && "Line and column should start from 1!");
1299
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001300 // Find the first file ID that corresponds to the given file.
1301 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001303 // First, check the main file ID, since it is common to look for a
1304 // location in the main file.
1305 llvm::Optional<ino_t> SourceFileInode;
1306 llvm::Optional<llvm::StringRef> SourceFileName;
1307 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001308 bool Invalid = false;
1309 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1310 if (Invalid)
1311 return SourceLocation();
1312
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001313 if (MainSLoc.isFile()) {
1314 const ContentCache *MainContentCache
1315 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001316 if (!MainContentCache) {
1317 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001318 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001319 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001320 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001321 // Fall back: check whether we have the same base name and inode
1322 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001323 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001324 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1325 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1326 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001327 if (SourceFileInode) {
1328 if (llvm::Optional<ino_t> MainFileInode
1329 = getActualFileInode(MainFile)) {
1330 if (*SourceFileInode == *MainFileInode) {
1331 FirstFID = MainFileID;
1332 SourceFile = MainFile;
1333 }
1334 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (FirstFID.isInvalid()) {
1342 // The location we're looking for isn't in the main file; look
1343 // through all of the source locations.
1344 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001345 bool Invalid = false;
1346 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1347 if (Invalid)
1348 return SourceLocation();
1349
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001350 if (SLoc.isFile() &&
1351 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001352 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001353 FirstFID = FileID::get(I);
1354 break;
1355 }
1356 }
1357 }
1358
1359 // If we haven't found what we want yet, try again, but this time stat()
1360 // each of the files in case the files have changed since we originally
1361 // parsed the file.
1362 if (FirstFID.isInvalid() &&
1363 (SourceFileName ||
1364 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1365 (SourceFileInode ||
1366 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001367 bool Invalid = false;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001368 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001369 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1370 if (Invalid)
1371 return SourceLocation();
1372
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001373 if (SLoc.isFile()) {
1374 const ContentCache *FileContentCache
1375 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001376 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001377 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001378 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1379 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1380 if (*SourceFileInode == *EntryInode) {
1381 FirstFID = FileID::get(I);
1382 SourceFile = Entry;
1383 break;
1384 }
1385 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001386 }
1387 }
1388 }
1389 }
1390
1391 if (FirstFID.isInvalid())
1392 return SourceLocation();
1393
1394 if (Line == 1 && Col == 1)
1395 return getLocForStartOfFile(FirstFID);
1396
1397 ContentCache *Content
1398 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1399 if (!Content)
1400 return SourceLocation();
1401
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001402 // If this is the first use of line information for this buffer, compute the
1403 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001404 if (Content->SourceLineCache == 0) {
1405 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001406 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001407 if (MyInvalid)
1408 return SourceLocation();
1409 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001410
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001411 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001412 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001413 if (Size > 0)
1414 --Size;
1415 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1416 }
1417
1418 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001419 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1420 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001421 unsigned i = 0;
1422
1423 // Check that the given column is valid.
1424 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1425 ++i;
1426 if (i < Col-1)
1427 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1428
Douglas Gregor4a160e12009-12-02 05:34:39 +00001429 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001430}
1431
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001432/// Given a decomposed source location, move it up the include/instantiation
1433/// stack to the parent source location. If this is possible, return the
1434/// decomposed version of the parent in Loc and return false. If Loc is the
1435/// top-level entry, return true and don't modify it.
1436static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1437 const SourceManager &SM) {
1438 SourceLocation UpperLoc;
1439 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1440 if (Entry.isInstantiation())
1441 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1442 else
1443 UpperLoc = Entry.getFile().getIncludeLoc();
1444
1445 if (UpperLoc.isInvalid())
1446 return true; // We reached the top.
1447
1448 Loc = SM.getDecomposedLoc(UpperLoc);
1449 return false;
1450}
1451
1452
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001453/// \brief Determines the order of 2 source locations in the translation unit.
1454///
1455/// \returns true if LHS source location comes before RHS, false otherwise.
1456bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1457 SourceLocation RHS) const {
1458 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1459 if (LHS == RHS)
1460 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001462 // If both locations are macro instantiations, the order of their offsets
1463 // reflect the order that the tokens, pointed to by these locations, were
1464 // instantiated (during parsing each token that is instantiated by a macro,
1465 // expands the SLocEntries).
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001466
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001467 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1468 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001470 // If the source locations are in the same file, just compare offsets.
1471 if (LOffs.first == ROffs.first)
1472 return LOffs.second < ROffs.second;
1473
1474 // If we are comparing a source location with multiple locations in the same
1475 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001476 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1477 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001479 // Okay, we missed in the cache, start updating the cache for this query.
1480 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001482 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001483 // find a common "ancestor". FileIDs build a tree-like structure that
1484 // reflects the #include hierarchy, and this algorithm needs to find the
1485 // nearest common ancestor between the two locations. For example, if you
1486 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1487 // a location in c.h, we need to find that their nearest common ancestor is
1488 // a.c, and compare the locations of the two #includes to find their relative
1489 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001490 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001491 // SourceManager assigns FileIDs in order of parsing. This means that an
1492 // includee always has a larger FileID than an includer. While you might
1493 // think that we could just compare the FileID's here, that doesn't work to
1494 // compare a point at the end of a.c with a point within c.h. Though c.h has
1495 // a larger FileID, we have to compare the include point of c.h to the
1496 // location in a.c.
1497 //
1498 // Despite not being able to directly compare FileID's, we can tell that a
1499 // larger FileID is necessarily more deeply nested than a lower one and use
1500 // this information to walk up the tree to the nearest common ancestor.
1501 do {
1502 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1503 // ROffs, walk up the #include chain.
1504 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001505 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001506 break; // We reached the top.
1507
Chris Lattner48296ba2010-05-07 05:51:13 +00001508 } else {
1509 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1510 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001511 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001512 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001513 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001514 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Chris Lattner48296ba2010-05-07 05:51:13 +00001516 // If we exited because we found a nearest common ancestor, compare the
1517 // locations within the common file and cache them.
1518 if (LOffs.first == ROffs.first) {
1519 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1520 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001521 }
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001523 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001524 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001525 // FIXME: We should rearrange the external interface so this simply never
1526 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001527 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1528
1529 // Zip both entries up to the top level record.
1530 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1531 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001532
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001533 // If exactly one location is a memory buffer, assume it precedes the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001534
1535 // Strip off macro instantation locations, going up to the top-level File
1536 // SLocEntry.
1537 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1538 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001539 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001540 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001542 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001543 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001544}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546/// PrintStats - Print statistics to stderr.
1547///
1548void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001549 llvm::errs() << "\n*** Source Manager Stats:\n";
1550 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1551 << " mem buffers mapped.\n";
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001552 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated ("
1553 << SLocEntryTable.capacity()*sizeof(SrcMgr::SLocEntry)
1554 << " bytes of capacity), "
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001555 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 unsigned NumLineNumsComputed = 0;
1558 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001559 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1560 NumLineNumsComputed += I->second->SourceLineCache != 0;
1561 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001564 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1565 << NumLineNumsComputed << " files with line #'s computed.\n";
1566 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1567 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001568}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001569
1570ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001571
1572/// Return the amount of memory used by memory buffers, breaking down
1573/// by heap-backed versus mmap'ed memory.
1574SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1575 size_t malloc_bytes = 0;
1576 size_t mmap_bytes = 0;
1577
1578 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1579 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1580 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1581 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1582 mmap_bytes += sized_mapped;
1583 break;
1584 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1585 malloc_bytes += sized_mapped;
1586 break;
1587 }
1588
1589 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1590}
1591