blob: 8190ca397ab39474fe2d9ebff64973fd021ac90b [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"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000020#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000022#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000023#include "llvm/Support/Path.h"
Ted Kremenek6e36c122011-07-27 18:41:16 +000024#include "llvm/Support/Capacity.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
Chandler Carruth3201f382011-07-26 05:17:23 +000043/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenekc16c2082009-01-06 01:55:26 +000045unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000047}
48
Ted Kremenekf61b8312011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57
58 const llvm::MemoryBuffer *buf = Buffer.getPointer();
59 return buf->getBufferKind();
60}
61
Ted Kremenekc16c2082009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000069}
70
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000071void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
72 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000073 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000074
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000075 if (shouldFreeBuffer())
76 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000077 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000078 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000079}
80
Douglas Gregor36c35ba2010-03-16 00:35:39 +000081const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000082 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000083 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000084 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000085 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000086 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000087 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000088 if (Invalid)
89 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000090
Chris Lattnerb088cd32010-11-23 08:50:03 +000091 return Buffer.getPointer();
92 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000093
Chris Lattnerb088cd32010-11-23 08:50:03 +000094 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000095 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000096
97 // If we were unable to open the file, then we are in an inconsistent
98 // situation where the content cache referenced a file which no longer
99 // exists. Most likely, we were using a stat cache with an invalid entry but
100 // the file could also have been removed during processing. Since we can't
101 // really deal with this situation, just create an empty buffer.
102 //
103 // FIXME: This is definitely not ideal, but our immediate clients can't
104 // currently handle returning a null entry here. Ideally we should detect
105 // that we are in an inconsistent situation and error out as quickly as
106 // possible.
107 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000109 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000110 "<invalid>"));
111 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000112 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000113 Ptr[i] = FillStr[i % FillStr.size()];
114
115 if (Diag.isDiagnosticInFlight())
116 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 else
119 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121
122 Buffer.setInt(Buffer.getInt() | InvalidFlag);
123
124 if (Invalid) *Invalid = true;
125 return Buffer.getPointer();
126 }
127
128 // Check that the file's size is the same as in the file entry (which may
129 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000130 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000131 if (Diag.isDiagnosticInFlight())
132 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000133 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000134 else
135 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000136 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000137
138 Buffer.setInt(Buffer.getInt() | InvalidFlag);
139 if (Invalid) *Invalid = true;
140 return Buffer.getPointer();
141 }
Eric Christopher156119d2011-04-09 00:01:04 +0000142
Chris Lattnerb088cd32010-11-23 08:50:03 +0000143 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000144 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000145 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000146 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000147 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000148 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
149 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
150 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
151 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
152 .StartsWith("\x2B\x2F\x76", "UTF-7")
153 .StartsWith("\xF7\x64\x4C", "UTF-1")
154 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
155 .StartsWith("\x0E\xFE\xFF", "SDSU")
156 .StartsWith("\xFB\xEE\x28", "BOCU-1")
157 .StartsWith("\x84\x31\x95\x33", "GB-18030")
158 .Default(0);
159
Eric Christopher156119d2011-04-09 00:01:04 +0000160 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000161 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000162 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000163 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000164 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000165
Douglas Gregorc8151082010-03-16 22:53:51 +0000166 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000167 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000168
169 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000170}
171
Chris Lattner5f9e2722011-07-23 10:55:15 +0000172unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000173 // Look up the filename in the string table, returning the pre-existing value
174 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000175 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000176 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000177 if (Entry.getValue() != ~0U)
178 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner5b9a5042009-01-26 07:57:50 +0000180 // Otherwise, assign this the next available ID.
181 Entry.setValue(FilenamesByID.size());
182 FilenamesByID.push_back(&Entry);
183 return FilenamesByID.size()-1;
184}
185
Chris Lattnerac50e342009-02-03 22:13:05 +0000186/// AddLineNote - Add a line note to the line table that indicates that there
187/// is a #line at the specified FID/Offset location which changes the presumed
188/// location to LineNo/FilenameID.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000189void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000190 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000191 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner23b5dc62009-02-04 00:40:31 +0000193 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner9d79eba2009-02-04 05:21:58 +0000196 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000197 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner9d79eba2009-02-04 05:21:58 +0000199 if (!Entries.empty()) {
200 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201 // that we are still in "foo.h".
202 if (FilenameID == -1)
203 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 // If we are after a line marker that switched us to system header mode, or
206 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000207 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000208 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattner137b6a62009-02-04 06:25:26 +0000211 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
212 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000213}
214
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215/// AddLineNote This is the same as the previous version of AddLineNote, but is
216/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
217/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
218/// this is a file exit. FileKind specifies whether this is a system header or
219/// extern C system header.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000220void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000221 unsigned LineNo, int FilenameID,
222 unsigned EntryExit,
223 SrcMgr::CharacteristicKind FileKind) {
224 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattner9d79eba2009-02-04 05:21:58 +0000226 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner9d79eba2009-02-04 05:21:58 +0000228 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229 "Adding line entries out of order!");
230
Chris Lattner137b6a62009-02-04 06:25:26 +0000231 unsigned IncludeOffset = 0;
232 if (EntryExit == 0) { // No #include stack change.
233 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234 } else if (EntryExit == 1) {
235 IncludeOffset = Offset-1;
236 } else if (EntryExit == 2) {
237 assert(!Entries.empty() && Entries.back().IncludeOffset &&
238 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattner137b6a62009-02-04 06:25:26 +0000240 // Get the include loc of the last entries' include loc as our include loc.
241 IncludeOffset = 0;
242 if (const LineEntry *PrevEntry =
243 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244 IncludeOffset = PrevEntry->IncludeOffset;
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner137b6a62009-02-04 06:25:26 +0000247 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
248 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000249}
250
251
Chris Lattner3cd949c2009-02-04 01:55:42 +0000252/// FindNearestLineEntry - Find the line entry nearest to FID that is before
253/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000254const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000255 unsigned Offset) {
256 const std::vector<LineEntry> &Entries = LineEntries[FID];
257 assert(!Entries.empty() && "No #line entries for this FID after all!");
258
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000259 // It is very common for the query to be after the last #line, check this
260 // first.
261 if (Entries.back().FileOffset <= Offset)
262 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000263
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000264 // Do a binary search to find the maximal element that is still before Offset.
265 std::vector<LineEntry>::const_iterator I =
266 std::upper_bound(Entries.begin(), Entries.end(), Offset);
267 if (I == Entries.begin()) return 0;
268 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000269}
Chris Lattnerac50e342009-02-03 22:13:05 +0000270
Douglas Gregorbd945002009-04-13 16:31:14 +0000271/// \brief Add a new line entry that has already been encoded into
272/// the internal representation of the line table.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000273void LineTableInfo::AddEntry(int FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000274 const std::vector<LineEntry> &Entries) {
275 LineEntries[FID] = Entries;
276}
Chris Lattnerac50e342009-02-03 22:13:05 +0000277
Chris Lattner5b9a5042009-01-26 07:57:50 +0000278/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000279///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000280unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000283 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000284}
285
286
Chris Lattner4c4ea172009-02-03 21:52:55 +0000287/// AddLineNote - Add a line note to the line table for the FileID and offset
288/// specified by Loc. If FilenameID is -1, it is considered to be
289/// unspecified.
290void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291 int FilenameID) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000292 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Douglas Gregore23ac652011-04-20 00:21:03 +0000294 bool Invalid = false;
295 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
296 if (!Entry.isFile() || Invalid)
297 return;
298
299 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000300
301 // Remember that this file has #line directives now if it doesn't already.
302 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnerac50e342009-02-03 22:13:05 +0000304 if (LineTable == 0)
305 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000306 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000307}
308
Chris Lattner9d79eba2009-02-04 05:21:58 +0000309/// AddLineNote - Add a GNU line marker to the line table.
310void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311 int FilenameID, bool IsFileEntry,
312 bool IsFileExit, bool IsSystemHeader,
313 bool IsExternCHeader) {
314 // If there is no filename and no flags, this is treated just like a #line,
315 // which does not change the flags of the previous line marker.
316 if (FilenameID == -1) {
317 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
318 "Can't set flags without setting the filename!");
319 return AddLineNote(Loc, LineNo, FilenameID);
320 }
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000322 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000323
324 bool Invalid = false;
325 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
326 if (!Entry.isFile() || Invalid)
327 return;
328
329 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner9d79eba2009-02-04 05:21:58 +0000331 // Remember that this file has #line directives now if it doesn't already.
332 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner9d79eba2009-02-04 05:21:58 +0000334 if (LineTable == 0)
335 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner9d79eba2009-02-04 05:21:58 +0000337 SrcMgr::CharacteristicKind FileKind;
338 if (IsExternCHeader)
339 FileKind = SrcMgr::C_ExternCSystem;
340 else if (IsSystemHeader)
341 FileKind = SrcMgr::C_System;
342 else
343 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner9d79eba2009-02-04 05:21:58 +0000345 unsigned EntryExit = 0;
346 if (IsFileEntry)
347 EntryExit = 1;
348 else if (IsFileExit)
349 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner9d79eba2009-02-04 05:21:58 +0000351 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
352 EntryExit, FileKind);
353}
354
Douglas Gregorbd945002009-04-13 16:31:14 +0000355LineTableInfo &SourceManager::getLineTable() {
356 if (LineTable == 0)
357 LineTable = new LineTableInfo();
358 return *LineTable;
359}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000360
Chris Lattner23b5dc62009-02-04 00:40:31 +0000361//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000362// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000363//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000364
Chris Lattner39b49bc2010-11-23 08:35:12 +0000365SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000366 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000367 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000368 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000369 clearIDTables();
370 Diag.setSourceManager(this);
371}
372
Chris Lattner5b9a5042009-01-26 07:57:50 +0000373SourceManager::~SourceManager() {
374 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000376 // Delete FileEntry objects corresponding to content caches. Since the actual
377 // content cache objects are bump pointer allocated, we just have to run the
378 // dtors, but we call the deallocate method for completeness.
379 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
380 MemBufferInfos[i]->~ContentCache();
381 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
382 }
383 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
385 I->second->~ContentCache();
386 ContentCacheAlloc.Deallocate(I->second);
387 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000388
389 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000390}
391
392void SourceManager::clearIDTables() {
393 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000394 LocalSLocEntryTable.clear();
395 LoadedSLocEntryTable.clear();
396 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000397 LastLineNoFileIDQuery = FileID();
398 LastLineNoContentCache = 0;
399 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner5b9a5042009-01-26 07:57:50 +0000401 if (LineTable)
402 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chandler Carruth3201f382011-07-26 05:17:23 +0000404 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000405 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000406 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000407 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000408}
409
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000410/// getOrCreateContentCache - Create or return a cached ContentCache for the
411/// specified file.
412const ContentCache *
413SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000417 ContentCache *&Entry = FileInfos[FileEnt];
418 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner00282d62009-02-03 07:41:46 +0000420 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
421 // so that FileInfo can use the low 3 bits of the pointer for its own
422 // nefarious purposes.
423 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
424 EntryAlign = std::max(8U, EntryAlign);
425 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000426
427 // If the file contents are overridden with contents from another file,
428 // pass that file to ContentCache.
429 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430 overI = OverriddenFiles.find(FileEnt);
431 if (overI == OverriddenFiles.end())
432 new (Entry) ContentCache(FileEnt);
433 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000434 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
435 : overI->second,
436 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000437
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000438 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000439}
440
441
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000442/// createMemBufferContentCache - Create a new ContentCache for the specified
443/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000444const ContentCache*
445SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000446 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
447 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
448 // the pointer for its own nefarious purposes.
449 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
450 EntryAlign = std::max(8U, EntryAlign);
451 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000452 new (Entry) ContentCache();
453 MemBufferInfos.push_back(Entry);
454 Entry->setBuffer(Buffer);
455 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000456}
457
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000458std::pair<int, unsigned>
459SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
460 unsigned TotalSize) {
461 assert(ExternalSLocEntries && "Don't have an external sloc source");
462 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
463 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
464 CurrentLoadedOffset -= TotalSize;
465 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
466 int ID = LoadedSLocEntryTable.size();
467 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000468}
469
Douglas Gregore23ac652011-04-20 00:21:03 +0000470/// \brief As part of recovering from missing or changed content, produce a
471/// fake, non-empty buffer.
472const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
473 if (!FakeBufferForRecovery)
474 FakeBufferForRecovery
475 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
476
477 return FakeBufferForRecovery;
478}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000479
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000480//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000481// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000482//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000483
Dan Gohman3f86b782010-08-26 21:27:06 +0000484/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000485/// include position. This works regardless of whether the ContentCache
486/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000487FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000488 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000489 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000490 int LoadedID, unsigned LoadedOffset) {
491 if (LoadedID < 0) {
492 assert(LoadedID != -1 && "Loading sentinel FileID");
493 unsigned Index = unsigned(-LoadedID) - 2;
494 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
495 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
496 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
497 FileInfo::get(IncludePos, File, FileCharacter));
498 SLocEntryLoaded[Index] = true;
499 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000500 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000501 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
502 FileInfo::get(IncludePos, File,
503 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000504 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000505 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
506 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
507 "Ran out of source locations!");
508 // We do a +1 here because we want a SourceLocation that means "the end of the
509 // file", e.g. for the "no newline at the end of the file" diagnostic.
510 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000512 // Set LastFileIDLookup to the newly created file. The next getFileID call is
513 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000514 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000515 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000516}
517
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000518SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000519SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
520 SourceLocation ExpansionLoc,
521 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000522 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
523 ExpansionLoc);
524 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000525}
526
527SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000528SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
529 SourceLocation ExpansionLocStart,
530 SourceLocation ExpansionLocEnd,
531 unsigned TokLength,
532 int LoadedID,
533 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000534 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
535 ExpansionLocEnd);
536 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000537}
538
539SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000540SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000541 unsigned TokLength,
542 int LoadedID,
543 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000544 if (LoadedID < 0) {
545 assert(LoadedID != -1 && "Loading sentinel FileID");
546 unsigned Index = unsigned(-LoadedID) - 2;
547 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
548 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000549 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000550 SLocEntryLoaded[Index] = true;
551 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000552 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000553 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000554 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
555 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
556 "Ran out of source locations!");
557 // See createFileID for that +1.
558 NextLocalOffset += TokLength + 1;
559 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000560}
561
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000562const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000563SourceManager::getMemoryBufferForFile(const FileEntry *File,
564 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000565 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000566 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000567 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000568}
569
Dan Gohman0d06e992010-10-26 20:47:28 +0000570void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000571 const llvm::MemoryBuffer *Buffer,
572 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000573 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000574 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000575
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000576 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000577}
578
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000579void SourceManager::overrideFileContents(const FileEntry *SourceFile,
580 const FileEntry *NewFile) {
581 assert(SourceFile->getSize() == NewFile->getSize() &&
582 "Different sizes, use the FileManager to create a virtual file with "
583 "the correct size");
584 assert(FileInfos.count(SourceFile) == 0 &&
585 "This function should be called at the initialization stage, before "
586 "any parsing occurs.");
587 OverriddenFiles[SourceFile] = NewFile;
588}
589
Chris Lattner5f9e2722011-07-23 10:55:15 +0000590StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000591 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000592 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000593 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000594 if (Invalid)
595 *Invalid = true;
596 return "<<<<<INVALID SOURCE LOCATION>>>>>";
597 }
598
599 const llvm::MemoryBuffer *Buf
600 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
601 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000602 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000603 *Invalid = MyInvalid;
604
605 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000606 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000607
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000608 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000609}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000610
Chris Lattner23b5dc62009-02-04 00:40:31 +0000611//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000612// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000613//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000614
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000615/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000616///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000617/// This is the cache-miss path of getFileID. Not as hot as that function, but
618/// still very important. It is responsible for finding the entry in the
619/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000620FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000621 if (!SLocOffset)
622 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000624 // Now it is time to search for the correct file. See where the SLocOffset
625 // sits in the global view and consult local or loaded buffers for it.
626 if (SLocOffset < NextLocalOffset)
627 return getFileIDLocal(SLocOffset);
628 return getFileIDLoaded(SLocOffset);
629}
630
631/// \brief Return the FileID for a SourceLocation with a low offset.
632///
633/// This function knows that the SourceLocation is in a local buffer, not a
634/// loaded one.
635FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
636 assert(SLocOffset < NextLocalOffset && "Bad function choice");
637
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000638 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000639 // behavior: 1) a lot of searched FileID's are "near" the cached file
640 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000641 // completely random and may be a very long way away.
642 //
643 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
644 // then we fall back to a less cache efficient, but more scalable, binary
645 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000647 // See if this is near the file point - worst case we start scanning from the
648 // most newly created FileID.
649 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000651 if (LastFileIDLookup.ID < 0 ||
652 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000653 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000654 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000655 } else {
656 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000657 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000658 }
659
660 // Find the FileID that contains this. "I" is an iterator that points to a
661 // FileID whose offset is known to be larger than SLocOffset.
662 unsigned NumProbes = 0;
663 while (1) {
664 --I;
665 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000666 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000667
Chandler Carruth3201f382011-07-26 05:17:23 +0000668 // If this isn't an expansion, remember it. We have good locality across
669 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000670 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000671 LastFileIDLookup = Res;
672 NumLinearScans += NumProbes+1;
673 return Res;
674 }
675 if (++NumProbes == 8)
676 break;
677 }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000679 // Convert "I" back into an index. We know that it is an entry whose index is
680 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000681 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000682 // LessIndex - This is the lower bound of the range that we're searching.
683 // We know that the offset corresponding to the FileID is is less than
684 // SLocOffset.
685 unsigned LessIndex = 0;
686 NumProbes = 0;
687 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000688 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000689 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000690 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000691 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.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000704 // FIXME: This could be made faster by using a function that's aware of
705 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000706 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707 FileID Res = FileID::get(MiddleIndex);
708
Chandler Carruth17287622011-07-26 04:56:51 +0000709 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000710 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000711 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000712 LastFileIDLookup = Res;
713 NumBinaryProbes += NumProbes;
714 return Res;
715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000717 // Otherwise, move the low-side up to the middle index.
718 LessIndex = MiddleIndex;
719 }
720}
721
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000722/// \brief Return the FileID for a SourceLocation with a high offset.
723///
724/// This function knows that the SourceLocation is in a loaded buffer, not a
725/// local one.
726FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
727 assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
728
729 // Essentially the same as the local case, but the loaded array is sorted
730 // in the other direction.
731
732 // First do a linear scan from the last lookup position, if possible.
733 unsigned I;
734 int LastID = LastFileIDLookup.ID;
735 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
736 I = 0;
737 else
738 I = (-LastID - 2) + 1;
739
740 unsigned NumProbes;
741 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
742 // Make sure the entry is loaded!
743 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
744 if (E.getOffset() <= SLocOffset) {
745 FileID Res = FileID::get(-int(I) - 2);
746
Chandler Carruth17287622011-07-26 04:56:51 +0000747 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000748 LastFileIDLookup = Res;
749 NumLinearScans += NumProbes + 1;
750 return Res;
751 }
752 }
753
754 // Linear scan failed. Do the binary search. Note the reverse sorting of the
755 // table: GreaterIndex is the one where the offset is greater, which is
756 // actually a lower index!
757 unsigned GreaterIndex = I;
758 unsigned LessIndex = LoadedSLocEntryTable.size();
759 NumProbes = 0;
760 while (1) {
761 ++NumProbes;
762 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
763 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
764
765 ++NumProbes;
766
767 if (E.getOffset() > SLocOffset) {
768 GreaterIndex = MiddleIndex;
769 continue;
770 }
771
772 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
773 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000774 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000775 LastFileIDLookup = Res;
776 NumBinaryProbes += NumProbes;
777 return Res;
778 }
779
780 LessIndex = MiddleIndex;
781 }
782}
783
Chris Lattneraddb7972009-01-26 20:04:19 +0000784SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000785getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000786 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000787 // Note: If Loc indicates an offset into a token that came from a macro
788 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000789 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000790 // location is the macro invocation, which the offset has nothing to do
791 // with. This is unlike when we get the spelling loc, because the offset
792 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000793 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000794 } while (!Loc.isFileID());
795
796 return Loc;
797}
798
799SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
800 do {
801 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000802 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattneraddb7972009-01-26 20:04:19 +0000803 Loc = Loc.getFileLocWithOffset(LocInfo.second);
804 } while (!Loc.isFileID());
805 return Loc;
806}
807
808
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000809std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000810SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000811 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000812 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000813 FileID FID;
814 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000815 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000816 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000817 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000819 FID = getFileID(Loc);
820 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000821 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000822 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000824 return std::make_pair(FID, Offset);
825}
826
827std::pair<FileID, unsigned>
828SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
829 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000830 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000831 FileID FID;
832 SourceLocation Loc;
833 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000834 Loc = E->getExpansion().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000836 FID = getFileID(Loc);
837 E = &getSLocEntry(FID);
838 Offset += Loc.getOffset()-E->getOffset();
839 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000841 return std::make_pair(FID, Offset);
842}
843
Chris Lattner387616e2009-02-17 08:04:48 +0000844/// getImmediateSpellingLoc - Given a SourceLocation object, return the
845/// spelling location referenced by the ID. This is the first level down
846/// towards the place where the characters that make up the lexed token can be
847/// found. This should not generally be used by clients.
848SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
849 if (Loc.isFileID()) return Loc;
850 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000851 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattner387616e2009-02-17 08:04:48 +0000852 return Loc.getFileLocWithOffset(LocInfo.second);
853}
854
855
Chandler Carruth3201f382011-07-26 05:17:23 +0000856/// getImmediateExpansionRange - Loc is required to be an expansion location.
857/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000858std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000859SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000860 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000861 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000862 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000863}
864
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000865/// getExpansionRange - Given a SourceLocation object, return the range of
866/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000867std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000868SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000869 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Chris Lattner66781332009-02-15 21:26:50 +0000871 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000872 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chandler Carruth3201f382011-07-26 05:17:23 +0000874 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000875 // points.
876 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000877 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +0000878 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000879 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +0000880 return Res;
881}
882
Chandler Carruth96d35892011-07-26 03:03:00 +0000883bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000884 if (!Loc.isMacroID()) return false;
885
886 FileID FID = getFileID(Loc);
887 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
Chandler Carruth17287622011-07-26 04:56:51 +0000888 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000889 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000890}
Chris Lattnere7fb4842009-02-15 20:52:18 +0000891
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000892
893//===----------------------------------------------------------------------===//
894// Queries about the code at a SourceLocation.
895//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
897/// getCharacterData - Return a pointer to the start of the specified location
898/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000899const char *SourceManager::getCharacterData(SourceLocation SL,
900 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 // Note that this is a hot function in the getSpelling() path, which is
902 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000903 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Ted Kremenekc16c2082009-01-06 01:55:26 +0000905 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000906 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000907 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
908 if (CharDataInvalid || !Entry.isFile()) {
909 if (Invalid)
910 *Invalid = true;
911
912 return "<<<<INVALID BUFFER>>>>";
913 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000914 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000915 = Entry.getFile().getContentCache()
916 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000917 if (Invalid)
918 *Invalid = CharDataInvalid;
919 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000920}
921
Reid Spencer5f016e22007-07-11 17:01:13 +0000922
Chris Lattner9dc1f532007-07-20 16:37:10 +0000923/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000924/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000925unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
926 bool *Invalid) const {
927 bool MyInvalid = false;
928 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
929 if (Invalid)
930 *Invalid = MyInvalid;
931
932 if (MyInvalid)
933 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 unsigned LineStart = FilePos;
936 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
937 --LineStart;
938 return FilePos-LineStart+1;
939}
940
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000941// isInvalid - Return the result of calling loc.isInvalid(), and
942// if Invalid is not null, set its value to same.
943static bool isInvalid(SourceLocation Loc, bool *Invalid) {
944 bool MyInvalid = Loc.isInvalid();
945 if (Invalid)
946 *Invalid = MyInvalid;
947 return MyInvalid;
948}
949
Douglas Gregor50f6af72010-03-16 05:20:39 +0000950unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
951 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000952 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000953 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000954 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000955}
956
Chandler Carrutha77c0312011-07-25 20:57:57 +0000957unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
958 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000959 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000960 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000961 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000962}
963
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000964unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
965 bool *Invalid) const {
966 if (isInvalid(Loc, Invalid)) return 0;
967 return getPresumedLoc(Loc).getColumn();
968}
969
Chandler Carruth14bd9652010-10-23 08:44:57 +0000970static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000971ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
972 llvm::BumpPtrAllocator &Alloc,
973 const SourceManager &SM, bool &Invalid);
974static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
975 llvm::BumpPtrAllocator &Alloc,
976 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000977 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000978 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
979 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000980 if (Invalid)
981 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000983 // Find the file offsets of all of the *physical* source lines. This does
984 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000985 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000987 // Line #1 starts at char 0.
988 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000990 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
991 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
992 unsigned Offs = 0;
993 while (1) {
994 // Skip over the contents of the line.
995 // TODO: Vectorize this? This is very performance sensitive for programs
996 // with lots of diagnostics and in -E mode.
997 const unsigned char *NextBuf = (const unsigned char *)Buf;
998 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
999 ++NextBuf;
1000 Offs += NextBuf-Buf;
1001 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001003 if (Buf[0] == '\n' || Buf[0] == '\r') {
1004 // If this is \n\r or \r\n, skip both characters.
1005 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1006 ++Offs, ++Buf;
1007 ++Offs, ++Buf;
1008 LineOffsets.push_back(Offs);
1009 } else {
1010 // Otherwise, this is a null. If end of file, exit.
1011 if (Buf == End) break;
1012 // Otherwise, skip the null.
1013 ++Offs, ++Buf;
1014 }
1015 }
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001017 // Copy the offsets into the FileInfo structure.
1018 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001019 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001020 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1021}
Reid Spencer5f016e22007-07-11 17:01:13 +00001022
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001023/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001024/// for the position indicated. This requires building and caching a table of
1025/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1026/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001027unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1028 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001029 if (FID.isInvalid()) {
1030 if (Invalid)
1031 *Invalid = true;
1032 return 1;
1033 }
1034
Chris Lattner2b2453a2009-01-17 06:22:33 +00001035 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001036 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001037 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001038 else {
1039 bool MyInvalid = false;
1040 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1041 if (MyInvalid || !Entry.isFile()) {
1042 if (Invalid)
1043 *Invalid = true;
1044 return 1;
1045 }
1046
1047 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1048 }
1049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001051 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001052 if (Content->SourceLineCache == 0) {
1053 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001054 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001055 if (Invalid)
1056 *Invalid = MyInvalid;
1057 if (MyInvalid)
1058 return 1;
1059 } else if (Invalid)
1060 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001061
1062 // Okay, we know we have a line number table. Do a binary search to find the
1063 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001064 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001065 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001066 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner30fc9332009-02-04 01:06:56 +00001068 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001069
Daniel Dunbar4106d692009-05-18 17:30:52 +00001070 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001072 //
1073 // If it is worth being optimized, then in my opinion it could be more
1074 // performant, simpler, and more obviously correct by just "galloping" outward
1075 // from the queried file position. In fact, this could be incorporated into a
1076 // generic algorithm such as lower_bound_with_hint.
1077 //
1078 // If someone gives me a test case where this matters, and I will do it! - DWD
1079
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001080 // If the previous query was to the same file, we know both the file pos from
1081 // that query and the line number returned. This allows us to narrow the
1082 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001083 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001084 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001085 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001086 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001088 // The query is likely to be nearby the previous one. Here we check to
1089 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1090 // where big comment blocks and vertical whitespace eat up lines but
1091 // contribute no tokens.
1092 if (SourceLineCache+5 < SourceLineCacheEnd) {
1093 if (SourceLineCache[5] > QueriedFilePos)
1094 SourceLineCacheEnd = SourceLineCache+5;
1095 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1096 if (SourceLineCache[10] > QueriedFilePos)
1097 SourceLineCacheEnd = SourceLineCache+10;
1098 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1099 if (SourceLineCache[20] > QueriedFilePos)
1100 SourceLineCacheEnd = SourceLineCache+20;
1101 }
1102 }
1103 }
1104 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001105 if (LastLineNoResult < Content->NumLines)
1106 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001107 }
1108 }
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001110 // If the spread is large, do a "radix" test as our initial guess, based on
1111 // the assumption that lines average to approximately the same length.
1112 // NOTE: This is currently disabled, as it does not appear to be profitable in
1113 // initial measurements.
1114 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001115 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001117 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001118 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001120 // Check for -10 and +10 lines.
1121 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1122 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1123
1124 // If the computed lower bound is less than the query location, move it in.
1125 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1126 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1127 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001129 // If the computed upper bound is greater than the query location, move it.
1130 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1131 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1132 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1133 }
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001135 unsigned *Pos
1136 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001137 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Chris Lattner30fc9332009-02-04 01:06:56 +00001139 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001140 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001141 LastLineNoFilePos = QueriedFilePos;
1142 LastLineNoResult = LineNo;
1143 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001144}
1145
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001146unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1147 bool *Invalid) const {
1148 if (isInvalid(Loc, Invalid)) return 0;
1149 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1150 return getLineNumber(LocInfo.first, LocInfo.second);
1151}
Chandler Carruth64211622011-07-25 21:09:52 +00001152unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1153 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001154 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001155 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001156 return getLineNumber(LocInfo.first, LocInfo.second);
1157}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001158unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001159 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001160 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001161 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001162}
1163
Chris Lattner6b306672009-02-04 05:33:01 +00001164/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001165/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001166/// header, or an "implicit extern C" system header.
1167///
1168/// This state can be modified with flags on GNU linemarker directives like:
1169/// # 4 "foo.h" 3
1170/// which changes all source locations in the current file after that to be
1171/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001172SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001173SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1174 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001175 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001176 bool Invalid = false;
1177 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1178 if (Invalid || !SEntry.isFile())
1179 return C_User;
1180
1181 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001182
1183 // If there are no #line directives in this file, just return the whole-file
1184 // state.
1185 if (!FI.hasLineDirectives())
1186 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Chris Lattner6b306672009-02-04 05:33:01 +00001188 assert(LineTable && "Can't have linetable entries without a LineTable!");
1189 // See if there is a #line directive before the location.
1190 const LineEntry *Entry =
1191 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Chris Lattner6b306672009-02-04 05:33:01 +00001193 // If this is before the first line marker, use the file characteristic.
1194 if (!Entry)
1195 return FI.getFileCharacteristic();
1196
1197 return Entry->FileKind;
1198}
1199
Chris Lattnerbff5c512009-02-17 08:39:06 +00001200/// Return the filename or buffer identifier of the buffer the location is in.
1201/// Note that this name does not respect #line directives. Use getPresumedLoc
1202/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001203const char *SourceManager::getBufferName(SourceLocation Loc,
1204 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001205 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Douglas Gregor50f6af72010-03-16 05:20:39 +00001207 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001208}
1209
Chris Lattner30fc9332009-02-04 01:06:56 +00001210
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001211/// getPresumedLoc - This method returns the "presumed" location of a
1212/// SourceLocation specifies. A "presumed location" can be modified by #line
1213/// or GNU line marker directives. This provides a view on the data that a
1214/// user should see in diagnostics, for example.
1215///
Chandler Carruth3201f382011-07-26 05:17:23 +00001216/// Note that a presumed location is always given as the expansion point of an
1217/// expansion location, not at the spelling location.
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001218PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1219 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chandler Carruth3201f382011-07-26 05:17:23 +00001221 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001222 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Douglas Gregore23ac652011-04-20 00:21:03 +00001224 bool Invalid = false;
1225 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1226 if (Invalid || !Entry.isFile())
1227 return PresumedLoc();
1228
1229 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001230 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Chris Lattner3cd949c2009-02-04 01:55:42 +00001232 // To get the source name, first consult the FileEntry (if one exists)
1233 // before the MemBuffer as this will avoid unnecessarily paging in the
1234 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001235 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001236 if (C->OrigEntry)
1237 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001238 else
1239 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001240
Douglas Gregorc417fa02010-11-02 00:39:22 +00001241 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1242 if (Invalid)
1243 return PresumedLoc();
1244 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1245 if (Invalid)
1246 return PresumedLoc();
1247
Chris Lattner3cd949c2009-02-04 01:55:42 +00001248 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner3cd949c2009-02-04 01:55:42 +00001250 // If we have #line directives in this file, update and overwrite the physical
1251 // location info if appropriate.
1252 if (FI.hasLineDirectives()) {
1253 assert(LineTable && "Can't have linetable entries without a LineTable!");
1254 // See if there is a #line directive before this. If so, get it.
1255 if (const LineEntry *Entry =
1256 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001257 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001258 if (Entry->FilenameID != -1)
1259 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001260
1261 // Use the line number specified by the LineEntry. This line number may
1262 // be multiple lines down from the line entry. Add the difference in
1263 // physical line numbers from the query point and the line marker to the
1264 // total.
1265 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1266 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001268 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattner137b6a62009-02-04 06:25:26 +00001270 // Handle virtual #include manipulation.
1271 if (Entry->IncludeOffset) {
1272 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1273 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1274 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001275 }
1276 }
1277
1278 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001279}
1280
1281//===----------------------------------------------------------------------===//
1282// Other miscellaneous methods.
1283//===----------------------------------------------------------------------===//
1284
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001285/// \brief Retrieve the inode for the given file entry, if possible.
1286///
1287/// This routine involves a system call, and therefore should only be used
1288/// in non-performance-critical code.
1289static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1290 if (!File)
1291 return llvm::Optional<ino_t>();
1292
1293 struct stat StatBuf;
1294 if (::stat(File->getName(), &StatBuf))
1295 return llvm::Optional<ino_t>();
1296
1297 return StatBuf.st_ino;
1298}
1299
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001300/// \brief Get the source location for the given file:line:col triplet.
1301///
1302/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001303/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001304SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1305 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001306 assert(SourceFile && "Null source file!");
1307 assert(Line && Col && "Line and column should start from 1!");
1308
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001309 // Find the first file ID that corresponds to the given file.
1310 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001312 // First, check the main file ID, since it is common to look for a
1313 // location in the main file.
1314 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001315 llvm::Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001316 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001317 bool Invalid = false;
1318 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1319 if (Invalid)
1320 return SourceLocation();
1321
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001322 if (MainSLoc.isFile()) {
1323 const ContentCache *MainContentCache
1324 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001325 if (!MainContentCache) {
1326 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001327 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001328 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001329 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001330 // Fall back: check whether we have the same base name and inode
1331 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001332 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001333 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1334 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1335 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001336 if (SourceFileInode) {
1337 if (llvm::Optional<ino_t> MainFileInode
1338 = getActualFileInode(MainFile)) {
1339 if (*SourceFileInode == *MainFileInode) {
1340 FirstFID = MainFileID;
1341 SourceFile = MainFile;
1342 }
1343 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001344 }
1345 }
1346 }
1347 }
1348 }
1349
1350 if (FirstFID.isInvalid()) {
1351 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001352 // through all of the local source locations.
1353 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001354 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001355 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001356 if (Invalid)
1357 return SourceLocation();
1358
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001359 if (SLoc.isFile() &&
1360 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001361 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001362 FirstFID = FileID::get(I);
1363 break;
1364 }
1365 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001366 // If that still didn't help, try the modules.
1367 if (FirstFID.isInvalid()) {
1368 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1369 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1370 if (SLoc.isFile() &&
1371 SLoc.getFile().getContentCache() &&
1372 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1373 FirstFID = FileID::get(-int(I) - 2);
1374 break;
1375 }
1376 }
1377 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001378 }
1379
1380 // If we haven't found what we want yet, try again, but this time stat()
1381 // each of the files in case the files have changed since we originally
1382 // parsed the file.
1383 if (FirstFID.isInvalid() &&
1384 (SourceFileName ||
1385 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1386 (SourceFileInode ||
1387 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001388 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001389 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1390 FileID IFileID;
1391 IFileID.ID = I;
1392 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001393 if (Invalid)
1394 return SourceLocation();
1395
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001396 if (SLoc.isFile()) {
1397 const ContentCache *FileContentCache
1398 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001399 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001400 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001401 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1402 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1403 if (*SourceFileInode == *EntryInode) {
1404 FirstFID = FileID::get(I);
1405 SourceFile = Entry;
1406 break;
1407 }
1408 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001409 }
1410 }
1411 }
1412 }
1413
1414 if (FirstFID.isInvalid())
1415 return SourceLocation();
1416
1417 if (Line == 1 && Col == 1)
1418 return getLocForStartOfFile(FirstFID);
1419
1420 ContentCache *Content
1421 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1422 if (!Content)
1423 return SourceLocation();
1424
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001425 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001426 // SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001427 if (Content->SourceLineCache == 0) {
1428 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001429 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001430 if (MyInvalid)
1431 return SourceLocation();
1432 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001433
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001434 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001435 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001436 if (Size > 0)
1437 --Size;
1438 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1439 }
1440
1441 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001442 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1443 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001444 unsigned i = 0;
1445
1446 // Check that the given column is valid.
1447 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1448 ++i;
1449 if (i < Col-1)
1450 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1451
Douglas Gregor4a160e12009-12-02 05:34:39 +00001452 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001453}
1454
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001455/// \brief If \arg Loc points inside a function macro argument, the returned
1456/// location will be the macro location in which the argument was expanded.
1457/// If a macro argument is used multiple times, the expanded location will
1458/// be at the first expansion of the argument.
1459/// e.g.
1460/// MY_MACRO(foo);
1461/// ^
1462/// Passing a file location pointing at 'foo', will yield a macro location
1463/// where 'foo' was expanded into.
1464SourceLocation SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) {
1465 if (Loc.isInvalid())
1466 return Loc;
1467
1468 FileID FID = getFileID(Loc);
1469 if (FID.isInvalid())
1470 return Loc;
1471
1472 int ID = FID.ID;
1473 while (1) {
1474 ++ID;
1475 // Stop if there are no more FileIDs to check.
1476 if (ID > 0) {
1477 if (unsigned(ID) >= local_sloc_entry_size())
1478 return Loc;
1479 } else if (ID == -1) {
1480 return Loc;
1481 }
1482
1483 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
1484 if (Entry.isFile()) {
1485 if (Entry.getFile().getIncludeLoc().isValid() &&
1486 !isBeforeInTranslationUnit(Entry.getFile().getIncludeLoc(), Loc))
1487 return Loc;
1488 continue;
1489 }
1490
1491 if (isBeforeInTranslationUnit(Loc,
1492 Entry.getExpansion().getExpansionLocStart()))
1493 return Loc;
1494 if (!Entry.getExpansion().isMacroArgExpansion())
1495 continue;
1496
1497 // This is a macro argument expansion. See if Loc points in the argument
1498 // that was lexed.
1499
1500 SourceLocation SpellLoc = Entry.getExpansion().getSpellingLoc();
1501 unsigned NextOffset;
1502 if (ID > 0) {
1503 if (unsigned(ID+1) == local_sloc_entry_size())
1504 NextOffset = getNextLocalOffset();
1505 else
1506 NextOffset = getLocalSLocEntry(ID+1).getOffset();
1507 } else {
1508 if (ID+1 == -1)
1509 NextOffset = MaxLoadedOffset;
1510 else
1511 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1512 }
1513 unsigned EntrySize = NextOffset - Entry.getOffset() - 1;
1514 unsigned BeginOffs = SpellLoc.getOffset();
1515 unsigned EndOffs = BeginOffs + EntrySize;
1516 if (BeginOffs <= Loc.getOffset() && Loc.getOffset() < EndOffs) {
1517 SourceLocation ExpandLoc = SourceLocation::getMacroLoc(Entry.getOffset());
1518 // Replace current Loc with the expanded location and continue.
1519 // The expanded argument may end up being passed to another function macro
1520 // and relexed again.
1521 Loc = ExpandLoc.getFileLocWithOffset(Loc.getOffset()-BeginOffs);
1522 }
1523 }
1524}
1525
Chandler Carruth3201f382011-07-26 05:17:23 +00001526/// Given a decomposed source location, move it up the include/expansion stack
1527/// to the parent source location. If this is possible, return the decomposed
1528/// version of the parent in Loc and return false. If Loc is the top-level
1529/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001530static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1531 const SourceManager &SM) {
1532 SourceLocation UpperLoc;
1533 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
Chandler Carruth17287622011-07-26 04:56:51 +00001534 if (Entry.isExpansion())
1535 UpperLoc = Entry.getExpansion().getExpansionLocStart();
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001536 else
1537 UpperLoc = Entry.getFile().getIncludeLoc();
1538
1539 if (UpperLoc.isInvalid())
1540 return true; // We reached the top.
1541
1542 Loc = SM.getDecomposedLoc(UpperLoc);
1543 return false;
1544}
1545
1546
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001547/// \brief Determines the order of 2 source locations in the translation unit.
1548///
1549/// \returns true if LHS source location comes before RHS, false otherwise.
1550bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1551 SourceLocation RHS) const {
1552 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1553 if (LHS == RHS)
1554 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001556 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1557 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001559 // If the source locations are in the same file, just compare offsets.
1560 if (LOffs.first == ROffs.first)
1561 return LOffs.second < ROffs.second;
1562
1563 // If we are comparing a source location with multiple locations in the same
1564 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001565 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1566 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001568 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001569 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
1570 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001572 // We need to find the common ancestor. The only way of doing this is to
1573 // build the complete include chain for one and then walking up the chain
1574 // of the other looking for a match.
1575 // We use a map from FileID to Offset to store the chain. Easier than writing
1576 // a custom set hash info that only depends on the first part of a pair.
1577 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1578 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00001579 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001580 LChain.insert(LOffs);
1581 // We catch the case where LOffs is in a file included by ROffs and
1582 // quit early. The other way round unfortunately remains suboptimal.
1583 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1584 LocSet::iterator I;
1585 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1586 if (MoveUpIncludeHierarchy(ROffs, *this))
1587 break; // Met at topmost file.
1588 }
1589 if (I != LChain.end())
1590 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Chris Lattner48296ba2010-05-07 05:51:13 +00001592 // If we exited because we found a nearest common ancestor, compare the
1593 // locations within the common file and cache them.
1594 if (LOffs.first == ROffs.first) {
1595 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1596 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001597 }
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001599 // This can happen if a location is in a built-ins buffer.
1600 // But see PR5662.
1601 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001602 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001603 bool LIsBuiltins = strcmp("<built-in>",
1604 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1605 bool RIsBuiltins = strcmp("<built-in>",
1606 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1607 // built-in is before non-built-in
1608 if (LIsBuiltins != RIsBuiltins)
1609 return LIsBuiltins;
1610 assert(LIsBuiltins && RIsBuiltins &&
1611 "Non-built-in locations must be rooted in the main file");
1612 // Both are in built-in buffers, but from different files. We just claim that
1613 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001614 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001615}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001616
Reid Spencer5f016e22007-07-11 17:01:13 +00001617/// PrintStats - Print statistics to stderr.
1618///
1619void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001620 llvm::errs() << "\n*** Source Manager Stats:\n";
1621 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1622 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001623 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00001624 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001625 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001626 << NextLocalOffset << "B of Sloc address space used.\n";
1627 llvm::errs() << LoadedSLocEntryTable.size()
1628 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001629 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001630 << "B of Sloc address space used.\n";
1631
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 unsigned NumLineNumsComputed = 0;
1633 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001634 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1635 NumLineNumsComputed += I->second->SourceLineCache != 0;
1636 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 }
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001639 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1640 << NumLineNumsComputed << " files with line #'s computed.\n";
1641 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1642 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001643}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001644
1645ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001646
1647/// Return the amount of memory used by memory buffers, breaking down
1648/// by heap-backed versus mmap'ed memory.
1649SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1650 size_t malloc_bytes = 0;
1651 size_t mmap_bytes = 0;
1652
1653 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1654 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1655 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1656 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1657 mmap_bytes += sized_mapped;
1658 break;
1659 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1660 malloc_bytes += sized_mapped;
1661 break;
1662 }
1663
1664 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1665}
1666
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001667size_t SourceManager::getDataStructureSizes() const {
Ted Kremenek6e36c122011-07-27 18:41:16 +00001668 return llvm::capacity_in_bytes(MemBufferInfos)
1669 + llvm::capacity_in_bytes(LocalSLocEntryTable)
1670 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
1671 + llvm::capacity_in_bytes(SLocEntryLoaded)
1672 + llvm::capacity_in_bytes(FileInfos)
1673 + llvm::capacity_in_bytes(OverriddenFiles);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001674}