blob: 355b87a9dd7af229776fe14492cbec03573dbefb [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"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000023#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000024#include <cstring>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace SrcMgr;
28using llvm::MemoryBuffer;
29
Chris Lattner23b5dc62009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000033
Ted Kremenek78d85f52007-10-30 21:08:08 +000034ContentCache::~ContentCache() {
Douglas Gregorc8151082010-03-16 22:53:51 +000035 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
Ted Kremenekc16c2082009-01-06 01:55:26 +000038/// getSizeBytesMapped - Returns the number of bytes actually mapped for
39/// this ContentCache. This can be 0 if the MemBuffer was not actually
40/// instantiated.
41unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000042 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000043}
44
45/// getSize - Returns the size of the content encapsulated by this ContentCache.
46/// This can be the size of the source file or the size of an arbitrary
47/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000048/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000049unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000050 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
51 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000052}
53
Douglas Gregor29684422009-12-02 06:49:09 +000054void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregorc8151082010-03-16 22:53:51 +000055 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000056
Douglas Gregorc8151082010-03-16 22:53:51 +000057 delete Buffer.getPointer();
58 Buffer.setPointer(B);
59 Buffer.setInt(false);
Douglas Gregor29684422009-12-02 06:49:09 +000060}
61
Douglas Gregor36c35ba2010-03-16 00:35:39 +000062const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattnere127a0d2010-04-20 20:35:58 +000063 const SourceManager &sm,
64 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000065 bool *Invalid) const {
66 if (Invalid)
67 *Invalid = false;
68
Ted Kremenek5b034ad2009-01-06 22:43:04 +000069 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregorc8151082010-03-16 22:53:51 +000070 if (!Buffer.getPointer() && Entry) {
Chris Lattnere127a0d2010-04-20 20:35:58 +000071 // FIXME:
72 SourceManager &SM = const_cast<SourceManager &>(sm);
73
Douglas Gregoraea67db2010-03-15 22:54:52 +000074 std::string ErrorStr;
75 struct stat FileInfo;
Douglas Gregorc8151082010-03-16 22:53:51 +000076 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
77 Entry->getSize(), &FileInfo));
78 Buffer.setInt(false);
79
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000080 // If we were unable to open the file, then we are in an inconsistent
81 // situation where the content cache referenced a file which no longer
82 // exists. Most likely, we were using a stat cache with an invalid entry but
83 // the file could also have been removed during processing. Since we can't
84 // really deal with this situation, just create an empty buffer.
85 //
86 // FIXME: This is definitely not ideal, but our immediate clients can't
87 // currently handle returning a null entry here. Ideally we should detect
88 // that we are in an inconsistent situation and error out as quickly as
89 // possible.
Douglas Gregorc8151082010-03-16 22:53:51 +000090 if (!Buffer.getPointer()) {
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000091 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregorc8151082010-03-16 22:53:51 +000092 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
93 "<invalid>"));
94 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000095 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
96 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor93ea5cb2010-03-22 15:10:57 +000097
98 if (Diag.isDiagnosticInFlight())
99 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
100 Entry->getName(), ErrorStr);
101 else
Chris Lattnere127a0d2010-04-20 20:35:58 +0000102 Diag.Report(FullSourceLoc(Loc, SM), diag::err_cannot_open_file)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000103 << Entry->getName() << ErrorStr;
104
Douglas Gregorc8151082010-03-16 22:53:51 +0000105 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000106
107 // FIXME: This conditionalization is horrible, but we see spurious failures
108 // in the test suite due to this warning and no one has had time to hunt it
109 // down. So for now, we just don't emit this diagnostic on Win32, and hope
110 // nothing bad happens.
111 //
112 // PR6812.
Douglas Gregor9f692a02010-04-09 15:54:22 +0000113#if !defined(LLVM_ON_WIN32)
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000114 } else if (FileInfo.st_size != Entry->getSize() ||
115 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor9f692a02010-04-09 15:54:22 +0000116 // Check that the file's size and modification time are the same
117 // as in the file entry (which may have come from a stat cache).
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000118 if (Diag.isDiagnosticInFlight())
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000119 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000120 Entry->getName());
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000121 else
Chris Lattnere127a0d2010-04-20 20:35:58 +0000122 Diag.Report(FullSourceLoc(Loc, SM), diag::err_file_modified)
123 << Entry->getName();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000124
Douglas Gregore39b6002010-03-17 15:30:15 +0000125 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000126#endif
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000127 }
Chris Lattner38caec42010-04-20 18:14:03 +0000128
129 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
130 // (BOM). We only support UTF-8 without a BOM right now. See
131 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
132 if (!Buffer.getInt()) {
133 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
134 const char *BOM = 0;
135 if (BufStr.startswith("\xFE\xBB\xBF"))
136 BOM = "UTF-8";
137 else if (BufStr.startswith("\xFE\xFF"))
138 BOM = "UTF-16 (BE)";
139 else if (BufStr.startswith("\xFF\xFE"))
140 BOM = "UTF-16 (LE)";
141 else if (BufStr.startswith(llvm::StringRef("\x00\x00\xFE\xFF", 4)))
142 BOM = "UTF-32 (BE)";
143 else if (BufStr.startswith(llvm::StringRef("\xFF\xFE\x00\x00", 4)))
144 BOM = "UTF-32 (LE)";
145 else if (BufStr.startswith("\x2B\x2F\x76"))
146 BOM = "UTF-7";
147 else if (BufStr.startswith("\xF7\x64\x4C"))
148 BOM = "UTF-1";
149 else if (BufStr.startswith("\xDD\x73\x66\x73"))
150 BOM = "UTF-EBCDIC";
151 else if (BufStr.startswith("\x0E\xFE\xFF"))
152 BOM = "SDSU";
153 else if (BufStr.startswith("\xFB\xEE\x28"))
154 BOM = "BOCU-1";
155 else if (BufStr.startswith("\x84\x31\x95\x33"))
156 BOM = "BOCU-1";
157
158 if (BOM) {
Chris Lattnere127a0d2010-04-20 20:35:58 +0000159 Diag.Report(FullSourceLoc(Loc, SM), diag::err_unsupported_bom)
160 << BOM << Entry->getName();
Chris Lattner38caec42010-04-20 18:14:03 +0000161 Buffer.setInt(1);
162 }
163 }
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)
167 *Invalid = Buffer.getInt();
168
169 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000170}
171
Chris Lattner5b9a5042009-01-26 07:57:50 +0000172unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
173 // 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 =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000176 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
177 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.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000189void LineTableInfo::AddLineNote(unsigned 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.
220void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
221 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.
Mike Stump1eb44332009-09-09 15:08:12 +0000254const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned 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.
Mike Stump1eb44332009-09-09 15:08:12 +0000273void LineTableInfo::AddEntry(unsigned 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 Lattner5b9a5042009-01-26 07:57:50 +0000280unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
283 return LineTable->getLineTableFilenameID(Ptr, Len);
284}
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) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000292 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnerac50e342009-02-03 22:13:05 +0000294 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
295
296 // Remember that this file has #line directives now if it doesn't already.
297 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnerac50e342009-02-03 22:13:05 +0000299 if (LineTable == 0)
300 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000301 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000302}
303
Chris Lattner9d79eba2009-02-04 05:21:58 +0000304/// AddLineNote - Add a GNU line marker to the line table.
305void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
306 int FilenameID, bool IsFileEntry,
307 bool IsFileExit, bool IsSystemHeader,
308 bool IsExternCHeader) {
309 // If there is no filename and no flags, this is treated just like a #line,
310 // which does not change the flags of the previous line marker.
311 if (FilenameID == -1) {
312 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
313 "Can't set flags without setting the filename!");
314 return AddLineNote(Loc, LineNo, FilenameID);
315 }
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattner9d79eba2009-02-04 05:21:58 +0000317 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
318 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner9d79eba2009-02-04 05:21:58 +0000320 // Remember that this file has #line directives now if it doesn't already.
321 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner9d79eba2009-02-04 05:21:58 +0000323 if (LineTable == 0)
324 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner9d79eba2009-02-04 05:21:58 +0000326 SrcMgr::CharacteristicKind FileKind;
327 if (IsExternCHeader)
328 FileKind = SrcMgr::C_ExternCSystem;
329 else if (IsSystemHeader)
330 FileKind = SrcMgr::C_System;
331 else
332 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner9d79eba2009-02-04 05:21:58 +0000334 unsigned EntryExit = 0;
335 if (IsFileEntry)
336 EntryExit = 1;
337 else if (IsFileExit)
338 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner9d79eba2009-02-04 05:21:58 +0000340 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
341 EntryExit, FileKind);
342}
343
Douglas Gregorbd945002009-04-13 16:31:14 +0000344LineTableInfo &SourceManager::getLineTable() {
345 if (LineTable == 0)
346 LineTable = new LineTableInfo();
347 return *LineTable;
348}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000349
Chris Lattner23b5dc62009-02-04 00:40:31 +0000350//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000351// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000352//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000353
Chris Lattner5b9a5042009-01-26 07:57:50 +0000354SourceManager::~SourceManager() {
355 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000357 // Delete FileEntry objects corresponding to content caches. Since the actual
358 // content cache objects are bump pointer allocated, we just have to run the
359 // dtors, but we call the deallocate method for completeness.
360 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
361 MemBufferInfos[i]->~ContentCache();
362 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
363 }
364 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
365 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
366 I->second->~ContentCache();
367 ContentCacheAlloc.Deallocate(I->second);
368 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000369}
370
371void SourceManager::clearIDTables() {
372 MainFileID = FileID();
373 SLocEntryTable.clear();
374 LastLineNoFileIDQuery = FileID();
375 LastLineNoContentCache = 0;
376 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner5b9a5042009-01-26 07:57:50 +0000378 if (LineTable)
379 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner5b9a5042009-01-26 07:57:50 +0000381 // Use up FileID #0 as an invalid instantiation.
382 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000383 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000384}
385
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000386/// getOrCreateContentCache - Create or return a cached ContentCache for the
387/// specified file.
388const ContentCache *
389SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000393 ContentCache *&Entry = FileInfos[FileEnt];
394 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner00282d62009-02-03 07:41:46 +0000396 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
397 // so that FileInfo can use the low 3 bits of the pointer for its own
398 // nefarious purposes.
399 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
400 EntryAlign = std::max(8U, EntryAlign);
401 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000402 new (Entry) ContentCache(FileEnt);
403 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000404}
405
406
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000407/// createMemBufferContentCache - Create a new ContentCache for the specified
408/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000409const ContentCache*
410SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000411 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
412 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
413 // the pointer for its own nefarious purposes.
414 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
415 EntryAlign = std::max(8U, EntryAlign);
416 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000417 new (Entry) ContentCache();
418 MemBufferInfos.push_back(Entry);
419 Entry->setBuffer(Buffer);
420 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
422
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000423void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
424 unsigned NumSLocEntries,
425 unsigned NextOffset) {
426 ExternalSLocEntries = Source;
427 this->NextOffset = NextOffset;
428 SLocEntryLoaded.resize(NumSLocEntries + 1);
429 SLocEntryLoaded[0] = true;
430 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
431}
432
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000433void SourceManager::ClearPreallocatedSLocEntries() {
434 unsigned I = 0;
435 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
436 if (!SLocEntryLoaded[I])
437 break;
438
439 // We've already loaded all preallocated source location entries.
440 if (I == SLocEntryLoaded.size())
441 return;
442
443 // Remove everything from location I onward.
444 SLocEntryTable.resize(I);
445 SLocEntryLoaded.clear();
446 ExternalSLocEntries = 0;
447}
448
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000449
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000450//===----------------------------------------------------------------------===//
451// Methods to create new FileID's and instantiations.
452//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000453
Nico Weber48002c82008-09-29 00:25:48 +0000454/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000455/// include position. This works regardless of whether the ContentCache
456/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000457FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000458 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000459 SrcMgr::CharacteristicKind FileCharacter,
460 unsigned PreallocatedID,
461 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000462 if (PreallocatedID) {
463 // If we're filling in a preallocated ID, just load in the file
464 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000465 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000466 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000467 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000468 "Source location entry already loaded");
469 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000470 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000471 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
472 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000473 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000474 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000475 }
476
Mike Stump1eb44332009-09-09 15:08:12 +0000477 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000478 FileInfo::get(IncludePos, File,
479 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000480 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000481 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
482 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000484 // Set LastFileIDLookup to the newly created file. The next getFileID call is
485 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000486 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000487 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000488}
489
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000490/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000491/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000492/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000493SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000494 SourceLocation ILocStart,
495 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000496 unsigned TokLength,
497 unsigned PreallocatedID,
498 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000499 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000500 if (PreallocatedID) {
501 // If we're filling in a preallocated ID, just load in the
502 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000503 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000504 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000505 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 "Source location entry already loaded");
507 assert(Offset && "Preallocate source location cannot have zero offset");
508 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
509 SLocEntryLoaded[PreallocatedID] = true;
510 return SourceLocation::getMacroLoc(Offset);
511 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000512 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000513 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
514 NextOffset += TokLength+1;
515 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000516}
517
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000518const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000519SourceManager::getMemoryBufferForFile(const FileEntry *File,
520 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000521 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000522 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000523 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000524}
525
526bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
527 const llvm::MemoryBuffer *Buffer) {
528 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
529 if (IR == 0)
530 return true;
531
532 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
533 return false;
534}
535
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000536llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000537 bool MyInvalid = false;
538 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000539 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000540 *Invalid = MyInvalid;
541
542 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000543 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000544
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000545 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000546}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000547
Chris Lattner23b5dc62009-02-04 00:40:31 +0000548//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000549// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000550//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000551
552/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
553/// method that is used for all SourceManager queries that start with a
554/// SourceLocation object. It is responsible for finding the entry in
555/// SLocEntryTable which contains the specified location.
556///
557FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
558 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000560 // After the first and second level caches, I see two common sorts of
561 // behavior: 1) a lot of searched FileID's are "near" the cached file location
562 // or are "near" the cached instantiation location. 2) others are just
563 // completely random and may be a very long way away.
564 //
565 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
566 // then we fall back to a less cache efficient, but more scalable, binary
567 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000569 // See if this is near the file point - worst case we start scanning from the
570 // most newly created FileID.
571 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000573 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
574 // Neither loc prunes our search.
575 I = SLocEntryTable.end();
576 } else {
577 // Perhaps it is near the file point.
578 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
579 }
580
581 // Find the FileID that contains this. "I" is an iterator that points to a
582 // FileID whose offset is known to be larger than SLocOffset.
583 unsigned NumProbes = 0;
584 while (1) {
585 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000586 if (ExternalSLocEntries)
587 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000588 if (I->getOffset() <= SLocOffset) {
589#if 0
590 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
591 I-SLocEntryTable.begin(),
592 I->isInstantiation() ? "inst" : "file",
593 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
594#endif
595 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000596
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000597 // If this isn't an instantiation, remember it. We have good locality
598 // across FileID lookups.
599 if (!I->isInstantiation())
600 LastFileIDLookup = Res;
601 NumLinearScans += NumProbes+1;
602 return Res;
603 }
604 if (++NumProbes == 8)
605 break;
606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000608 // Convert "I" back into an index. We know that it is an entry whose index is
609 // larger than the offset we are looking for.
610 unsigned GreaterIndex = I-SLocEntryTable.begin();
611 // LessIndex - This is the lower bound of the range that we're searching.
612 // We know that the offset corresponding to the FileID is is less than
613 // SLocOffset.
614 unsigned LessIndex = 0;
615 NumProbes = 0;
616 while (1) {
617 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000618 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000620 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000622 // If the offset of the midpoint is too large, chop the high side of the
623 // range to the midpoint.
624 if (MidOffset > SLocOffset) {
625 GreaterIndex = MiddleIndex;
626 continue;
627 }
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000629 // If the middle index contains the value, succeed and return.
630 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
631#if 0
632 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
633 I-SLocEntryTable.begin(),
634 I->isInstantiation() ? "inst" : "file",
635 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
636#endif
637 FileID Res = FileID::get(MiddleIndex);
638
639 // If this isn't an instantiation, remember it. We have good locality
640 // across FileID lookups.
641 if (!I->isInstantiation())
642 LastFileIDLookup = Res;
643 NumBinaryProbes += NumProbes;
644 return Res;
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000647 // Otherwise, move the low-side up to the middle index.
648 LessIndex = MiddleIndex;
649 }
650}
651
Chris Lattneraddb7972009-01-26 20:04:19 +0000652SourceLocation SourceManager::
653getInstantiationLocSlowCase(SourceLocation Loc) const {
654 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000655 // Note: If Loc indicates an offset into a token that came from a macro
656 // expansion (e.g. the 5th character of the token) we do not want to add
657 // this offset when going to the instantiation location. The instatiation
658 // location is the macro invocation, which the offset has nothing to do
659 // with. This is unlike when we get the spelling loc, because the offset
660 // directly correspond to the token whose spelling we're inspecting.
661 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000662 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000663 } while (!Loc.isFileID());
664
665 return Loc;
666}
667
668SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
669 do {
670 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
671 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
672 Loc = Loc.getFileLocWithOffset(LocInfo.second);
673 } while (!Loc.isFileID());
674 return Loc;
675}
676
677
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000678std::pair<FileID, unsigned>
679SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
680 unsigned Offset) const {
681 // If this is an instantiation record, walk through all the instantiation
682 // points.
683 FileID FID;
684 SourceLocation Loc;
685 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000686 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000688 FID = getFileID(Loc);
689 E = &getSLocEntry(FID);
690 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000691 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000693 return std::make_pair(FID, Offset);
694}
695
696std::pair<FileID, unsigned>
697SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
698 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000699 // If this is an instantiation record, walk through all the instantiation
700 // points.
701 FileID FID;
702 SourceLocation Loc;
703 do {
704 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000706 FID = getFileID(Loc);
707 E = &getSLocEntry(FID);
708 Offset += Loc.getOffset()-E->getOffset();
709 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000711 return std::make_pair(FID, Offset);
712}
713
Chris Lattner387616e2009-02-17 08:04:48 +0000714/// getImmediateSpellingLoc - Given a SourceLocation object, return the
715/// spelling location referenced by the ID. This is the first level down
716/// towards the place where the characters that make up the lexed token can be
717/// found. This should not generally be used by clients.
718SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
719 if (Loc.isFileID()) return Loc;
720 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
721 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
722 return Loc.getFileLocWithOffset(LocInfo.second);
723}
724
725
Chris Lattnere7fb4842009-02-15 20:52:18 +0000726/// getImmediateInstantiationRange - Loc is required to be an instantiation
727/// location. Return the start/end of the instantiation information.
728std::pair<SourceLocation,SourceLocation>
729SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
730 assert(Loc.isMacroID() && "Not an instantiation loc!");
731 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
732 return II.getInstantiationLocRange();
733}
734
Chris Lattner66781332009-02-15 21:26:50 +0000735/// getInstantiationRange - Given a SourceLocation object, return the
736/// range of tokens covered by the instantiation in the ultimate file.
737std::pair<SourceLocation,SourceLocation>
738SourceManager::getInstantiationRange(SourceLocation Loc) const {
739 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner66781332009-02-15 21:26:50 +0000741 std::pair<SourceLocation,SourceLocation> Res =
742 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattner66781332009-02-15 21:26:50 +0000744 // Fully resolve the start and end locations to their ultimate instantiation
745 // points.
746 while (!Res.first.isFileID())
747 Res.first = getImmediateInstantiationRange(Res.first).first;
748 while (!Res.second.isFileID())
749 Res.second = getImmediateInstantiationRange(Res.second).second;
750 return Res;
751}
752
Chris Lattnere7fb4842009-02-15 20:52:18 +0000753
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000754
755//===----------------------------------------------------------------------===//
756// Queries about the code at a SourceLocation.
757//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000758
759/// getCharacterData - Return a pointer to the start of the specified location
760/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000761const char *SourceManager::getCharacterData(SourceLocation SL,
762 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 // Note that this is a hot function in the getSpelling() path, which is
764 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000765 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Ted Kremenekc16c2082009-01-06 01:55:26 +0000767 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000768 bool CharDataInvalid = false;
769 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +0000770 = getSLocEntry(LocInfo.first).getFile().getContentCache()
771 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000772 if (Invalid)
773 *Invalid = CharDataInvalid;
774 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000775}
776
Reid Spencer5f016e22007-07-11 17:01:13 +0000777
Chris Lattner9dc1f532007-07-20 16:37:10 +0000778/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000779/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000780unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
781 bool *Invalid) const {
782 bool MyInvalid = false;
783 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
784 if (Invalid)
785 *Invalid = MyInvalid;
786
787 if (MyInvalid)
788 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 unsigned LineStart = FilePos;
791 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
792 --LineStart;
793 return FilePos-LineStart+1;
794}
795
Douglas Gregor50f6af72010-03-16 05:20:39 +0000796unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
797 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000798 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000799 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000800 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000801}
802
Douglas Gregor50f6af72010-03-16 05:20:39 +0000803unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
804 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000805 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000806 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000807 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000808}
809
Chris Lattnere127a0d2010-04-20 20:35:58 +0000810static DISABLE_INLINE void
811ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
812 llvm::BumpPtrAllocator &Alloc,
813 const SourceManager &SM, bool &Invalid);
814static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
815 llvm::BumpPtrAllocator &Alloc,
816 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000817 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000818 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
819 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000820 if (Invalid)
821 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000823 // Find the file offsets of all of the *physical* source lines. This does
824 // not look at trigraphs, escaped newlines, or anything else tricky.
825 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000827 // Line #1 starts at char 0.
828 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000830 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
831 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
832 unsigned Offs = 0;
833 while (1) {
834 // Skip over the contents of the line.
835 // TODO: Vectorize this? This is very performance sensitive for programs
836 // with lots of diagnostics and in -E mode.
837 const unsigned char *NextBuf = (const unsigned char *)Buf;
838 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
839 ++NextBuf;
840 Offs += NextBuf-Buf;
841 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000843 if (Buf[0] == '\n' || Buf[0] == '\r') {
844 // If this is \n\r or \r\n, skip both characters.
845 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
846 ++Offs, ++Buf;
847 ++Offs, ++Buf;
848 LineOffsets.push_back(Offs);
849 } else {
850 // Otherwise, this is a null. If end of file, exit.
851 if (Buf == End) break;
852 // Otherwise, skip the null.
853 ++Offs, ++Buf;
854 }
855 }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000857 // Copy the offsets into the FileInfo structure.
858 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000859 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000860 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
861}
Reid Spencer5f016e22007-07-11 17:01:13 +0000862
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000863/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000864/// for the position indicated. This requires building and caching a table of
865/// line offsets for the MemoryBuffer, so this is not cheap: use only when
866/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000867unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
868 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000869 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000870 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000871 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000872 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000873 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000874 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000877 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000878 if (Content->SourceLineCache == 0) {
879 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000880 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000881 if (Invalid)
882 *Invalid = MyInvalid;
883 if (MyInvalid)
884 return 1;
885 } else if (Invalid)
886 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000887
888 // Okay, we know we have a line number table. Do a binary search to find the
889 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000890 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000891 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000892 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Chris Lattner30fc9332009-02-04 01:06:56 +0000894 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000895
Daniel Dunbar4106d692009-05-18 17:30:52 +0000896 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000897 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000898 //
899 // If it is worth being optimized, then in my opinion it could be more
900 // performant, simpler, and more obviously correct by just "galloping" outward
901 // from the queried file position. In fact, this could be incorporated into a
902 // generic algorithm such as lower_bound_with_hint.
903 //
904 // If someone gives me a test case where this matters, and I will do it! - DWD
905
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000906 // If the previous query was to the same file, we know both the file pos from
907 // that query and the line number returned. This allows us to narrow the
908 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000909 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000910 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000911 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000912 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000914 // The query is likely to be nearby the previous one. Here we check to
915 // see if it is within 5, 10 or 20 lines. It can be far away in cases
916 // where big comment blocks and vertical whitespace eat up lines but
917 // contribute no tokens.
918 if (SourceLineCache+5 < SourceLineCacheEnd) {
919 if (SourceLineCache[5] > QueriedFilePos)
920 SourceLineCacheEnd = SourceLineCache+5;
921 else if (SourceLineCache+10 < SourceLineCacheEnd) {
922 if (SourceLineCache[10] > QueriedFilePos)
923 SourceLineCacheEnd = SourceLineCache+10;
924 else if (SourceLineCache+20 < SourceLineCacheEnd) {
925 if (SourceLineCache[20] > QueriedFilePos)
926 SourceLineCacheEnd = SourceLineCache+20;
927 }
928 }
929 }
930 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000931 if (LastLineNoResult < Content->NumLines)
932 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000933 }
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000936 // If the spread is large, do a "radix" test as our initial guess, based on
937 // the assumption that lines average to approximately the same length.
938 // NOTE: This is currently disabled, as it does not appear to be profitable in
939 // initial measurements.
940 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000941 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000943 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000944 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000946 // Check for -10 and +10 lines.
947 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
948 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
949
950 // If the computed lower bound is less than the query location, move it in.
951 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
952 SourceLineCacheStart[LowerBound] < QueriedFilePos)
953 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000955 // If the computed upper bound is greater than the query location, move it.
956 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
957 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
958 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000961 unsigned *Pos
962 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000963 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattner30fc9332009-02-04 01:06:56 +0000965 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000966 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000967 LastLineNoFilePos = QueriedFilePos;
968 LastLineNoResult = LineNo;
969 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000970}
971
Douglas Gregor50f6af72010-03-16 05:20:39 +0000972unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
973 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000974 if (Loc.isInvalid()) return 0;
975 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
976 return getLineNumber(LocInfo.first, LocInfo.second);
977}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000978unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
979 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000980 if (Loc.isInvalid()) return 0;
981 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
982 return getLineNumber(LocInfo.first, LocInfo.second);
983}
984
Chris Lattner6b306672009-02-04 05:33:01 +0000985/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000986/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000987/// header, or an "implicit extern C" system header.
988///
989/// This state can be modified with flags on GNU linemarker directives like:
990/// # 4 "foo.h" 3
991/// which changes all source locations in the current file after that to be
992/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000993SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000994SourceManager::getFileCharacteristic(SourceLocation Loc) const {
995 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
996 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
997 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
998
999 // If there are no #line directives in this file, just return the whole-file
1000 // state.
1001 if (!FI.hasLineDirectives())
1002 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner6b306672009-02-04 05:33:01 +00001004 assert(LineTable && "Can't have linetable entries without a LineTable!");
1005 // See if there is a #line directive before the location.
1006 const LineEntry *Entry =
1007 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner6b306672009-02-04 05:33:01 +00001009 // If this is before the first line marker, use the file characteristic.
1010 if (!Entry)
1011 return FI.getFileCharacteristic();
1012
1013 return Entry->FileKind;
1014}
1015
Chris Lattnerbff5c512009-02-17 08:39:06 +00001016/// Return the filename or buffer identifier of the buffer the location is in.
1017/// Note that this name does not respect #line directives. Use getPresumedLoc
1018/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001019const char *SourceManager::getBufferName(SourceLocation Loc,
1020 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +00001021 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Douglas Gregor50f6af72010-03-16 05:20:39 +00001023 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001024}
1025
Chris Lattner30fc9332009-02-04 01:06:56 +00001026
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001027/// getPresumedLoc - This method returns the "presumed" location of a
1028/// SourceLocation specifies. A "presumed location" can be modified by #line
1029/// or GNU line marker directives. This provides a view on the data that a
1030/// user should see in diagnostics, for example.
1031///
1032/// Note that a presumed location is always given as the instantiation point
1033/// of an instantiation location, not at the spelling location.
1034PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1035 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001037 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001038 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner30fc9332009-02-04 01:06:56 +00001040 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001041 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner3cd949c2009-02-04 01:55:42 +00001043 // To get the source name, first consult the FileEntry (if one exists)
1044 // before the MemBuffer as this will avoid unnecessarily paging in the
1045 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001046 const char *Filename;
1047 if (C->Entry)
1048 Filename = C->Entry->getName();
1049 else
1050 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001051 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1052 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1053 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner3cd949c2009-02-04 01:55:42 +00001055 // If we have #line directives in this file, update and overwrite the physical
1056 // location info if appropriate.
1057 if (FI.hasLineDirectives()) {
1058 assert(LineTable && "Can't have linetable entries without a LineTable!");
1059 // See if there is a #line directive before this. If so, get it.
1060 if (const LineEntry *Entry =
1061 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001062 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001063 if (Entry->FilenameID != -1)
1064 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001065
1066 // Use the line number specified by the LineEntry. This line number may
1067 // be multiple lines down from the line entry. Add the difference in
1068 // physical line numbers from the query point and the line marker to the
1069 // total.
1070 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1071 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001073 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner137b6a62009-02-04 06:25:26 +00001075 // Handle virtual #include manipulation.
1076 if (Entry->IncludeOffset) {
1077 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1078 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1079 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001080 }
1081 }
1082
1083 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001084}
1085
1086//===----------------------------------------------------------------------===//
1087// Other miscellaneous methods.
1088//===----------------------------------------------------------------------===//
1089
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001090/// \brief Get the source location for the given file:line:col triplet.
1091///
1092/// If the source file is included multiple times, the source location will
1093/// be based upon the first inclusion.
1094SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1095 unsigned Line, unsigned Col) const {
1096 assert(SourceFile && "Null source file!");
1097 assert(Line && Col && "Line and column should start from 1!");
1098
1099 fileinfo_iterator FI = FileInfos.find(SourceFile);
1100 if (FI == FileInfos.end())
1101 return SourceLocation();
1102 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001104 // If this is the first use of line information for this buffer, compute the
1105 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001106 if (Content->SourceLineCache == 0) {
1107 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001108 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001109 if (MyInvalid)
1110 return SourceLocation();
1111 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001112
Douglas Gregor4a160e12009-12-02 05:34:39 +00001113 // Find the first file ID that corresponds to the given file.
1114 FileID FirstFID;
1115
1116 // First, check the main file ID, since it is common to look for a
1117 // location in the main file.
1118 if (!MainFileID.isInvalid()) {
1119 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1120 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1121 FirstFID = MainFileID;
1122 }
1123
1124 if (FirstFID.isInvalid()) {
1125 // The location we're looking for isn't in the main file; look
1126 // through all of the source locations.
1127 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1128 const SLocEntry &SLoc = getSLocEntry(I);
1129 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1130 FirstFID = FileID::get(I);
1131 break;
1132 }
1133 }
1134 }
1135
1136 if (FirstFID.isInvalid())
1137 return SourceLocation();
1138
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001139 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001140 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001141 if (Size > 0)
1142 --Size;
1143 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1144 }
1145
1146 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001147 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1148 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001149 unsigned i = 0;
1150
1151 // Check that the given column is valid.
1152 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1153 ++i;
1154 if (i < Col-1)
1155 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1156
Douglas Gregor4a160e12009-12-02 05:34:39 +00001157 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001158}
1159
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001160/// \brief Determines the order of 2 source locations in the translation unit.
1161///
1162/// \returns true if LHS source location comes before RHS, false otherwise.
1163bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1164 SourceLocation RHS) const {
1165 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1166 if (LHS == RHS)
1167 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001169 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1170 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001172 // If the source locations are in the same file, just compare offsets.
1173 if (LOffs.first == ROffs.first)
1174 return LOffs.second < ROffs.second;
1175
1176 // If we are comparing a source location with multiple locations in the same
1177 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001179 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1180 LastRFIDForBeforeTUCheck == ROffs.first)
1181 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001183 LastLFIDForBeforeTUCheck = LOffs.first;
1184 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001186 // "Traverse" the include/instantiation stacks of both locations and try to
1187 // find a common "ancestor".
1188 //
1189 // First we traverse the stack of the right location and check each level
1190 // against the level of the left location, while collecting all levels in a
1191 // "stack map".
1192
1193 std::map<FileID, unsigned> ROffsMap;
1194 ROffsMap[ROffs.first] = ROffs.second;
1195
1196 while (1) {
1197 SourceLocation UpperLoc;
1198 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1199 if (Entry.isInstantiation())
1200 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1201 else
1202 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001204 if (UpperLoc.isInvalid())
1205 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001207 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001209 if (LOffs.first == ROffs.first)
1210 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001212 ROffsMap[ROffs.first] = ROffs.second;
1213 }
1214
1215 // We didn't find a common ancestor. Now traverse the stack of the left
1216 // location, checking against the stack map of the right location.
1217
1218 while (1) {
1219 SourceLocation UpperLoc;
1220 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1221 if (Entry.isInstantiation())
1222 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1223 else
1224 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001226 if (UpperLoc.isInvalid())
1227 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001229 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001231 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1232 if (I != ROffsMap.end())
1233 return LastResForBeforeTUCheck = LOffs.second < I->second;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001236 // There is no common ancestor, most probably because one location is in the
1237 // predefines buffer.
1238 //
1239 // FIXME: We should rearrange the external interface so this simply never
1240 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001242 // If exactly one location is a memory buffer, assume it preceeds the other.
1243 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1244 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1245 if (LIsMB != RIsMB)
1246 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001248 // Otherwise, just assume FileIDs were created in order.
1249 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001250}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252/// PrintStats - Print statistics to stderr.
1253///
1254void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001255 llvm::errs() << "\n*** Source Manager Stats:\n";
1256 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1257 << " mem buffers mapped.\n";
1258 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1259 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 unsigned NumLineNumsComputed = 0;
1262 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001263 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1264 NumLineNumsComputed += I->second->SourceLineCache != 0;
1265 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001268 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1269 << NumLineNumsComputed << " files with line #'s computed.\n";
1270 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1271 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001272}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001273
1274ExternalSLocEntrySource::~ExternalSLocEntrySource() { }