blob: c76624139a08c4e20fd2d6876920eec18f9a1d49 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregora07ebc52009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000017#include "clang/Basic/FileManager.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000023#include <string>
Douglas Gregore0fbb832010-03-16 00:06:06 +000024#include <cstring>
Douglas Gregor802b7762010-03-15 22:54:52 +000025
Chris Lattner22eb9722006-06-18 05:43:12 +000026using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000027using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000028using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000029
Chris Lattner153a0f12009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000033
Ted Kremenekc08bca62007-10-30 21:08:08 +000034ContentCache::~ContentCache() {
Douglas Gregor82752ec2010-03-16 22:53:51 +000035 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000036}
37
Ted Kremenek12c2af42009-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 Gregor82752ec2010-03-16 22:53:51 +000042 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-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 Gregor53ad6b92009-12-02 06:49:09 +000048/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000049unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000050 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
51 : (unsigned) Entry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000052}
53
Douglas Gregor53ad6b92009-12-02 06:49:09 +000054void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregor82752ec2010-03-16 22:53:51 +000055 assert(B != Buffer.getPointer());
Douglas Gregor53ad6b92009-12-02 06:49:09 +000056
Douglas Gregor82752ec2010-03-16 22:53:51 +000057 delete Buffer.getPointer();
58 Buffer.setPointer(B);
59 Buffer.setInt(false);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000060}
61
Douglas Gregor874cc622010-03-16 00:35:39 +000062const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
63 bool *Invalid) const {
64 if (Invalid)
65 *Invalid = false;
66
Ted Kremenek763ea552009-01-06 22:43:04 +000067 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregor82752ec2010-03-16 22:53:51 +000068 if (!Buffer.getPointer() && Entry) {
Douglas Gregor802b7762010-03-15 22:54:52 +000069 std::string ErrorStr;
70 struct stat FileInfo;
Douglas Gregor82752ec2010-03-16 22:53:51 +000071 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
72 Entry->getSize(), &FileInfo));
73 Buffer.setInt(false);
74
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000075 // If we were unable to open the file, then we are in an inconsistent
76 // situation where the content cache referenced a file which no longer
77 // exists. Most likely, we were using a stat cache with an invalid entry but
78 // the file could also have been removed during processing. Since we can't
79 // really deal with this situation, just create an empty buffer.
80 //
81 // FIXME: This is definitely not ideal, but our immediate clients can't
82 // currently handle returning a null entry here. Ideally we should detect
83 // that we are in an inconsistent situation and error out as quickly as
84 // possible.
Douglas Gregor82752ec2010-03-16 22:53:51 +000085 if (!Buffer.getPointer()) {
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000086 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregor82752ec2010-03-16 22:53:51 +000087 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
88 "<invalid>"));
89 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar7cea5f12009-12-06 05:43:36 +000090 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
91 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor85795312010-03-22 15:10:57 +000092
93 if (Diag.isDiagnosticInFlight())
94 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
95 Entry->getName(), ErrorStr);
96 else
97 Diag.Report(diag::err_cannot_open_file)
98 << Entry->getName() << ErrorStr;
99
Douglas Gregor82752ec2010-03-16 22:53:51 +0000100 Buffer.setInt(true);
Daniel Dunbar584344f2010-04-10 01:17:16 +0000101
102 // FIXME: This conditionalization is horrible, but we see spurious failures
103 // in the test suite due to this warning and no one has had time to hunt it
104 // down. So for now, we just don't emit this diagnostic on Win32, and hope
105 // nothing bad happens.
106 //
107 // PR6812.
Douglas Gregor08288f22010-04-09 15:54:22 +0000108#if !defined(LLVM_ON_WIN32)
Daniel Dunbar584344f2010-04-10 01:17:16 +0000109 } else if (FileInfo.st_size != Entry->getSize() ||
110 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor08288f22010-04-09 15:54:22 +0000111 // Check that the file's size and modification time are the same
112 // as in the file entry (which may have come from a stat cache).
Douglas Gregor85795312010-03-22 15:10:57 +0000113 if (Diag.isDiagnosticInFlight())
Daniel Dunbar584344f2010-04-10 01:17:16 +0000114 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor85795312010-03-22 15:10:57 +0000115 Entry->getName());
Daniel Dunbar584344f2010-04-10 01:17:16 +0000116 else
Douglas Gregor85795312010-03-22 15:10:57 +0000117 Diag.Report(diag::err_file_modified) << Entry->getName();
118
Douglas Gregor6597f592010-03-17 15:30:15 +0000119 Buffer.setInt(true);
Daniel Dunbar584344f2010-04-10 01:17:16 +0000120#endif
Daniel Dunbar7cea5f12009-12-06 05:43:36 +0000121 }
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000122
123 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
124 // (BOM). We only support UTF-8 without a BOM right now. See
125 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
126 if (!Buffer.getInt()) {
127 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
128 const char *BOM = 0;
129 if (BufStr.startswith("\xFE\xBB\xBF"))
130 BOM = "UTF-8";
131 else if (BufStr.startswith("\xFE\xFF"))
132 BOM = "UTF-16 (BE)";
133 else if (BufStr.startswith("\xFF\xFE"))
134 BOM = "UTF-16 (LE)";
135 else if (BufStr.startswith(llvm::StringRef("\x00\x00\xFE\xFF", 4)))
136 BOM = "UTF-32 (BE)";
137 else if (BufStr.startswith(llvm::StringRef("\xFF\xFE\x00\x00", 4)))
138 BOM = "UTF-32 (LE)";
139 else if (BufStr.startswith("\x2B\x2F\x76"))
140 BOM = "UTF-7";
141 else if (BufStr.startswith("\xF7\x64\x4C"))
142 BOM = "UTF-1";
143 else if (BufStr.startswith("\xDD\x73\x66\x73"))
144 BOM = "UTF-EBCDIC";
145 else if (BufStr.startswith("\x0E\xFE\xFF"))
146 BOM = "SDSU";
147 else if (BufStr.startswith("\xFB\xEE\x28"))
148 BOM = "BOCU-1";
149 else if (BufStr.startswith("\x84\x31\x95\x33"))
150 BOM = "BOCU-1";
151
152 if (BOM) {
153 Diag.Report(diag::err_unsupported_bom) << BOM << Entry->getName();
154 Buffer.setInt(1);
155 }
156 }
Ted Kremenek763ea552009-01-06 22:43:04 +0000157 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000158
Douglas Gregor82752ec2010-03-16 22:53:51 +0000159 if (Invalid)
160 *Invalid = Buffer.getInt();
161
162 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000163}
164
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000165unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
166 // Look up the filename in the string table, returning the pre-existing value
167 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000168 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000169 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
170 if (Entry.getValue() != ~0U)
171 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000173 // Otherwise, assign this the next available ID.
174 Entry.setValue(FilenamesByID.size());
175 FilenamesByID.push_back(&Entry);
176 return FilenamesByID.size()-1;
177}
178
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000179/// AddLineNote - Add a line note to the line table that indicates that there
180/// is a #line at the specified FID/Offset location which changes the presumed
181/// location to LineNo/FilenameID.
Chris Lattner153a0f12009-02-04 00:40:31 +0000182void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000183 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000184 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner153a0f12009-02-04 00:40:31 +0000186 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
187 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000189 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000190 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000192 if (!Entries.empty()) {
193 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
194 // that we are still in "foo.h".
195 if (FilenameID == -1)
196 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner1c967782009-02-04 06:25:26 +0000198 // If we are after a line marker that switched us to system header mode, or
199 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000200 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000201 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner1c967782009-02-04 06:25:26 +0000204 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
205 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000206}
207
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000208/// AddLineNote This is the same as the previous version of AddLineNote, but is
209/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
210/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
211/// this is a file exit. FileKind specifies whether this is a system header or
212/// extern C system header.
213void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
214 unsigned LineNo, int FilenameID,
215 unsigned EntryExit,
216 SrcMgr::CharacteristicKind FileKind) {
217 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000218
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000219 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000221 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
222 "Adding line entries out of order!");
223
Chris Lattner1c967782009-02-04 06:25:26 +0000224 unsigned IncludeOffset = 0;
225 if (EntryExit == 0) { // No #include stack change.
226 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
227 } else if (EntryExit == 1) {
228 IncludeOffset = Offset-1;
229 } else if (EntryExit == 2) {
230 assert(!Entries.empty() && Entries.back().IncludeOffset &&
231 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000232
Chris Lattner1c967782009-02-04 06:25:26 +0000233 // Get the include loc of the last entries' include loc as our include loc.
234 IncludeOffset = 0;
235 if (const LineEntry *PrevEntry =
236 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
237 IncludeOffset = PrevEntry->IncludeOffset;
238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattner1c967782009-02-04 06:25:26 +0000240 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
241 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000242}
243
244
Chris Lattnerd4293922009-02-04 01:55:42 +0000245/// FindNearestLineEntry - Find the line entry nearest to FID that is before
246/// it. If there is no line entry before Offset in FID, return null.
Mike Stump11289f42009-09-09 15:08:12 +0000247const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000248 unsigned Offset) {
249 const std::vector<LineEntry> &Entries = LineEntries[FID];
250 assert(!Entries.empty() && "No #line entries for this FID after all!");
251
Chris Lattner334a2ad2009-02-04 04:46:59 +0000252 // It is very common for the query to be after the last #line, check this
253 // first.
254 if (Entries.back().FileOffset <= Offset)
255 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000256
Chris Lattner334a2ad2009-02-04 04:46:59 +0000257 // Do a binary search to find the maximal element that is still before Offset.
258 std::vector<LineEntry>::const_iterator I =
259 std::upper_bound(Entries.begin(), Entries.end(), Offset);
260 if (I == Entries.begin()) return 0;
261 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000262}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000263
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000264/// \brief Add a new line entry that has already been encoded into
265/// the internal representation of the line table.
Mike Stump11289f42009-09-09 15:08:12 +0000266void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000267 const std::vector<LineEntry> &Entries) {
268 LineEntries[FID] = Entries;
269}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000270
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000271/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000272///
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000273unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
274 if (LineTable == 0)
275 LineTable = new LineTableInfo();
276 return LineTable->getLineTableFilenameID(Ptr, Len);
277}
278
279
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000280/// AddLineNote - Add a line note to the line table for the FileID and offset
281/// specified by Loc. If FilenameID is -1, it is considered to be
282/// unspecified.
283void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
284 int FilenameID) {
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000285 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000287 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
288
289 // Remember that this file has #line directives now if it doesn't already.
290 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000292 if (LineTable == 0)
293 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000294 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000295}
296
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000297/// AddLineNote - Add a GNU line marker to the line table.
298void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
299 int FilenameID, bool IsFileEntry,
300 bool IsFileExit, bool IsSystemHeader,
301 bool IsExternCHeader) {
302 // If there is no filename and no flags, this is treated just like a #line,
303 // which does not change the flags of the previous line marker.
304 if (FilenameID == -1) {
305 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
306 "Can't set flags without setting the filename!");
307 return AddLineNote(Loc, LineNo, FilenameID);
308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000310 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
311 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000313 // Remember that this file has #line directives now if it doesn't already.
314 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000315
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000316 if (LineTable == 0)
317 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000319 SrcMgr::CharacteristicKind FileKind;
320 if (IsExternCHeader)
321 FileKind = SrcMgr::C_ExternCSystem;
322 else if (IsSystemHeader)
323 FileKind = SrcMgr::C_System;
324 else
325 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000327 unsigned EntryExit = 0;
328 if (IsFileEntry)
329 EntryExit = 1;
330 else if (IsFileExit)
331 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000333 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
334 EntryExit, FileKind);
335}
336
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000337LineTableInfo &SourceManager::getLineTable() {
338 if (LineTable == 0)
339 LineTable = new LineTableInfo();
340 return *LineTable;
341}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000342
Chris Lattner153a0f12009-02-04 00:40:31 +0000343//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000344// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000345//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000346
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000347SourceManager::~SourceManager() {
348 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000349
Chris Lattnerc8233df2009-02-03 07:30:45 +0000350 // Delete FileEntry objects corresponding to content caches. Since the actual
351 // content cache objects are bump pointer allocated, we just have to run the
352 // dtors, but we call the deallocate method for completeness.
353 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
354 MemBufferInfos[i]->~ContentCache();
355 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
356 }
357 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
358 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
359 I->second->~ContentCache();
360 ContentCacheAlloc.Deallocate(I->second);
361 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000362}
363
364void SourceManager::clearIDTables() {
365 MainFileID = FileID();
366 SLocEntryTable.clear();
367 LastLineNoFileIDQuery = FileID();
368 LastLineNoContentCache = 0;
369 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000371 if (LineTable)
372 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000374 // Use up FileID #0 as an invalid instantiation.
375 NextOffset = 0;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000376 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000377}
378
Chris Lattner4fa23622009-01-26 00:43:02 +0000379/// getOrCreateContentCache - Create or return a cached ContentCache for the
380/// specified file.
381const ContentCache *
382SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000383 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattner22eb9722006-06-18 05:43:12 +0000385 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000386 ContentCache *&Entry = FileInfos[FileEnt];
387 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000389 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
390 // so that FileInfo can use the low 3 bits of the pointer for its own
391 // nefarious purposes.
392 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
393 EntryAlign = std::max(8U, EntryAlign);
394 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000395 new (Entry) ContentCache(FileEnt);
396 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000397}
398
399
Ted Kremenek08bed092007-10-31 17:53:38 +0000400/// createMemBufferContentCache - Create a new ContentCache for the specified
401/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000402const ContentCache*
403SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000404 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
405 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
406 // the pointer for its own nefarious purposes.
407 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
408 EntryAlign = std::max(8U, EntryAlign);
409 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000410 new (Entry) ContentCache();
411 MemBufferInfos.push_back(Entry);
412 Entry->setBuffer(Buffer);
413 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000414}
415
Douglas Gregor258ae542009-04-27 06:38:32 +0000416void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
417 unsigned NumSLocEntries,
418 unsigned NextOffset) {
419 ExternalSLocEntries = Source;
420 this->NextOffset = NextOffset;
421 SLocEntryLoaded.resize(NumSLocEntries + 1);
422 SLocEntryLoaded[0] = true;
423 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
424}
425
Douglas Gregor0bc12932009-04-27 21:28:04 +0000426void SourceManager::ClearPreallocatedSLocEntries() {
427 unsigned I = 0;
428 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
429 if (!SLocEntryLoaded[I])
430 break;
431
432 // We've already loaded all preallocated source location entries.
433 if (I == SLocEntryLoaded.size())
434 return;
435
436 // Remove everything from location I onward.
437 SLocEntryTable.resize(I);
438 SLocEntryLoaded.clear();
439 ExternalSLocEntries = 0;
440}
441
Douglas Gregor258ae542009-04-27 06:38:32 +0000442
Chris Lattner4fa23622009-01-26 00:43:02 +0000443//===----------------------------------------------------------------------===//
444// Methods to create new FileID's and instantiations.
445//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000446
Nico Weber378c5532008-09-29 00:25:48 +0000447/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000448/// include position. This works regardless of whether the ContentCache
449/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000450FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000451 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000452 SrcMgr::CharacteristicKind FileCharacter,
453 unsigned PreallocatedID,
454 unsigned Offset) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000455 if (PreallocatedID) {
456 // If we're filling in a preallocated ID, just load in the file
457 // entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000458 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000459 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000460 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000461 "Source location entry already loaded");
462 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump11289f42009-09-09 15:08:12 +0000463 SLocEntryTable[PreallocatedID]
Douglas Gregor258ae542009-04-27 06:38:32 +0000464 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
465 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000466 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor51c23512010-03-19 06:12:06 +0000467 return FID;
Douglas Gregor258ae542009-04-27 06:38:32 +0000468 }
469
Mike Stump11289f42009-09-09 15:08:12 +0000470 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattner4fa23622009-01-26 00:43:02 +0000471 FileInfo::get(IncludePos, File,
472 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000473 unsigned FileSize = File->getSize();
Chris Lattner4fa23622009-01-26 00:43:02 +0000474 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
475 NextOffset += FileSize+1;
Mike Stump11289f42009-09-09 15:08:12 +0000476
Chris Lattner4fa23622009-01-26 00:43:02 +0000477 // Set LastFileIDLookup to the newly created file. The next getFileID call is
478 // almost guaranteed to be from that file.
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000479 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000480 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000481}
482
Chris Lattner4fa23622009-01-26 00:43:02 +0000483/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattner53e384f2009-01-16 07:00:02 +0000484/// that a token from SpellingLoc should actually be referenced from
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000485/// InstantiationLoc.
Chris Lattner4fa23622009-01-26 00:43:02 +0000486SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000487 SourceLocation ILocStart,
488 SourceLocation ILocEnd,
Douglas Gregor258ae542009-04-27 06:38:32 +0000489 unsigned TokLength,
490 unsigned PreallocatedID,
491 unsigned Offset) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000492 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000493 if (PreallocatedID) {
494 // If we're filling in a preallocated ID, just load in the
495 // instantiation entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000496 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000497 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000498 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000499 "Source location entry already loaded");
500 assert(Offset && "Preallocate source location cannot have zero offset");
501 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
502 SLocEntryLoaded[PreallocatedID] = true;
503 return SourceLocation::getMacroLoc(Offset);
504 }
Chris Lattner9dc9c202009-02-15 20:52:18 +0000505 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner4fa23622009-01-26 00:43:02 +0000506 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
507 NextOffset += TokLength+1;
508 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000509}
510
Douglas Gregor874cc622010-03-16 00:35:39 +0000511const llvm::MemoryBuffer *
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000512SourceManager::getMemoryBufferForFile(const FileEntry *File,
513 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000514 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000515 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000516 return IR->getBuffer(Diag, Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000517}
518
519bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
520 const llvm::MemoryBuffer *Buffer) {
521 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
522 if (IR == 0)
523 return true;
524
525 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
526 return false;
527}
528
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000529llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000530 bool MyInvalid = false;
531 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000532 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000533 *Invalid = MyInvalid;
534
535 if (MyInvalid)
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000536 return "";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000537
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000538 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000539}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000540
Chris Lattner153a0f12009-02-04 00:40:31 +0000541//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000542// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000543//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000544
545/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
546/// method that is used for all SourceManager queries that start with a
547/// SourceLocation object. It is responsible for finding the entry in
548/// SLocEntryTable which contains the specified location.
549///
550FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
551 assert(SLocOffset && "Invalid FileID");
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattner4fa23622009-01-26 00:43:02 +0000553 // After the first and second level caches, I see two common sorts of
554 // behavior: 1) a lot of searched FileID's are "near" the cached file location
555 // or are "near" the cached instantiation location. 2) others are just
556 // completely random and may be a very long way away.
557 //
558 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
559 // then we fall back to a less cache efficient, but more scalable, binary
560 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattner4fa23622009-01-26 00:43:02 +0000562 // See if this is near the file point - worst case we start scanning from the
563 // most newly created FileID.
564 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner4fa23622009-01-26 00:43:02 +0000566 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
567 // Neither loc prunes our search.
568 I = SLocEntryTable.end();
569 } else {
570 // Perhaps it is near the file point.
571 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
572 }
573
574 // Find the FileID that contains this. "I" is an iterator that points to a
575 // FileID whose offset is known to be larger than SLocOffset.
576 unsigned NumProbes = 0;
577 while (1) {
578 --I;
Douglas Gregor258ae542009-04-27 06:38:32 +0000579 if (ExternalSLocEntries)
580 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattner4fa23622009-01-26 00:43:02 +0000581 if (I->getOffset() <= SLocOffset) {
582#if 0
583 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
584 I-SLocEntryTable.begin(),
585 I->isInstantiation() ? "inst" : "file",
586 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
587#endif
588 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor258ae542009-04-27 06:38:32 +0000589
Chris Lattner4fa23622009-01-26 00:43:02 +0000590 // If this isn't an instantiation, remember it. We have good locality
591 // across FileID lookups.
592 if (!I->isInstantiation())
593 LastFileIDLookup = Res;
594 NumLinearScans += NumProbes+1;
595 return Res;
596 }
597 if (++NumProbes == 8)
598 break;
599 }
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner4fa23622009-01-26 00:43:02 +0000601 // Convert "I" back into an index. We know that it is an entry whose index is
602 // larger than the offset we are looking for.
603 unsigned GreaterIndex = I-SLocEntryTable.begin();
604 // LessIndex - This is the lower bound of the range that we're searching.
605 // We know that the offset corresponding to the FileID is is less than
606 // SLocOffset.
607 unsigned LessIndex = 0;
608 NumProbes = 0;
609 while (1) {
610 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor258ae542009-04-27 06:38:32 +0000611 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump11289f42009-09-09 15:08:12 +0000612
Chris Lattner4fa23622009-01-26 00:43:02 +0000613 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000614
Chris Lattner4fa23622009-01-26 00:43:02 +0000615 // If the offset of the midpoint is too large, chop the high side of the
616 // range to the midpoint.
617 if (MidOffset > SLocOffset) {
618 GreaterIndex = MiddleIndex;
619 continue;
620 }
Mike Stump11289f42009-09-09 15:08:12 +0000621
Chris Lattner4fa23622009-01-26 00:43:02 +0000622 // If the middle index contains the value, succeed and return.
623 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
624#if 0
625 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
626 I-SLocEntryTable.begin(),
627 I->isInstantiation() ? "inst" : "file",
628 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
629#endif
630 FileID Res = FileID::get(MiddleIndex);
631
632 // If this isn't an instantiation, remember it. We have good locality
633 // across FileID lookups.
634 if (!I->isInstantiation())
635 LastFileIDLookup = Res;
636 NumBinaryProbes += NumProbes;
637 return Res;
638 }
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattner4fa23622009-01-26 00:43:02 +0000640 // Otherwise, move the low-side up to the middle index.
641 LessIndex = MiddleIndex;
642 }
643}
644
Chris Lattner659ac5f2009-01-26 20:04:19 +0000645SourceLocation SourceManager::
646getInstantiationLocSlowCase(SourceLocation Loc) const {
647 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000648 // Note: If Loc indicates an offset into a token that came from a macro
649 // expansion (e.g. the 5th character of the token) we do not want to add
650 // this offset when going to the instantiation location. The instatiation
651 // location is the macro invocation, which the offset has nothing to do
652 // with. This is unlike when we get the spelling loc, because the offset
653 // directly correspond to the token whose spelling we're inspecting.
654 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattner9dc9c202009-02-15 20:52:18 +0000655 .getInstantiationLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000656 } while (!Loc.isFileID());
657
658 return Loc;
659}
660
661SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
662 do {
663 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
664 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
665 Loc = Loc.getFileLocWithOffset(LocInfo.second);
666 } while (!Loc.isFileID());
667 return Loc;
668}
669
670
Chris Lattner4fa23622009-01-26 00:43:02 +0000671std::pair<FileID, unsigned>
672SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
673 unsigned Offset) const {
674 // If this is an instantiation record, walk through all the instantiation
675 // points.
676 FileID FID;
677 SourceLocation Loc;
678 do {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000679 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner4fa23622009-01-26 00:43:02 +0000681 FID = getFileID(Loc);
682 E = &getSLocEntry(FID);
683 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000684 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattner4fa23622009-01-26 00:43:02 +0000686 return std::make_pair(FID, Offset);
687}
688
689std::pair<FileID, unsigned>
690SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
691 unsigned Offset) const {
Chris Lattner31af4e02009-01-26 19:41:58 +0000692 // If this is an instantiation record, walk through all the instantiation
693 // points.
694 FileID FID;
695 SourceLocation Loc;
696 do {
697 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattner31af4e02009-01-26 19:41:58 +0000699 FID = getFileID(Loc);
700 E = &getSLocEntry(FID);
701 Offset += Loc.getOffset()-E->getOffset();
702 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattner4fa23622009-01-26 00:43:02 +0000704 return std::make_pair(FID, Offset);
705}
706
Chris Lattner8ad52d52009-02-17 08:04:48 +0000707/// getImmediateSpellingLoc - Given a SourceLocation object, return the
708/// spelling location referenced by the ID. This is the first level down
709/// towards the place where the characters that make up the lexed token can be
710/// found. This should not generally be used by clients.
711SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
712 if (Loc.isFileID()) return Loc;
713 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
714 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
715 return Loc.getFileLocWithOffset(LocInfo.second);
716}
717
718
Chris Lattner9dc9c202009-02-15 20:52:18 +0000719/// getImmediateInstantiationRange - Loc is required to be an instantiation
720/// location. Return the start/end of the instantiation information.
721std::pair<SourceLocation,SourceLocation>
722SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
723 assert(Loc.isMacroID() && "Not an instantiation loc!");
724 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
725 return II.getInstantiationLocRange();
726}
727
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000728/// getInstantiationRange - Given a SourceLocation object, return the
729/// range of tokens covered by the instantiation in the ultimate file.
730std::pair<SourceLocation,SourceLocation>
731SourceManager::getInstantiationRange(SourceLocation Loc) const {
732 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000734 std::pair<SourceLocation,SourceLocation> Res =
735 getImmediateInstantiationRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000737 // Fully resolve the start and end locations to their ultimate instantiation
738 // points.
739 while (!Res.first.isFileID())
740 Res.first = getImmediateInstantiationRange(Res.first).first;
741 while (!Res.second.isFileID())
742 Res.second = getImmediateInstantiationRange(Res.second).second;
743 return Res;
744}
745
Chris Lattner9dc9c202009-02-15 20:52:18 +0000746
Chris Lattner4fa23622009-01-26 00:43:02 +0000747
748//===----------------------------------------------------------------------===//
749// Queries about the code at a SourceLocation.
750//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000751
Chris Lattnerd01e2912006-06-18 16:22:51 +0000752/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000753/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000754const char *SourceManager::getCharacterData(SourceLocation SL,
755 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000756 // Note that this is a hot function in the getSpelling() path, which is
757 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000758 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000759
Ted Kremenek12c2af42009-01-06 01:55:26 +0000760 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000761 bool CharDataInvalid = false;
762 const llvm::MemoryBuffer *Buffer
763 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
764 &CharDataInvalid);
765 if (Invalid)
766 *Invalid = CharDataInvalid;
767 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000768}
769
Chris Lattner685730f2006-06-26 01:36:22 +0000770
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000771/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000772/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000773unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
774 bool *Invalid) const {
775 bool MyInvalid = false;
776 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
777 if (Invalid)
778 *Invalid = MyInvalid;
779
780 if (MyInvalid)
781 return 1;
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner22eb9722006-06-18 05:43:12 +0000783 unsigned LineStart = FilePos;
784 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
785 --LineStart;
786 return FilePos-LineStart+1;
787}
788
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000789unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
790 bool *Invalid) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000791 if (Loc.isInvalid()) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000792 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000793 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000794}
795
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000796unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
797 bool *Invalid) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000798 if (Loc.isInvalid()) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000799 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000800 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000801}
802
Douglas Gregor874cc622010-03-16 00:35:39 +0000803static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
804 ContentCache* FI,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000805 llvm::BumpPtrAllocator &Alloc,
806 bool &Invalid);
Douglas Gregor874cc622010-03-16 00:35:39 +0000807static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000808 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +0000809 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000810 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
811 if (Invalid)
812 return;
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattner8996fff2007-07-24 05:57:19 +0000814 // Find the file offsets of all of the *physical* source lines. This does
815 // not look at trigraphs, escaped newlines, or anything else tricky.
816 std::vector<unsigned> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattner8996fff2007-07-24 05:57:19 +0000818 // Line #1 starts at char 0.
819 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner8996fff2007-07-24 05:57:19 +0000821 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
822 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
823 unsigned Offs = 0;
824 while (1) {
825 // Skip over the contents of the line.
826 // TODO: Vectorize this? This is very performance sensitive for programs
827 // with lots of diagnostics and in -E mode.
828 const unsigned char *NextBuf = (const unsigned char *)Buf;
829 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
830 ++NextBuf;
831 Offs += NextBuf-Buf;
832 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000833
Chris Lattner8996fff2007-07-24 05:57:19 +0000834 if (Buf[0] == '\n' || Buf[0] == '\r') {
835 // If this is \n\r or \r\n, skip both characters.
836 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
837 ++Offs, ++Buf;
838 ++Offs, ++Buf;
839 LineOffsets.push_back(Offs);
840 } else {
841 // Otherwise, this is a null. If end of file, exit.
842 if (Buf == End) break;
843 // Otherwise, skip the null.
844 ++Offs, ++Buf;
845 }
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattner8996fff2007-07-24 05:57:19 +0000848 // Copy the offsets into the FileInfo structure.
849 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000850 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +0000851 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
852}
Chris Lattner9a13bde2006-06-21 04:57:09 +0000853
Chris Lattner53e384f2009-01-16 07:00:02 +0000854/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +0000855/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +0000856/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +0000857/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000858unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
859 bool *Invalid) const {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000860 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000861 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +0000862 Content = LastLineNoContentCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000863 else
Chris Lattner88ea93e2009-02-04 01:06:56 +0000864 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner4fa23622009-01-26 00:43:02 +0000865 .getFile().getContentCache());
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner22eb9722006-06-18 05:43:12 +0000867 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +0000868 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000869 if (Content->SourceLineCache == 0) {
870 bool MyInvalid = false;
871 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
872 if (Invalid)
873 *Invalid = MyInvalid;
874 if (MyInvalid)
875 return 1;
876 } else if (Invalid)
877 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000878
879 // Okay, we know we have a line number table. Do a binary search to find the
880 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000881 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000882 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000883 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattner88ea93e2009-02-04 01:06:56 +0000885 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000886
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000887 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +0000888 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000889 //
890 // If it is worth being optimized, then in my opinion it could be more
891 // performant, simpler, and more obviously correct by just "galloping" outward
892 // from the queried file position. In fact, this could be incorporated into a
893 // generic algorithm such as lower_bound_with_hint.
894 //
895 // If someone gives me a test case where this matters, and I will do it! - DWD
896
Chris Lattner8996fff2007-07-24 05:57:19 +0000897 // If the previous query was to the same file, we know both the file pos from
898 // that query and the line number returned. This allows us to narrow the
899 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000900 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +0000901 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000902 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +0000903 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Chris Lattner8996fff2007-07-24 05:57:19 +0000905 // The query is likely to be nearby the previous one. Here we check to
906 // see if it is within 5, 10 or 20 lines. It can be far away in cases
907 // where big comment blocks and vertical whitespace eat up lines but
908 // contribute no tokens.
909 if (SourceLineCache+5 < SourceLineCacheEnd) {
910 if (SourceLineCache[5] > QueriedFilePos)
911 SourceLineCacheEnd = SourceLineCache+5;
912 else if (SourceLineCache+10 < SourceLineCacheEnd) {
913 if (SourceLineCache[10] > QueriedFilePos)
914 SourceLineCacheEnd = SourceLineCache+10;
915 else if (SourceLineCache+20 < SourceLineCacheEnd) {
916 if (SourceLineCache[20] > QueriedFilePos)
917 SourceLineCacheEnd = SourceLineCache+20;
918 }
919 }
920 }
921 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000922 if (LastLineNoResult < Content->NumLines)
923 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000924 }
925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner830a77f2007-07-24 06:43:46 +0000927 // If the spread is large, do a "radix" test as our initial guess, based on
928 // the assumption that lines average to approximately the same length.
929 // NOTE: This is currently disabled, as it does not appear to be profitable in
930 // initial measurements.
931 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +0000932 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner830a77f2007-07-24 06:43:46 +0000934 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000935 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattner830a77f2007-07-24 06:43:46 +0000937 // Check for -10 and +10 lines.
938 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
939 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
940
941 // If the computed lower bound is less than the query location, move it in.
942 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
943 SourceLineCacheStart[LowerBound] < QueriedFilePos)
944 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner830a77f2007-07-24 06:43:46 +0000946 // If the computed upper bound is greater than the query location, move it.
947 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
948 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
949 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner830a77f2007-07-24 06:43:46 +0000952 unsigned *Pos
953 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +0000954 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner88ea93e2009-02-04 01:06:56 +0000956 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000957 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +0000958 LastLineNoFilePos = QueriedFilePos;
959 LastLineNoResult = LineNo;
960 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000961}
962
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000963unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
964 bool *Invalid) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000965 if (Loc.isInvalid()) return 0;
966 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
967 return getLineNumber(LocInfo.first, LocInfo.second);
968}
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000969unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
970 bool *Invalid) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000971 if (Loc.isInvalid()) return 0;
972 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
973 return getLineNumber(LocInfo.first, LocInfo.second);
974}
975
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000976/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +0000977/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000978/// header, or an "implicit extern C" system header.
979///
980/// This state can be modified with flags on GNU linemarker directives like:
981/// # 4 "foo.h" 3
982/// which changes all source locations in the current file after that to be
983/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +0000984SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000985SourceManager::getFileCharacteristic(SourceLocation Loc) const {
986 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
987 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
988 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
989
990 // If there are no #line directives in this file, just return the whole-file
991 // state.
992 if (!FI.hasLineDirectives())
993 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000995 assert(LineTable && "Can't have linetable entries without a LineTable!");
996 // See if there is a #line directive before the location.
997 const LineEntry *Entry =
998 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001000 // If this is before the first line marker, use the file characteristic.
1001 if (!Entry)
1002 return FI.getFileCharacteristic();
1003
1004 return Entry->FileKind;
1005}
1006
Chris Lattnera6f037c2009-02-17 08:39:06 +00001007/// Return the filename or buffer identifier of the buffer the location is in.
1008/// Note that this name does not respect #line directives. Use getPresumedLoc
1009/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001010const char *SourceManager::getBufferName(SourceLocation Loc,
1011 bool *Invalid) const {
Chris Lattnera6f037c2009-02-17 08:39:06 +00001012 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001013
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001014 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001015}
1016
Chris Lattner88ea93e2009-02-04 01:06:56 +00001017
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001018/// getPresumedLoc - This method returns the "presumed" location of a
1019/// SourceLocation specifies. A "presumed location" can be modified by #line
1020/// or GNU line marker directives. This provides a view on the data that a
1021/// user should see in diagnostics, for example.
1022///
1023/// Note that a presumed location is always given as the instantiation point
1024/// of an instantiation location, not at the spelling location.
1025PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1026 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001028 // Presumed locations are always for instantiation points.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001029 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001030
Chris Lattner88ea93e2009-02-04 01:06:56 +00001031 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001032 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattnerd4293922009-02-04 01:55:42 +00001034 // To get the source name, first consult the FileEntry (if one exists)
1035 // before the MemBuffer as this will avoid unnecessarily paging in the
1036 // MemBuffer.
Mike Stump11289f42009-09-09 15:08:12 +00001037 const char *Filename =
Douglas Gregor874cc622010-03-16 00:35:39 +00001038 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattnerd4293922009-02-04 01:55:42 +00001039 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1040 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1041 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattnerd4293922009-02-04 01:55:42 +00001043 // If we have #line directives in this file, update and overwrite the physical
1044 // location info if appropriate.
1045 if (FI.hasLineDirectives()) {
1046 assert(LineTable && "Can't have linetable entries without a LineTable!");
1047 // See if there is a #line directive before this. If so, get it.
1048 if (const LineEntry *Entry =
1049 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001050 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001051 if (Entry->FilenameID != -1)
1052 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001053
1054 // Use the line number specified by the LineEntry. This line number may
1055 // be multiple lines down from the line entry. Add the difference in
1056 // physical line numbers from the query point and the line marker to the
1057 // total.
1058 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1059 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattner20c50ba2009-02-04 02:15:40 +00001061 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001062
Chris Lattner1c967782009-02-04 06:25:26 +00001063 // Handle virtual #include manipulation.
1064 if (Entry->IncludeOffset) {
1065 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1066 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1067 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001068 }
1069 }
1070
1071 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001072}
1073
1074//===----------------------------------------------------------------------===//
1075// Other miscellaneous methods.
1076//===----------------------------------------------------------------------===//
1077
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001078/// \brief Get the source location for the given file:line:col triplet.
1079///
1080/// If the source file is included multiple times, the source location will
1081/// be based upon the first inclusion.
1082SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1083 unsigned Line, unsigned Col) const {
1084 assert(SourceFile && "Null source file!");
1085 assert(Line && Col && "Line and column should start from 1!");
1086
1087 fileinfo_iterator FI = FileInfos.find(SourceFile);
1088 if (FI == FileInfos.end())
1089 return SourceLocation();
1090 ContentCache *Content = FI->second;
Mike Stump11289f42009-09-09 15:08:12 +00001091
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001092 // If this is the first use of line information for this buffer, compute the
1093 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001094 if (Content->SourceLineCache == 0) {
1095 bool MyInvalid = false;
1096 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1097 if (MyInvalid)
1098 return SourceLocation();
1099 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001100
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001101 // Find the first file ID that corresponds to the given file.
1102 FileID FirstFID;
1103
1104 // First, check the main file ID, since it is common to look for a
1105 // location in the main file.
1106 if (!MainFileID.isInvalid()) {
1107 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1108 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1109 FirstFID = MainFileID;
1110 }
1111
1112 if (FirstFID.isInvalid()) {
1113 // The location we're looking for isn't in the main file; look
1114 // through all of the source locations.
1115 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1116 const SLocEntry &SLoc = getSLocEntry(I);
1117 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1118 FirstFID = FileID::get(I);
1119 break;
1120 }
1121 }
1122 }
1123
1124 if (FirstFID.isInvalid())
1125 return SourceLocation();
1126
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001127 if (Line > Content->NumLines) {
Douglas Gregor874cc622010-03-16 00:35:39 +00001128 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001129 if (Size > 0)
1130 --Size;
1131 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1132 }
1133
1134 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor874cc622010-03-16 00:35:39 +00001135 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1136 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001137 unsigned i = 0;
1138
1139 // Check that the given column is valid.
1140 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1141 ++i;
1142 if (i < Col-1)
1143 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1144
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001145 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001146}
1147
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001148/// \brief Determines the order of 2 source locations in the translation unit.
1149///
1150/// \returns true if LHS source location comes before RHS, false otherwise.
1151bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1152 SourceLocation RHS) const {
1153 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1154 if (LHS == RHS)
1155 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001157 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1158 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001159
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001160 // If the source locations are in the same file, just compare offsets.
1161 if (LOffs.first == ROffs.first)
1162 return LOffs.second < ROffs.second;
1163
1164 // If we are comparing a source location with multiple locations in the same
1165 // file, we get a big win by caching the result.
Mike Stump11289f42009-09-09 15:08:12 +00001166
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001167 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1168 LastRFIDForBeforeTUCheck == ROffs.first)
1169 return LastResForBeforeTUCheck;
Mike Stump11289f42009-09-09 15:08:12 +00001170
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001171 LastLFIDForBeforeTUCheck = LOffs.first;
1172 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump11289f42009-09-09 15:08:12 +00001173
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001174 // "Traverse" the include/instantiation stacks of both locations and try to
1175 // find a common "ancestor".
1176 //
1177 // First we traverse the stack of the right location and check each level
1178 // against the level of the left location, while collecting all levels in a
1179 // "stack map".
1180
1181 std::map<FileID, unsigned> ROffsMap;
1182 ROffsMap[ROffs.first] = ROffs.second;
1183
1184 while (1) {
1185 SourceLocation UpperLoc;
1186 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1187 if (Entry.isInstantiation())
1188 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1189 else
1190 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001191
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001192 if (UpperLoc.isInvalid())
1193 break; // We reached the top.
Mike Stump11289f42009-09-09 15:08:12 +00001194
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001195 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001197 if (LOffs.first == ROffs.first)
1198 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump11289f42009-09-09 15:08:12 +00001199
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001200 ROffsMap[ROffs.first] = ROffs.second;
1201 }
1202
1203 // We didn't find a common ancestor. Now traverse the stack of the left
1204 // location, checking against the stack map of the right location.
1205
1206 while (1) {
1207 SourceLocation UpperLoc;
1208 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1209 if (Entry.isInstantiation())
1210 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1211 else
1212 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001213
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001214 if (UpperLoc.isInvalid())
1215 break; // We reached the top.
Mike Stump11289f42009-09-09 15:08:12 +00001216
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001217 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001218
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001219 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1220 if (I != ROffsMap.end())
1221 return LastResForBeforeTUCheck = LOffs.second < I->second;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001224 // There is no common ancestor, most probably because one location is in the
1225 // predefines buffer.
1226 //
1227 // FIXME: We should rearrange the external interface so this simply never
1228 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump11289f42009-09-09 15:08:12 +00001229
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001230 // If exactly one location is a memory buffer, assume it preceeds the other.
1231 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1232 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1233 if (LIsMB != RIsMB)
1234 return LastResForBeforeTUCheck = LIsMB;
Mike Stump11289f42009-09-09 15:08:12 +00001235
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001236 // Otherwise, just assume FileIDs were created in order.
1237 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001238}
Chris Lattner4fa23622009-01-26 00:43:02 +00001239
Chris Lattner22eb9722006-06-18 05:43:12 +00001240/// PrintStats - Print statistics to stderr.
1241///
1242void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001243 llvm::errs() << "\n*** Source Manager Stats:\n";
1244 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1245 << " mem buffers mapped.\n";
1246 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1247 << NextOffset << "B of Sloc address space used.\n";
Mike Stump11289f42009-09-09 15:08:12 +00001248
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 unsigned NumLineNumsComputed = 0;
1250 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001251 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1252 NumLineNumsComputed += I->second->SourceLineCache != 0;
1253 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001256 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1257 << NumLineNumsComputed << " files with line #'s computed.\n";
1258 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1259 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001260}
Douglas Gregor258ae542009-04-27 06:38:32 +00001261
1262ExternalSLocEntrySource::~ExternalSLocEntrySource() { }