blob: 3ecab1d8c16fceb94e06c2c769ffa922c052a259 [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 Lattner5c5db4e2010-04-20 20:49:23 +000063 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000064 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) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000071 std::string ErrorStr;
72 struct stat FileInfo;
Douglas Gregorc8151082010-03-16 22:53:51 +000073 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
74 Entry->getSize(), &FileInfo));
75 Buffer.setInt(false);
76
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000077 // If we were unable to open the file, then we are in an inconsistent
78 // situation where the content cache referenced a file which no longer
79 // exists. Most likely, we were using a stat cache with an invalid entry but
80 // the file could also have been removed during processing. Since we can't
81 // really deal with this situation, just create an empty buffer.
82 //
83 // FIXME: This is definitely not ideal, but our immediate clients can't
84 // currently handle returning a null entry here. Ideally we should detect
85 // that we are in an inconsistent situation and error out as quickly as
86 // possible.
Douglas Gregorc8151082010-03-16 22:53:51 +000087 if (!Buffer.getPointer()) {
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000088 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregorc8151082010-03-16 22:53:51 +000089 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
90 "<invalid>"));
91 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000092 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
93 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor93ea5cb2010-03-22 15:10:57 +000094
95 if (Diag.isDiagnosticInFlight())
96 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
97 Entry->getName(), ErrorStr);
98 else
Chris Lattnere127a0d2010-04-20 20:35:58 +000099 Diag.Report(FullSourceLoc(Loc, SM), diag::err_cannot_open_file)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000100 << Entry->getName() << ErrorStr;
101
Douglas Gregorc8151082010-03-16 22:53:51 +0000102 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000103
104 // FIXME: This conditionalization is horrible, but we see spurious failures
105 // in the test suite due to this warning and no one has had time to hunt it
106 // down. So for now, we just don't emit this diagnostic on Win32, and hope
107 // nothing bad happens.
108 //
109 // PR6812.
Douglas Gregor9f692a02010-04-09 15:54:22 +0000110#if !defined(LLVM_ON_WIN32)
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000111 } else if (FileInfo.st_size != Entry->getSize() ||
112 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor9f692a02010-04-09 15:54:22 +0000113 // Check that the file's size and modification time are the same
114 // as in the file entry (which may have come from a stat cache).
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000115 if (Diag.isDiagnosticInFlight())
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000116 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000117 Entry->getName());
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000118 else
Chris Lattnere127a0d2010-04-20 20:35:58 +0000119 Diag.Report(FullSourceLoc(Loc, SM), diag::err_file_modified)
120 << Entry->getName();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000121
Douglas Gregore39b6002010-03-17 15:30:15 +0000122 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000123#endif
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000124 }
Chris Lattner38caec42010-04-20 18:14:03 +0000125
126 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
127 // (BOM). We only support UTF-8 without a BOM right now. See
128 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
129 if (!Buffer.getInt()) {
130 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
131 const char *BOM = 0;
132 if (BufStr.startswith("\xFE\xBB\xBF"))
133 BOM = "UTF-8";
134 else if (BufStr.startswith("\xFE\xFF"))
135 BOM = "UTF-16 (BE)";
136 else if (BufStr.startswith("\xFF\xFE"))
137 BOM = "UTF-16 (LE)";
138 else if (BufStr.startswith(llvm::StringRef("\x00\x00\xFE\xFF", 4)))
139 BOM = "UTF-32 (BE)";
140 else if (BufStr.startswith(llvm::StringRef("\xFF\xFE\x00\x00", 4)))
141 BOM = "UTF-32 (LE)";
142 else if (BufStr.startswith("\x2B\x2F\x76"))
143 BOM = "UTF-7";
144 else if (BufStr.startswith("\xF7\x64\x4C"))
145 BOM = "UTF-1";
146 else if (BufStr.startswith("\xDD\x73\x66\x73"))
147 BOM = "UTF-EBCDIC";
148 else if (BufStr.startswith("\x0E\xFE\xFF"))
149 BOM = "SDSU";
150 else if (BufStr.startswith("\xFB\xEE\x28"))
151 BOM = "BOCU-1";
152 else if (BufStr.startswith("\x84\x31\x95\x33"))
153 BOM = "BOCU-1";
154
155 if (BOM) {
Chris Lattnere127a0d2010-04-20 20:35:58 +0000156 Diag.Report(FullSourceLoc(Loc, SM), diag::err_unsupported_bom)
157 << BOM << Entry->getName();
Chris Lattner38caec42010-04-20 18:14:03 +0000158 Buffer.setInt(1);
159 }
160 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000161 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000162
Douglas Gregorc8151082010-03-16 22:53:51 +0000163 if (Invalid)
164 *Invalid = Buffer.getInt();
165
166 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000167}
168
Chris Lattner5b9a5042009-01-26 07:57:50 +0000169unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
170 // Look up the filename in the string table, returning the pre-existing value
171 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000172 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000173 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
174 if (Entry.getValue() != ~0U)
175 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Chris Lattner5b9a5042009-01-26 07:57:50 +0000177 // Otherwise, assign this the next available ID.
178 Entry.setValue(FilenamesByID.size());
179 FilenamesByID.push_back(&Entry);
180 return FilenamesByID.size()-1;
181}
182
Chris Lattnerac50e342009-02-03 22:13:05 +0000183/// AddLineNote - Add a line note to the line table that indicates that there
184/// is a #line at the specified FID/Offset location which changes the presumed
185/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000186void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000187 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000188 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattner23b5dc62009-02-04 00:40:31 +0000190 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
191 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner9d79eba2009-02-04 05:21:58 +0000193 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000194 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner9d79eba2009-02-04 05:21:58 +0000196 if (!Entries.empty()) {
197 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
198 // that we are still in "foo.h".
199 if (FilenameID == -1)
200 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattner137b6a62009-02-04 06:25:26 +0000202 // If we are after a line marker that switched us to system header mode, or
203 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000204 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattner137b6a62009-02-04 06:25:26 +0000208 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
209 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000210}
211
Chris Lattner9d79eba2009-02-04 05:21:58 +0000212/// AddLineNote This is the same as the previous version of AddLineNote, but is
213/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
214/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
215/// this is a file exit. FileKind specifies whether this is a system header or
216/// extern C system header.
217void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
218 unsigned LineNo, int FilenameID,
219 unsigned EntryExit,
220 SrcMgr::CharacteristicKind FileKind) {
221 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattner9d79eba2009-02-04 05:21:58 +0000223 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner9d79eba2009-02-04 05:21:58 +0000225 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
226 "Adding line entries out of order!");
227
Chris Lattner137b6a62009-02-04 06:25:26 +0000228 unsigned IncludeOffset = 0;
229 if (EntryExit == 0) { // No #include stack change.
230 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
231 } else if (EntryExit == 1) {
232 IncludeOffset = Offset-1;
233 } else if (EntryExit == 2) {
234 assert(!Entries.empty() && Entries.back().IncludeOffset &&
235 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattner137b6a62009-02-04 06:25:26 +0000237 // Get the include loc of the last entries' include loc as our include loc.
238 IncludeOffset = 0;
239 if (const LineEntry *PrevEntry =
240 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
241 IncludeOffset = PrevEntry->IncludeOffset;
242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattner137b6a62009-02-04 06:25:26 +0000244 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
245 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000246}
247
248
Chris Lattner3cd949c2009-02-04 01:55:42 +0000249/// FindNearestLineEntry - Find the line entry nearest to FID that is before
250/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000251const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000252 unsigned Offset) {
253 const std::vector<LineEntry> &Entries = LineEntries[FID];
254 assert(!Entries.empty() && "No #line entries for this FID after all!");
255
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000256 // It is very common for the query to be after the last #line, check this
257 // first.
258 if (Entries.back().FileOffset <= Offset)
259 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000260
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000261 // Do a binary search to find the maximal element that is still before Offset.
262 std::vector<LineEntry>::const_iterator I =
263 std::upper_bound(Entries.begin(), Entries.end(), Offset);
264 if (I == Entries.begin()) return 0;
265 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000266}
Chris Lattnerac50e342009-02-03 22:13:05 +0000267
Douglas Gregorbd945002009-04-13 16:31:14 +0000268/// \brief Add a new line entry that has already been encoded into
269/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000270void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000271 const std::vector<LineEntry> &Entries) {
272 LineEntries[FID] = Entries;
273}
Chris Lattnerac50e342009-02-03 22:13:05 +0000274
Chris Lattner5b9a5042009-01-26 07:57:50 +0000275/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000276///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000277unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
278 if (LineTable == 0)
279 LineTable = new LineTableInfo();
280 return LineTable->getLineTableFilenameID(Ptr, Len);
281}
282
283
Chris Lattner4c4ea172009-02-03 21:52:55 +0000284/// AddLineNote - Add a line note to the line table for the FileID and offset
285/// specified by Loc. If FilenameID is -1, it is considered to be
286/// unspecified.
287void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
288 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000289 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnerac50e342009-02-03 22:13:05 +0000291 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
292
293 // Remember that this file has #line directives now if it doesn't already.
294 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattnerac50e342009-02-03 22:13:05 +0000296 if (LineTable == 0)
297 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000298 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000299}
300
Chris Lattner9d79eba2009-02-04 05:21:58 +0000301/// AddLineNote - Add a GNU line marker to the line table.
302void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
303 int FilenameID, bool IsFileEntry,
304 bool IsFileExit, bool IsSystemHeader,
305 bool IsExternCHeader) {
306 // If there is no filename and no flags, this is treated just like a #line,
307 // which does not change the flags of the previous line marker.
308 if (FilenameID == -1) {
309 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
310 "Can't set flags without setting the filename!");
311 return AddLineNote(Loc, LineNo, FilenameID);
312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner9d79eba2009-02-04 05:21:58 +0000314 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
315 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattner9d79eba2009-02-04 05:21:58 +0000317 // Remember that this file has #line directives now if it doesn't already.
318 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner9d79eba2009-02-04 05:21:58 +0000320 if (LineTable == 0)
321 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner9d79eba2009-02-04 05:21:58 +0000323 SrcMgr::CharacteristicKind FileKind;
324 if (IsExternCHeader)
325 FileKind = SrcMgr::C_ExternCSystem;
326 else if (IsSystemHeader)
327 FileKind = SrcMgr::C_System;
328 else
329 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner9d79eba2009-02-04 05:21:58 +0000331 unsigned EntryExit = 0;
332 if (IsFileEntry)
333 EntryExit = 1;
334 else if (IsFileExit)
335 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner9d79eba2009-02-04 05:21:58 +0000337 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
338 EntryExit, FileKind);
339}
340
Douglas Gregorbd945002009-04-13 16:31:14 +0000341LineTableInfo &SourceManager::getLineTable() {
342 if (LineTable == 0)
343 LineTable = new LineTableInfo();
344 return *LineTable;
345}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000346
Chris Lattner23b5dc62009-02-04 00:40:31 +0000347//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000348// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000349//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000350
Chris Lattner5b9a5042009-01-26 07:57:50 +0000351SourceManager::~SourceManager() {
352 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000354 // Delete FileEntry objects corresponding to content caches. Since the actual
355 // content cache objects are bump pointer allocated, we just have to run the
356 // dtors, but we call the deallocate method for completeness.
357 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
358 MemBufferInfos[i]->~ContentCache();
359 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
360 }
361 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
362 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
363 I->second->~ContentCache();
364 ContentCacheAlloc.Deallocate(I->second);
365 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000366}
367
368void SourceManager::clearIDTables() {
369 MainFileID = FileID();
370 SLocEntryTable.clear();
371 LastLineNoFileIDQuery = FileID();
372 LastLineNoContentCache = 0;
373 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner5b9a5042009-01-26 07:57:50 +0000375 if (LineTable)
376 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner5b9a5042009-01-26 07:57:50 +0000378 // Use up FileID #0 as an invalid instantiation.
379 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000380 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000381}
382
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000383/// getOrCreateContentCache - Create or return a cached ContentCache for the
384/// specified file.
385const ContentCache *
386SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000390 ContentCache *&Entry = FileInfos[FileEnt];
391 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner00282d62009-02-03 07:41:46 +0000393 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
394 // so that FileInfo can use the low 3 bits of the pointer for its own
395 // nefarious purposes.
396 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
397 EntryAlign = std::max(8U, EntryAlign);
398 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000399 new (Entry) ContentCache(FileEnt);
400 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000401}
402
403
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000404/// createMemBufferContentCache - Create a new ContentCache for the specified
405/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000406const ContentCache*
407SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000408 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
409 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
410 // the pointer for its own nefarious purposes.
411 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
412 EntryAlign = std::max(8U, EntryAlign);
413 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000414 new (Entry) ContentCache();
415 MemBufferInfos.push_back(Entry);
416 Entry->setBuffer(Buffer);
417 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000418}
419
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000420void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
421 unsigned NumSLocEntries,
422 unsigned NextOffset) {
423 ExternalSLocEntries = Source;
424 this->NextOffset = NextOffset;
425 SLocEntryLoaded.resize(NumSLocEntries + 1);
426 SLocEntryLoaded[0] = true;
427 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
428}
429
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000430void SourceManager::ClearPreallocatedSLocEntries() {
431 unsigned I = 0;
432 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
433 if (!SLocEntryLoaded[I])
434 break;
435
436 // We've already loaded all preallocated source location entries.
437 if (I == SLocEntryLoaded.size())
438 return;
439
440 // Remove everything from location I onward.
441 SLocEntryTable.resize(I);
442 SLocEntryLoaded.clear();
443 ExternalSLocEntries = 0;
444}
445
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000446
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000447//===----------------------------------------------------------------------===//
448// Methods to create new FileID's and instantiations.
449//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000450
Nico Weber48002c82008-09-29 00:25:48 +0000451/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000452/// include position. This works regardless of whether the ContentCache
453/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000454FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000455 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000456 SrcMgr::CharacteristicKind FileCharacter,
457 unsigned PreallocatedID,
458 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000459 if (PreallocatedID) {
460 // If we're filling in a preallocated ID, just load in the file
461 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000462 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000463 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000464 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000465 "Source location entry already loaded");
466 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000467 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000468 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
469 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000470 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000471 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000472 }
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000475 FileInfo::get(IncludePos, File,
476 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000477 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000478 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
479 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000481 // Set LastFileIDLookup to the newly created file. The next getFileID call is
482 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000483 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000484 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000485}
486
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000487/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000488/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000489/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000490SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000491 SourceLocation ILocStart,
492 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000493 unsigned TokLength,
494 unsigned PreallocatedID,
495 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000496 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000497 if (PreallocatedID) {
498 // If we're filling in a preallocated ID, just load in the
499 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000500 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000501 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000502 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000503 "Source location entry already loaded");
504 assert(Offset && "Preallocate source location cannot have zero offset");
505 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
506 SLocEntryLoaded[PreallocatedID] = true;
507 return SourceLocation::getMacroLoc(Offset);
508 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000509 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000510 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
511 NextOffset += TokLength+1;
512 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000513}
514
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000515const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000516SourceManager::getMemoryBufferForFile(const FileEntry *File,
517 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000518 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000519 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000520 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000521}
522
523bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
524 const llvm::MemoryBuffer *Buffer) {
525 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
526 if (IR == 0)
527 return true;
528
529 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
530 return false;
531}
532
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000533llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000534 bool MyInvalid = false;
535 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000536 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000537 *Invalid = MyInvalid;
538
539 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000540 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000541
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000542 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000543}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000544
Chris Lattner23b5dc62009-02-04 00:40:31 +0000545//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000546// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000547//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000548
549/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
550/// method that is used for all SourceManager queries that start with a
551/// SourceLocation object. It is responsible for finding the entry in
552/// SLocEntryTable which contains the specified location.
553///
554FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
555 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000557 // After the first and second level caches, I see two common sorts of
558 // behavior: 1) a lot of searched FileID's are "near" the cached file location
559 // or are "near" the cached instantiation location. 2) others are just
560 // completely random and may be a very long way away.
561 //
562 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
563 // then we fall back to a less cache efficient, but more scalable, binary
564 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000566 // See if this is near the file point - worst case we start scanning from the
567 // most newly created FileID.
568 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000570 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
571 // Neither loc prunes our search.
572 I = SLocEntryTable.end();
573 } else {
574 // Perhaps it is near the file point.
575 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
576 }
577
578 // Find the FileID that contains this. "I" is an iterator that points to a
579 // FileID whose offset is known to be larger than SLocOffset.
580 unsigned NumProbes = 0;
581 while (1) {
582 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000583 if (ExternalSLocEntries)
584 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000585 if (I->getOffset() <= SLocOffset) {
586#if 0
587 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
588 I-SLocEntryTable.begin(),
589 I->isInstantiation() ? "inst" : "file",
590 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
591#endif
592 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000593
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000594 // If this isn't an instantiation, remember it. We have good locality
595 // across FileID lookups.
596 if (!I->isInstantiation())
597 LastFileIDLookup = Res;
598 NumLinearScans += NumProbes+1;
599 return Res;
600 }
601 if (++NumProbes == 8)
602 break;
603 }
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000605 // Convert "I" back into an index. We know that it is an entry whose index is
606 // larger than the offset we are looking for.
607 unsigned GreaterIndex = I-SLocEntryTable.begin();
608 // LessIndex - This is the lower bound of the range that we're searching.
609 // We know that the offset corresponding to the FileID is is less than
610 // SLocOffset.
611 unsigned LessIndex = 0;
612 NumProbes = 0;
613 while (1) {
614 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000615 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000617 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000619 // If the offset of the midpoint is too large, chop the high side of the
620 // range to the midpoint.
621 if (MidOffset > SLocOffset) {
622 GreaterIndex = MiddleIndex;
623 continue;
624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000626 // If the middle index contains the value, succeed and return.
627 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
628#if 0
629 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
630 I-SLocEntryTable.begin(),
631 I->isInstantiation() ? "inst" : "file",
632 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
633#endif
634 FileID Res = FileID::get(MiddleIndex);
635
636 // If this isn't an instantiation, remember it. We have good locality
637 // across FileID lookups.
638 if (!I->isInstantiation())
639 LastFileIDLookup = Res;
640 NumBinaryProbes += NumProbes;
641 return Res;
642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000644 // Otherwise, move the low-side up to the middle index.
645 LessIndex = MiddleIndex;
646 }
647}
648
Chris Lattneraddb7972009-01-26 20:04:19 +0000649SourceLocation SourceManager::
650getInstantiationLocSlowCase(SourceLocation Loc) const {
651 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000652 // Note: If Loc indicates an offset into a token that came from a macro
653 // expansion (e.g. the 5th character of the token) we do not want to add
654 // this offset when going to the instantiation location. The instatiation
655 // location is the macro invocation, which the offset has nothing to do
656 // with. This is unlike when we get the spelling loc, because the offset
657 // directly correspond to the token whose spelling we're inspecting.
658 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000659 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000660 } while (!Loc.isFileID());
661
662 return Loc;
663}
664
665SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
666 do {
667 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
668 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
669 Loc = Loc.getFileLocWithOffset(LocInfo.second);
670 } while (!Loc.isFileID());
671 return Loc;
672}
673
674
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000675std::pair<FileID, unsigned>
676SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
677 unsigned Offset) const {
678 // If this is an instantiation record, walk through all the instantiation
679 // points.
680 FileID FID;
681 SourceLocation Loc;
682 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000683 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000685 FID = getFileID(Loc);
686 E = &getSLocEntry(FID);
687 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000688 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000690 return std::make_pair(FID, Offset);
691}
692
693std::pair<FileID, unsigned>
694SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
695 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000696 // If this is an instantiation record, walk through all the instantiation
697 // points.
698 FileID FID;
699 SourceLocation Loc;
700 do {
701 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000703 FID = getFileID(Loc);
704 E = &getSLocEntry(FID);
705 Offset += Loc.getOffset()-E->getOffset();
706 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000708 return std::make_pair(FID, Offset);
709}
710
Chris Lattner387616e2009-02-17 08:04:48 +0000711/// getImmediateSpellingLoc - Given a SourceLocation object, return the
712/// spelling location referenced by the ID. This is the first level down
713/// towards the place where the characters that make up the lexed token can be
714/// found. This should not generally be used by clients.
715SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
716 if (Loc.isFileID()) return Loc;
717 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
718 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
719 return Loc.getFileLocWithOffset(LocInfo.second);
720}
721
722
Chris Lattnere7fb4842009-02-15 20:52:18 +0000723/// getImmediateInstantiationRange - Loc is required to be an instantiation
724/// location. Return the start/end of the instantiation information.
725std::pair<SourceLocation,SourceLocation>
726SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
727 assert(Loc.isMacroID() && "Not an instantiation loc!");
728 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
729 return II.getInstantiationLocRange();
730}
731
Chris Lattner66781332009-02-15 21:26:50 +0000732/// getInstantiationRange - Given a SourceLocation object, return the
733/// range of tokens covered by the instantiation in the ultimate file.
734std::pair<SourceLocation,SourceLocation>
735SourceManager::getInstantiationRange(SourceLocation Loc) const {
736 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner66781332009-02-15 21:26:50 +0000738 std::pair<SourceLocation,SourceLocation> Res =
739 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner66781332009-02-15 21:26:50 +0000741 // Fully resolve the start and end locations to their ultimate instantiation
742 // points.
743 while (!Res.first.isFileID())
744 Res.first = getImmediateInstantiationRange(Res.first).first;
745 while (!Res.second.isFileID())
746 Res.second = getImmediateInstantiationRange(Res.second).second;
747 return Res;
748}
749
Chris Lattnere7fb4842009-02-15 20:52:18 +0000750
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000751
752//===----------------------------------------------------------------------===//
753// Queries about the code at a SourceLocation.
754//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000755
756/// getCharacterData - Return a pointer to the start of the specified location
757/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000758const char *SourceManager::getCharacterData(SourceLocation SL,
759 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 // Note that this is a hot function in the getSpelling() path, which is
761 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000762 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Ted Kremenekc16c2082009-01-06 01:55:26 +0000764 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000765 bool CharDataInvalid = false;
766 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +0000767 = getSLocEntry(LocInfo.first).getFile().getContentCache()
768 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000769 if (Invalid)
770 *Invalid = CharDataInvalid;
771 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000772}
773
Reid Spencer5f016e22007-07-11 17:01:13 +0000774
Chris Lattner9dc1f532007-07-20 16:37:10 +0000775/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000776/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000777unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
778 bool *Invalid) const {
779 bool MyInvalid = false;
780 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
781 if (Invalid)
782 *Invalid = MyInvalid;
783
784 if (MyInvalid)
785 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 unsigned LineStart = FilePos;
788 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
789 --LineStart;
790 return FilePos-LineStart+1;
791}
792
Douglas Gregor50f6af72010-03-16 05:20:39 +0000793unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
794 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000795 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000796 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000797 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000798}
799
Douglas Gregor50f6af72010-03-16 05:20:39 +0000800unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
801 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000802 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000803 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000804 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000805}
806
Chris Lattnere127a0d2010-04-20 20:35:58 +0000807static DISABLE_INLINE void
808ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
809 llvm::BumpPtrAllocator &Alloc,
810 const SourceManager &SM, bool &Invalid);
811static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
812 llvm::BumpPtrAllocator &Alloc,
813 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000814 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000815 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
816 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000817 if (Invalid)
818 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000820 // Find the file offsets of all of the *physical* source lines. This does
821 // not look at trigraphs, escaped newlines, or anything else tricky.
822 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000824 // Line #1 starts at char 0.
825 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000827 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
828 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
829 unsigned Offs = 0;
830 while (1) {
831 // Skip over the contents of the line.
832 // TODO: Vectorize this? This is very performance sensitive for programs
833 // with lots of diagnostics and in -E mode.
834 const unsigned char *NextBuf = (const unsigned char *)Buf;
835 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
836 ++NextBuf;
837 Offs += NextBuf-Buf;
838 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000840 if (Buf[0] == '\n' || Buf[0] == '\r') {
841 // If this is \n\r or \r\n, skip both characters.
842 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
843 ++Offs, ++Buf;
844 ++Offs, ++Buf;
845 LineOffsets.push_back(Offs);
846 } else {
847 // Otherwise, this is a null. If end of file, exit.
848 if (Buf == End) break;
849 // Otherwise, skip the null.
850 ++Offs, ++Buf;
851 }
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000854 // Copy the offsets into the FileInfo structure.
855 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000856 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000857 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
858}
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000860/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000861/// for the position indicated. This requires building and caching a table of
862/// line offsets for the MemoryBuffer, so this is not cheap: use only when
863/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000864unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
865 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000866 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000867 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000868 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000869 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000870 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000871 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000874 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000875 if (Content->SourceLineCache == 0) {
876 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000877 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000878 if (Invalid)
879 *Invalid = MyInvalid;
880 if (MyInvalid)
881 return 1;
882 } else if (Invalid)
883 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
885 // Okay, we know we have a line number table. Do a binary search to find the
886 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000887 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000888 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000889 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner30fc9332009-02-04 01:06:56 +0000891 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000892
Daniel Dunbar4106d692009-05-18 17:30:52 +0000893 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000894 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000895 //
896 // If it is worth being optimized, then in my opinion it could be more
897 // performant, simpler, and more obviously correct by just "galloping" outward
898 // from the queried file position. In fact, this could be incorporated into a
899 // generic algorithm such as lower_bound_with_hint.
900 //
901 // If someone gives me a test case where this matters, and I will do it! - DWD
902
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000903 // If the previous query was to the same file, we know both the file pos from
904 // that query and the line number returned. This allows us to narrow the
905 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000906 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000907 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000908 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000909 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000911 // The query is likely to be nearby the previous one. Here we check to
912 // see if it is within 5, 10 or 20 lines. It can be far away in cases
913 // where big comment blocks and vertical whitespace eat up lines but
914 // contribute no tokens.
915 if (SourceLineCache+5 < SourceLineCacheEnd) {
916 if (SourceLineCache[5] > QueriedFilePos)
917 SourceLineCacheEnd = SourceLineCache+5;
918 else if (SourceLineCache+10 < SourceLineCacheEnd) {
919 if (SourceLineCache[10] > QueriedFilePos)
920 SourceLineCacheEnd = SourceLineCache+10;
921 else if (SourceLineCache+20 < SourceLineCacheEnd) {
922 if (SourceLineCache[20] > QueriedFilePos)
923 SourceLineCacheEnd = SourceLineCache+20;
924 }
925 }
926 }
927 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000928 if (LastLineNoResult < Content->NumLines)
929 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000930 }
931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000933 // If the spread is large, do a "radix" test as our initial guess, based on
934 // the assumption that lines average to approximately the same length.
935 // NOTE: This is currently disabled, as it does not appear to be profitable in
936 // initial measurements.
937 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000938 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000940 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000941 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000943 // Check for -10 and +10 lines.
944 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
945 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
946
947 // If the computed lower bound is less than the query location, move it in.
948 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
949 SourceLineCacheStart[LowerBound] < QueriedFilePos)
950 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000952 // If the computed upper bound is greater than the query location, move it.
953 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
954 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
955 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000958 unsigned *Pos
959 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000960 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner30fc9332009-02-04 01:06:56 +0000962 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000963 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000964 LastLineNoFilePos = QueriedFilePos;
965 LastLineNoResult = LineNo;
966 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000967}
968
Douglas Gregor50f6af72010-03-16 05:20:39 +0000969unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
970 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000971 if (Loc.isInvalid()) return 0;
972 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
973 return getLineNumber(LocInfo.first, LocInfo.second);
974}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000975unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
976 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000977 if (Loc.isInvalid()) return 0;
978 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
979 return getLineNumber(LocInfo.first, LocInfo.second);
980}
981
Chris Lattner6b306672009-02-04 05:33:01 +0000982/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000983/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000984/// header, or an "implicit extern C" system header.
985///
986/// This state can be modified with flags on GNU linemarker directives like:
987/// # 4 "foo.h" 3
988/// which changes all source locations in the current file after that to be
989/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000990SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000991SourceManager::getFileCharacteristic(SourceLocation Loc) const {
992 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
993 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
994 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
995
996 // If there are no #line directives in this file, just return the whole-file
997 // state.
998 if (!FI.hasLineDirectives())
999 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner6b306672009-02-04 05:33:01 +00001001 assert(LineTable && "Can't have linetable entries without a LineTable!");
1002 // See if there is a #line directive before the location.
1003 const LineEntry *Entry =
1004 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner6b306672009-02-04 05:33:01 +00001006 // If this is before the first line marker, use the file characteristic.
1007 if (!Entry)
1008 return FI.getFileCharacteristic();
1009
1010 return Entry->FileKind;
1011}
1012
Chris Lattnerbff5c512009-02-17 08:39:06 +00001013/// Return the filename or buffer identifier of the buffer the location is in.
1014/// Note that this name does not respect #line directives. Use getPresumedLoc
1015/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001016const char *SourceManager::getBufferName(SourceLocation Loc,
1017 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +00001018 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregor50f6af72010-03-16 05:20:39 +00001020 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001021}
1022
Chris Lattner30fc9332009-02-04 01:06:56 +00001023
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001024/// getPresumedLoc - This method returns the "presumed" location of a
1025/// SourceLocation specifies. A "presumed location" can be modified by #line
1026/// or GNU line marker directives. This provides a view on the data that a
1027/// user should see in diagnostics, for example.
1028///
1029/// Note that a presumed location is always given as the instantiation point
1030/// of an instantiation location, not at the spelling location.
1031PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1032 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001034 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001035 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Chris Lattner30fc9332009-02-04 01:06:56 +00001037 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001038 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner3cd949c2009-02-04 01:55:42 +00001040 // To get the source name, first consult the FileEntry (if one exists)
1041 // before the MemBuffer as this will avoid unnecessarily paging in the
1042 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001043 const char *Filename;
1044 if (C->Entry)
1045 Filename = C->Entry->getName();
1046 else
1047 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001048 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1049 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1050 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Chris Lattner3cd949c2009-02-04 01:55:42 +00001052 // If we have #line directives in this file, update and overwrite the physical
1053 // location info if appropriate.
1054 if (FI.hasLineDirectives()) {
1055 assert(LineTable && "Can't have linetable entries without a LineTable!");
1056 // See if there is a #line directive before this. If so, get it.
1057 if (const LineEntry *Entry =
1058 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001059 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001060 if (Entry->FilenameID != -1)
1061 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001062
1063 // Use the line number specified by the LineEntry. This line number may
1064 // be multiple lines down from the line entry. Add the difference in
1065 // physical line numbers from the query point and the line marker to the
1066 // total.
1067 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1068 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001070 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner137b6a62009-02-04 06:25:26 +00001072 // Handle virtual #include manipulation.
1073 if (Entry->IncludeOffset) {
1074 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1075 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1076 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001077 }
1078 }
1079
1080 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001081}
1082
1083//===----------------------------------------------------------------------===//
1084// Other miscellaneous methods.
1085//===----------------------------------------------------------------------===//
1086
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001087/// \brief Get the source location for the given file:line:col triplet.
1088///
1089/// If the source file is included multiple times, the source location will
1090/// be based upon the first inclusion.
1091SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1092 unsigned Line, unsigned Col) const {
1093 assert(SourceFile && "Null source file!");
1094 assert(Line && Col && "Line and column should start from 1!");
1095
1096 fileinfo_iterator FI = FileInfos.find(SourceFile);
1097 if (FI == FileInfos.end())
1098 return SourceLocation();
1099 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001101 // If this is the first use of line information for this buffer, compute the
1102 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001103 if (Content->SourceLineCache == 0) {
1104 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001105 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001106 if (MyInvalid)
1107 return SourceLocation();
1108 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001109
Douglas Gregor4a160e12009-12-02 05:34:39 +00001110 // Find the first file ID that corresponds to the given file.
1111 FileID FirstFID;
1112
1113 // First, check the main file ID, since it is common to look for a
1114 // location in the main file.
1115 if (!MainFileID.isInvalid()) {
1116 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1117 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1118 FirstFID = MainFileID;
1119 }
1120
1121 if (FirstFID.isInvalid()) {
1122 // The location we're looking for isn't in the main file; look
1123 // through all of the source locations.
1124 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1125 const SLocEntry &SLoc = getSLocEntry(I);
1126 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1127 FirstFID = FileID::get(I);
1128 break;
1129 }
1130 }
1131 }
1132
1133 if (FirstFID.isInvalid())
1134 return SourceLocation();
1135
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001136 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001137 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001138 if (Size > 0)
1139 --Size;
1140 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1141 }
1142
1143 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001144 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1145 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001146 unsigned i = 0;
1147
1148 // Check that the given column is valid.
1149 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1150 ++i;
1151 if (i < Col-1)
1152 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1153
Douglas Gregor4a160e12009-12-02 05:34:39 +00001154 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001155}
1156
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001157/// \brief Determines the order of 2 source locations in the translation unit.
1158///
1159/// \returns true if LHS source location comes before RHS, false otherwise.
1160bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1161 SourceLocation RHS) const {
1162 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1163 if (LHS == RHS)
1164 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001166 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1167 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001169 // If the source locations are in the same file, just compare offsets.
1170 if (LOffs.first == ROffs.first)
1171 return LOffs.second < ROffs.second;
1172
1173 // If we are comparing a source location with multiple locations in the same
1174 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001176 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1177 LastRFIDForBeforeTUCheck == ROffs.first)
1178 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001180 LastLFIDForBeforeTUCheck = LOffs.first;
1181 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001183 // "Traverse" the include/instantiation stacks of both locations and try to
1184 // find a common "ancestor".
1185 //
1186 // First we traverse the stack of the right location and check each level
1187 // against the level of the left location, while collecting all levels in a
1188 // "stack map".
1189
1190 std::map<FileID, unsigned> ROffsMap;
1191 ROffsMap[ROffs.first] = ROffs.second;
1192
1193 while (1) {
1194 SourceLocation UpperLoc;
1195 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1196 if (Entry.isInstantiation())
1197 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1198 else
1199 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001201 if (UpperLoc.isInvalid())
1202 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001204 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001206 if (LOffs.first == ROffs.first)
1207 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001209 ROffsMap[ROffs.first] = ROffs.second;
1210 }
1211
1212 // We didn't find a common ancestor. Now traverse the stack of the left
1213 // location, checking against the stack map of the right location.
1214
1215 while (1) {
1216 SourceLocation UpperLoc;
1217 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1218 if (Entry.isInstantiation())
1219 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1220 else
1221 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001223 if (UpperLoc.isInvalid())
1224 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001226 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001228 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1229 if (I != ROffsMap.end())
1230 return LastResForBeforeTUCheck = LOffs.second < I->second;
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001233 // There is no common ancestor, most probably because one location is in the
1234 // predefines buffer.
1235 //
1236 // FIXME: We should rearrange the external interface so this simply never
1237 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001239 // If exactly one location is a memory buffer, assume it preceeds the other.
1240 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1241 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1242 if (LIsMB != RIsMB)
1243 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001245 // Otherwise, just assume FileIDs were created in order.
1246 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001247}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249/// PrintStats - Print statistics to stderr.
1250///
1251void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001252 llvm::errs() << "\n*** Source Manager Stats:\n";
1253 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1254 << " mem buffers mapped.\n";
1255 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1256 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 unsigned NumLineNumsComputed = 0;
1259 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001260 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1261 NumLineNumsComputed += I->second->SourceLineCache != 0;
1262 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001265 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1266 << NumLineNumsComputed << " files with line #'s computed.\n";
1267 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1268 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001269}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001270
1271ExternalSLocEntrySource::~ExternalSLocEntrySource() { }