blob: e476cb2e2997ada5b25e5e1ccd5c8c884bb865ff [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"
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000019#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000020#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000021#include "llvm/Support/raw_ostream.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000022#include "llvm/Support/Path.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000023#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000024#include <string>
Douglas Gregore0fbb832010-03-16 00:06:06 +000025#include <cstring>
Douglas Gregor802b7762010-03-15 22:54:52 +000026
Chris Lattner22eb9722006-06-18 05:43:12 +000027using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000028using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000029using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000030
Chris Lattner153a0f12009-02-04 00:40:31 +000031//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000032// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000034
Ted Kremenekc08bca62007-10-30 21:08:08 +000035ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000036 if (shouldFreeBuffer())
37 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000038}
39
Ted Kremenek12c2af42009-01-06 01:55:26 +000040/// getSizeBytesMapped - Returns the number of bytes actually mapped for
41/// this ContentCache. This can be 0 if the MemBuffer was not actually
42/// instantiated.
43unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000044 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000045}
46
47/// getSize - Returns the size of the content encapsulated by this ContentCache.
48/// This can be the size of the source file or the size of an arbitrary
49/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000050/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000051unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000052 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
53 : (unsigned) Entry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000054}
55
Douglas Gregor3f4bea02010-07-26 21:36:20 +000056void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
57 bool DoNotFree) {
Douglas Gregor82752ec2010-03-16 22:53:51 +000058 assert(B != Buffer.getPointer());
Douglas Gregor53ad6b92009-12-02 06:49:09 +000059
Douglas Gregor3f4bea02010-07-26 21:36:20 +000060 if (shouldFreeBuffer())
61 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000062 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000063 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000064}
65
Douglas Gregor874cc622010-03-16 00:35:39 +000066const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner8f5bc9f2010-04-20 20:49:23 +000067 const SourceManager &SM,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000068 SourceLocation Loc,
Douglas Gregor874cc622010-03-16 00:35:39 +000069 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000070 // Lazily create the Buffer for ContentCaches that wrap files. If we already
71 // computed it, jsut return what we have.
72 if (Buffer.getPointer() || Entry == 0) {
73 if (Invalid)
74 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000075
Chris Lattner5631b052010-11-23 08:50:03 +000076 return Buffer.getPointer();
77 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000078
Chris Lattner5631b052010-11-23 08:50:03 +000079 std::string ErrorStr;
80 Buffer.setPointer(SM.getFileManager().getBufferForFile(Entry, &ErrorStr));
81
82 // If we were unable to open the file, then we are in an inconsistent
83 // situation where the content cache referenced a file which no longer
84 // exists. Most likely, we were using a stat cache with an invalid entry but
85 // the file could also have been removed during processing. Since we can't
86 // really deal with this situation, just create an empty buffer.
87 //
88 // FIXME: This is definitely not ideal, but our immediate clients can't
89 // currently handle returning a null entry here. Ideally we should detect
90 // that we are in an inconsistent situation and error out as quickly as
91 // possible.
92 if (!Buffer.getPointer()) {
93 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
94 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
95 "<invalid>"));
96 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
97 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
98 Ptr[i] = FillStr[i % FillStr.size()];
99
100 if (Diag.isDiagnosticInFlight())
101 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
102 Entry->getName(), ErrorStr);
103 else
104 Diag.Report(Loc, diag::err_cannot_open_file)
105 << Entry->getName() << ErrorStr;
106
107 Buffer.setInt(Buffer.getInt() | InvalidFlag);
108
109 if (Invalid) *Invalid = true;
110 return Buffer.getPointer();
111 }
112
113 // Check that the file's size is the same as in the file entry (which may
114 // have come from a stat cache).
115 if (getRawBuffer()->getBufferSize() != (size_t)Entry->getSize()) {
116 if (Diag.isDiagnosticInFlight())
117 Diag.SetDelayedDiagnostic(diag::err_file_modified,
118 Entry->getName());
119 else
120 Diag.Report(Loc, diag::err_file_modified)
121 << Entry->getName();
122
123 Buffer.setInt(Buffer.getInt() | InvalidFlag);
124 if (Invalid) *Invalid = true;
125 return Buffer.getPointer();
126 }
127
128 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
129 // (BOM). We only support UTF-8 without a BOM right now. See
130 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
131 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
132 const char *BOM = llvm::StringSwitch<const char *>(BufStr)
133 .StartsWith("\xEF\xBB\xBF", "UTF-8")
134 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
135 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
136 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
137 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
138 .StartsWith("\x2B\x2F\x76", "UTF-7")
139 .StartsWith("\xF7\x64\x4C", "UTF-1")
140 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
141 .StartsWith("\x0E\xFE\xFF", "SDSU")
142 .StartsWith("\xFB\xEE\x28", "BOCU-1")
143 .StartsWith("\x84\x31\x95\x33", "GB-18030")
144 .Default(0);
145
146 if (BOM) {
147 Diag.Report(Loc, diag::err_unsupported_bom)
148 << BOM << Entry->getName();
149 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000150 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000151
Douglas Gregor82752ec2010-03-16 22:53:51 +0000152 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000153 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000154
155 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000156}
157
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000158unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
159 // Look up the filename in the string table, returning the pre-existing value
160 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000161 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000162 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
163 if (Entry.getValue() != ~0U)
164 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000166 // Otherwise, assign this the next available ID.
167 Entry.setValue(FilenamesByID.size());
168 FilenamesByID.push_back(&Entry);
169 return FilenamesByID.size()-1;
170}
171
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000172/// AddLineNote - Add a line note to the line table that indicates that there
173/// is a #line at the specified FID/Offset location which changes the presumed
174/// location to LineNo/FilenameID.
Chris Lattner153a0f12009-02-04 00:40:31 +0000175void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000176 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000177 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner153a0f12009-02-04 00:40:31 +0000179 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
180 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000182 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000183 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000184
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000185 if (!Entries.empty()) {
186 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
187 // that we are still in "foo.h".
188 if (FilenameID == -1)
189 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattner1c967782009-02-04 06:25:26 +0000191 // If we are after a line marker that switched us to system header mode, or
192 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000193 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000194 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000195 }
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattner1c967782009-02-04 06:25:26 +0000197 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
198 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000199}
200
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000201/// AddLineNote This is the same as the previous version of AddLineNote, but is
202/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
203/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
204/// this is a file exit. FileKind specifies whether this is a system header or
205/// extern C system header.
206void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
207 unsigned LineNo, int FilenameID,
208 unsigned EntryExit,
209 SrcMgr::CharacteristicKind FileKind) {
210 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000212 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000214 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
215 "Adding line entries out of order!");
216
Chris Lattner1c967782009-02-04 06:25:26 +0000217 unsigned IncludeOffset = 0;
218 if (EntryExit == 0) { // No #include stack change.
219 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
220 } else if (EntryExit == 1) {
221 IncludeOffset = Offset-1;
222 } else if (EntryExit == 2) {
223 assert(!Entries.empty() && Entries.back().IncludeOffset &&
224 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner1c967782009-02-04 06:25:26 +0000226 // Get the include loc of the last entries' include loc as our include loc.
227 IncludeOffset = 0;
228 if (const LineEntry *PrevEntry =
229 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
230 IncludeOffset = PrevEntry->IncludeOffset;
231 }
Mike Stump11289f42009-09-09 15:08:12 +0000232
Chris Lattner1c967782009-02-04 06:25:26 +0000233 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
234 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000235}
236
237
Chris Lattnerd4293922009-02-04 01:55:42 +0000238/// FindNearestLineEntry - Find the line entry nearest to FID that is before
239/// it. If there is no line entry before Offset in FID, return null.
Mike Stump11289f42009-09-09 15:08:12 +0000240const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000241 unsigned Offset) {
242 const std::vector<LineEntry> &Entries = LineEntries[FID];
243 assert(!Entries.empty() && "No #line entries for this FID after all!");
244
Chris Lattner334a2ad2009-02-04 04:46:59 +0000245 // It is very common for the query to be after the last #line, check this
246 // first.
247 if (Entries.back().FileOffset <= Offset)
248 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000249
Chris Lattner334a2ad2009-02-04 04:46:59 +0000250 // Do a binary search to find the maximal element that is still before Offset.
251 std::vector<LineEntry>::const_iterator I =
252 std::upper_bound(Entries.begin(), Entries.end(), Offset);
253 if (I == Entries.begin()) return 0;
254 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000255}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000256
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000257/// \brief Add a new line entry that has already been encoded into
258/// the internal representation of the line table.
Mike Stump11289f42009-09-09 15:08:12 +0000259void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000260 const std::vector<LineEntry> &Entries) {
261 LineEntries[FID] = Entries;
262}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000263
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000264/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000265///
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000266unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
267 if (LineTable == 0)
268 LineTable = new LineTableInfo();
269 return LineTable->getLineTableFilenameID(Ptr, Len);
270}
271
272
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000273/// AddLineNote - Add a line note to the line table for the FileID and offset
274/// specified by Loc. If FilenameID is -1, it is considered to be
275/// unspecified.
276void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
277 int FilenameID) {
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000278 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000280 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
281
282 // Remember that this file has #line directives now if it doesn't already.
283 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000285 if (LineTable == 0)
286 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000287 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000288}
289
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000290/// AddLineNote - Add a GNU line marker to the line table.
291void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
292 int FilenameID, bool IsFileEntry,
293 bool IsFileExit, bool IsSystemHeader,
294 bool IsExternCHeader) {
295 // If there is no filename and no flags, this is treated just like a #line,
296 // which does not change the flags of the previous line marker.
297 if (FilenameID == -1) {
298 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
299 "Can't set flags without setting the filename!");
300 return AddLineNote(Loc, LineNo, FilenameID);
301 }
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000303 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
304 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000306 // Remember that this file has #line directives now if it doesn't already.
307 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000308
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000309 if (LineTable == 0)
310 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000311
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000312 SrcMgr::CharacteristicKind FileKind;
313 if (IsExternCHeader)
314 FileKind = SrcMgr::C_ExternCSystem;
315 else if (IsSystemHeader)
316 FileKind = SrcMgr::C_System;
317 else
318 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000320 unsigned EntryExit = 0;
321 if (IsFileEntry)
322 EntryExit = 1;
323 else if (IsFileExit)
324 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000326 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
327 EntryExit, FileKind);
328}
329
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000330LineTableInfo &SourceManager::getLineTable() {
331 if (LineTable == 0)
332 LineTable = new LineTableInfo();
333 return *LineTable;
334}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000335
Chris Lattner153a0f12009-02-04 00:40:31 +0000336//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000337// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000338//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000339
Chris Lattner5159f612010-11-23 08:35:12 +0000340SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
341 : Diag(Diag), FileMgr(FileMgr),
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000342 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
343 NumBinaryProbes(0) {
344 clearIDTables();
345 Diag.setSourceManager(this);
346}
347
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000348SourceManager::~SourceManager() {
349 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000350
Chris Lattnerc8233df2009-02-03 07:30:45 +0000351 // Delete FileEntry objects corresponding to content caches. Since the actual
352 // content cache objects are bump pointer allocated, we just have to run the
353 // dtors, but we call the deallocate method for completeness.
354 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
355 MemBufferInfos[i]->~ContentCache();
356 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
357 }
358 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
359 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
360 I->second->~ContentCache();
361 ContentCacheAlloc.Deallocate(I->second);
362 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000363}
364
365void SourceManager::clearIDTables() {
366 MainFileID = FileID();
367 SLocEntryTable.clear();
368 LastLineNoFileIDQuery = FileID();
369 LastLineNoContentCache = 0;
370 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000372 if (LineTable)
373 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000374
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000375 // Use up FileID #0 as an invalid instantiation.
376 NextOffset = 0;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000377 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000378}
379
Chris Lattner4fa23622009-01-26 00:43:02 +0000380/// getOrCreateContentCache - Create or return a cached ContentCache for the
381/// specified file.
382const ContentCache *
383SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000384 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattner22eb9722006-06-18 05:43:12 +0000386 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000387 ContentCache *&Entry = FileInfos[FileEnt];
388 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000390 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
391 // so that FileInfo can use the low 3 bits of the pointer for its own
392 // nefarious purposes.
393 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
394 EntryAlign = std::max(8U, EntryAlign);
395 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000396 new (Entry) ContentCache(FileEnt);
397 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000398}
399
400
Ted Kremenek08bed092007-10-31 17:53:38 +0000401/// createMemBufferContentCache - Create a new ContentCache for the specified
402/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000403const ContentCache*
404SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000405 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
406 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
407 // the pointer for its own nefarious purposes.
408 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
409 EntryAlign = std::max(8U, EntryAlign);
410 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000411 new (Entry) ContentCache();
412 MemBufferInfos.push_back(Entry);
413 Entry->setBuffer(Buffer);
414 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000415}
416
Douglas Gregor258ae542009-04-27 06:38:32 +0000417void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
418 unsigned NumSLocEntries,
419 unsigned NextOffset) {
420 ExternalSLocEntries = Source;
421 this->NextOffset = NextOffset;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000422 unsigned CurPrealloc = SLocEntryLoaded.size();
423 // If we've ever preallocated, we must not count the dummy entry.
424 if (CurPrealloc) --CurPrealloc;
Douglas Gregor258ae542009-04-27 06:38:32 +0000425 SLocEntryLoaded.resize(NumSLocEntries + 1);
426 SLocEntryLoaded[0] = true;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000427 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000428}
429
Douglas Gregor0bc12932009-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 Gregor258ae542009-04-27 06:38:32 +0000446
Chris Lattner4fa23622009-01-26 00:43:02 +0000447//===----------------------------------------------------------------------===//
448// Methods to create new FileID's and instantiations.
449//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000450
Dan Gohmance46f022010-08-26 21:27:06 +0000451/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-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 Lattnerd32480d2009-01-17 06:22:33 +0000454FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000455 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000456 SrcMgr::CharacteristicKind FileCharacter,
457 unsigned PreallocatedID,
458 unsigned Offset) {
Douglas Gregor258ae542009-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 Stump11289f42009-09-09 15:08:12 +0000462 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000463 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000464 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000465 "Source location entry already loaded");
466 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump11289f42009-09-09 15:08:12 +0000467 SLocEntryTable[PreallocatedID]
Douglas Gregor258ae542009-04-27 06:38:32 +0000468 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
469 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000470 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor51c23512010-03-19 06:12:06 +0000471 return FID;
Douglas Gregor258ae542009-04-27 06:38:32 +0000472 }
473
Mike Stump11289f42009-09-09 15:08:12 +0000474 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattner4fa23622009-01-26 00:43:02 +0000475 FileInfo::get(IncludePos, File,
476 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000477 unsigned FileSize = File->getSize();
Chris Lattner4fa23622009-01-26 00:43:02 +0000478 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
479 NextOffset += FileSize+1;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner4fa23622009-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 Kyrtzidis0152c6c2009-06-23 00:42:06 +0000483 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000484 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000485}
486
Chris Lattner4fa23622009-01-26 00:43:02 +0000487/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattner53e384f2009-01-16 07:00:02 +0000488/// that a token from SpellingLoc should actually be referenced from
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000489/// InstantiationLoc.
Chris Lattner4fa23622009-01-26 00:43:02 +0000490SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000491 SourceLocation ILocStart,
492 SourceLocation ILocEnd,
Douglas Gregor258ae542009-04-27 06:38:32 +0000493 unsigned TokLength,
494 unsigned PreallocatedID,
495 unsigned Offset) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000496 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor258ae542009-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 Stump11289f42009-09-09 15:08:12 +0000500 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000501 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000502 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-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 Lattner9dc9c202009-02-15 20:52:18 +0000509 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner4fa23622009-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));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000513}
514
Douglas Gregor874cc622010-03-16 00:35:39 +0000515const llvm::MemoryBuffer *
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000516SourceManager::getMemoryBufferForFile(const FileEntry *File,
517 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000518 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000519 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000520 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000521}
522
Dan Gohman5d223dc2010-10-26 20:47:28 +0000523void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000524 const llvm::MemoryBuffer *Buffer,
525 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000526 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000527 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000528
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000529 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000530}
531
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000532llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000533 bool MyInvalid = false;
Douglas Gregor86af9842011-01-31 22:42:36 +0000534 const SLocEntry &SLoc = getSLocEntry(FID.ID);
535 if (!SLoc.isFile()) {
536 if (Invalid)
537 *Invalid = true;
538 return "<<<<<INVALID SOURCE LOCATION>>>>>";
539 }
540
541 const llvm::MemoryBuffer *Buf
542 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
543 &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000544 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000545 *Invalid = MyInvalid;
546
547 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000548 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000549
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000550 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000551}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000552
Chris Lattner153a0f12009-02-04 00:40:31 +0000553//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000554// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000555//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000556
557/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
558/// method that is used for all SourceManager queries that start with a
559/// SourceLocation object. It is responsible for finding the entry in
560/// SLocEntryTable which contains the specified location.
561///
562FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
563 assert(SLocOffset && "Invalid FileID");
Mike Stump11289f42009-09-09 15:08:12 +0000564
Chris Lattner4fa23622009-01-26 00:43:02 +0000565 // After the first and second level caches, I see two common sorts of
566 // behavior: 1) a lot of searched FileID's are "near" the cached file location
567 // or are "near" the cached instantiation location. 2) others are just
568 // completely random and may be a very long way away.
569 //
570 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
571 // then we fall back to a less cache efficient, but more scalable, binary
572 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000573
Chris Lattner4fa23622009-01-26 00:43:02 +0000574 // See if this is near the file point - worst case we start scanning from the
575 // most newly created FileID.
576 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner4fa23622009-01-26 00:43:02 +0000578 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
579 // Neither loc prunes our search.
580 I = SLocEntryTable.end();
581 } else {
582 // Perhaps it is near the file point.
583 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
584 }
585
586 // Find the FileID that contains this. "I" is an iterator that points to a
587 // FileID whose offset is known to be larger than SLocOffset.
588 unsigned NumProbes = 0;
589 while (1) {
590 --I;
Douglas Gregor258ae542009-04-27 06:38:32 +0000591 if (ExternalSLocEntries)
592 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattner4fa23622009-01-26 00:43:02 +0000593 if (I->getOffset() <= SLocOffset) {
594#if 0
595 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
596 I-SLocEntryTable.begin(),
597 I->isInstantiation() ? "inst" : "file",
598 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
599#endif
600 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor258ae542009-04-27 06:38:32 +0000601
Chris Lattner4fa23622009-01-26 00:43:02 +0000602 // If this isn't an instantiation, remember it. We have good locality
603 // across FileID lookups.
604 if (!I->isInstantiation())
605 LastFileIDLookup = Res;
606 NumLinearScans += NumProbes+1;
607 return Res;
608 }
609 if (++NumProbes == 8)
610 break;
611 }
Mike Stump11289f42009-09-09 15:08:12 +0000612
Chris Lattner4fa23622009-01-26 00:43:02 +0000613 // Convert "I" back into an index. We know that it is an entry whose index is
614 // larger than the offset we are looking for.
615 unsigned GreaterIndex = I-SLocEntryTable.begin();
616 // LessIndex - This is the lower bound of the range that we're searching.
617 // We know that the offset corresponding to the FileID is is less than
618 // SLocOffset.
619 unsigned LessIndex = 0;
620 NumProbes = 0;
621 while (1) {
622 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor258ae542009-04-27 06:38:32 +0000623 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump11289f42009-09-09 15:08:12 +0000624
Chris Lattner4fa23622009-01-26 00:43:02 +0000625 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattner4fa23622009-01-26 00:43:02 +0000627 // If the offset of the midpoint is too large, chop the high side of the
628 // range to the midpoint.
629 if (MidOffset > SLocOffset) {
630 GreaterIndex = MiddleIndex;
631 continue;
632 }
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner4fa23622009-01-26 00:43:02 +0000634 // If the middle index contains the value, succeed and return.
635 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
636#if 0
637 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
638 I-SLocEntryTable.begin(),
639 I->isInstantiation() ? "inst" : "file",
640 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
641#endif
642 FileID Res = FileID::get(MiddleIndex);
643
644 // If this isn't an instantiation, remember it. We have good locality
645 // across FileID lookups.
646 if (!I->isInstantiation())
647 LastFileIDLookup = Res;
648 NumBinaryProbes += NumProbes;
649 return Res;
650 }
Mike Stump11289f42009-09-09 15:08:12 +0000651
Chris Lattner4fa23622009-01-26 00:43:02 +0000652 // Otherwise, move the low-side up to the middle index.
653 LessIndex = MiddleIndex;
654 }
655}
656
Chris Lattner659ac5f2009-01-26 20:04:19 +0000657SourceLocation SourceManager::
658getInstantiationLocSlowCase(SourceLocation Loc) const {
659 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000660 // Note: If Loc indicates an offset into a token that came from a macro
661 // expansion (e.g. the 5th character of the token) we do not want to add
662 // this offset when going to the instantiation location. The instatiation
663 // location is the macro invocation, which the offset has nothing to do
664 // with. This is unlike when we get the spelling loc, because the offset
665 // directly correspond to the token whose spelling we're inspecting.
666 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattner9dc9c202009-02-15 20:52:18 +0000667 .getInstantiationLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000668 } while (!Loc.isFileID());
669
670 return Loc;
671}
672
673SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
674 do {
675 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
676 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
677 Loc = Loc.getFileLocWithOffset(LocInfo.second);
678 } while (!Loc.isFileID());
679 return Loc;
680}
681
682
Chris Lattner4fa23622009-01-26 00:43:02 +0000683std::pair<FileID, unsigned>
684SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
685 unsigned Offset) const {
686 // If this is an instantiation record, walk through all the instantiation
687 // points.
688 FileID FID;
689 SourceLocation Loc;
690 do {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000691 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattner4fa23622009-01-26 00:43:02 +0000693 FID = getFileID(Loc);
694 E = &getSLocEntry(FID);
695 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000696 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner4fa23622009-01-26 00:43:02 +0000698 return std::make_pair(FID, Offset);
699}
700
701std::pair<FileID, unsigned>
702SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
703 unsigned Offset) const {
Chris Lattner31af4e02009-01-26 19:41:58 +0000704 // If this is an instantiation record, walk through all the instantiation
705 // points.
706 FileID FID;
707 SourceLocation Loc;
708 do {
709 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner31af4e02009-01-26 19:41:58 +0000711 FID = getFileID(Loc);
712 E = &getSLocEntry(FID);
713 Offset += Loc.getOffset()-E->getOffset();
714 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000715
Chris Lattner4fa23622009-01-26 00:43:02 +0000716 return std::make_pair(FID, Offset);
717}
718
Chris Lattner8ad52d52009-02-17 08:04:48 +0000719/// getImmediateSpellingLoc - Given a SourceLocation object, return the
720/// spelling location referenced by the ID. This is the first level down
721/// towards the place where the characters that make up the lexed token can be
722/// found. This should not generally be used by clients.
723SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
724 if (Loc.isFileID()) return Loc;
725 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
726 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
727 return Loc.getFileLocWithOffset(LocInfo.second);
728}
729
730
Chris Lattner9dc9c202009-02-15 20:52:18 +0000731/// getImmediateInstantiationRange - Loc is required to be an instantiation
732/// location. Return the start/end of the instantiation information.
733std::pair<SourceLocation,SourceLocation>
734SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
735 assert(Loc.isMacroID() && "Not an instantiation loc!");
736 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
737 return II.getInstantiationLocRange();
738}
739
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000740/// getInstantiationRange - Given a SourceLocation object, return the
741/// range of tokens covered by the instantiation in the ultimate file.
742std::pair<SourceLocation,SourceLocation>
743SourceManager::getInstantiationRange(SourceLocation Loc) const {
744 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000746 std::pair<SourceLocation,SourceLocation> Res =
747 getImmediateInstantiationRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000749 // Fully resolve the start and end locations to their ultimate instantiation
750 // points.
751 while (!Res.first.isFileID())
752 Res.first = getImmediateInstantiationRange(Res.first).first;
753 while (!Res.second.isFileID())
754 Res.second = getImmediateInstantiationRange(Res.second).second;
755 return Res;
756}
757
Chris Lattner9dc9c202009-02-15 20:52:18 +0000758
Chris Lattner4fa23622009-01-26 00:43:02 +0000759
760//===----------------------------------------------------------------------===//
761// Queries about the code at a SourceLocation.
762//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000763
Chris Lattnerd01e2912006-06-18 16:22:51 +0000764/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000765/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000766const char *SourceManager::getCharacterData(SourceLocation SL,
767 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000768 // Note that this is a hot function in the getSpelling() path, which is
769 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000770 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Ted Kremenek12c2af42009-01-06 01:55:26 +0000772 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000773 bool CharDataInvalid = false;
774 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000775 = getSLocEntry(LocInfo.first).getFile().getContentCache()
776 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000777 if (Invalid)
778 *Invalid = CharDataInvalid;
779 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000780}
781
Chris Lattner685730f2006-06-26 01:36:22 +0000782
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000783/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000784/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000785unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
786 bool *Invalid) const {
787 bool MyInvalid = false;
788 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
789 if (Invalid)
790 *Invalid = MyInvalid;
791
792 if (MyInvalid)
793 return 1;
Mike Stump11289f42009-09-09 15:08:12 +0000794
Chris Lattner22eb9722006-06-18 05:43:12 +0000795 unsigned LineStart = FilePos;
796 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
797 --LineStart;
798 return FilePos-LineStart+1;
799}
800
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000801// isInvalid - Return the result of calling loc.isInvalid(), and
802// if Invalid is not null, set its value to same.
803static bool isInvalid(SourceLocation Loc, bool *Invalid) {
804 bool MyInvalid = Loc.isInvalid();
805 if (Invalid)
806 *Invalid = MyInvalid;
807 return MyInvalid;
808}
809
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000810unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
811 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000812 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000813 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000814 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000815}
816
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000817unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
818 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000819 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000820 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000821 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000822}
823
Chandler Carruthc3ce5842010-10-23 08:44:57 +0000824static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000825ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
826 llvm::BumpPtrAllocator &Alloc,
827 const SourceManager &SM, bool &Invalid);
828static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
829 llvm::BumpPtrAllocator &Alloc,
830 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +0000831 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000832 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
833 &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000834 if (Invalid)
835 return;
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner8996fff2007-07-24 05:57:19 +0000837 // Find the file offsets of all of the *physical* source lines. This does
838 // not look at trigraphs, escaped newlines, or anything else tricky.
839 std::vector<unsigned> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000840
Chris Lattner8996fff2007-07-24 05:57:19 +0000841 // Line #1 starts at char 0.
842 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner8996fff2007-07-24 05:57:19 +0000844 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
845 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
846 unsigned Offs = 0;
847 while (1) {
848 // Skip over the contents of the line.
849 // TODO: Vectorize this? This is very performance sensitive for programs
850 // with lots of diagnostics and in -E mode.
851 const unsigned char *NextBuf = (const unsigned char *)Buf;
852 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
853 ++NextBuf;
854 Offs += NextBuf-Buf;
855 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chris Lattner8996fff2007-07-24 05:57:19 +0000857 if (Buf[0] == '\n' || Buf[0] == '\r') {
858 // If this is \n\r or \r\n, skip both characters.
859 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
860 ++Offs, ++Buf;
861 ++Offs, ++Buf;
862 LineOffsets.push_back(Offs);
863 } else {
864 // Otherwise, this is a null. If end of file, exit.
865 if (Buf == End) break;
866 // Otherwise, skip the null.
867 ++Offs, ++Buf;
868 }
869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattner8996fff2007-07-24 05:57:19 +0000871 // Copy the offsets into the FileInfo structure.
872 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000873 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +0000874 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
875}
Chris Lattner9a13bde2006-06-21 04:57:09 +0000876
Chris Lattner53e384f2009-01-16 07:00:02 +0000877/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +0000878/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +0000879/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +0000880/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000881unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
882 bool *Invalid) const {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000883 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000884 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +0000885 Content = LastLineNoContentCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000886 else
Chris Lattner88ea93e2009-02-04 01:06:56 +0000887 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner4fa23622009-01-26 00:43:02 +0000888 .getFile().getContentCache());
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattner22eb9722006-06-18 05:43:12 +0000890 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +0000891 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000892 if (Content->SourceLineCache == 0) {
893 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000894 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000895 if (Invalid)
896 *Invalid = MyInvalid;
897 if (MyInvalid)
898 return 1;
899 } else if (Invalid)
900 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000901
902 // Okay, we know we have a line number table. Do a binary search to find the
903 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000904 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000905 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000906 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner88ea93e2009-02-04 01:06:56 +0000908 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000909
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000910 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +0000911 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000912 //
913 // If it is worth being optimized, then in my opinion it could be more
914 // performant, simpler, and more obviously correct by just "galloping" outward
915 // from the queried file position. In fact, this could be incorporated into a
916 // generic algorithm such as lower_bound_with_hint.
917 //
918 // If someone gives me a test case where this matters, and I will do it! - DWD
919
Chris Lattner8996fff2007-07-24 05:57:19 +0000920 // If the previous query was to the same file, we know both the file pos from
921 // that query and the line number returned. This allows us to narrow the
922 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000923 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +0000924 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000925 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +0000926 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattner8996fff2007-07-24 05:57:19 +0000928 // The query is likely to be nearby the previous one. Here we check to
929 // see if it is within 5, 10 or 20 lines. It can be far away in cases
930 // where big comment blocks and vertical whitespace eat up lines but
931 // contribute no tokens.
932 if (SourceLineCache+5 < SourceLineCacheEnd) {
933 if (SourceLineCache[5] > QueriedFilePos)
934 SourceLineCacheEnd = SourceLineCache+5;
935 else if (SourceLineCache+10 < SourceLineCacheEnd) {
936 if (SourceLineCache[10] > QueriedFilePos)
937 SourceLineCacheEnd = SourceLineCache+10;
938 else if (SourceLineCache+20 < SourceLineCacheEnd) {
939 if (SourceLineCache[20] > QueriedFilePos)
940 SourceLineCacheEnd = SourceLineCache+20;
941 }
942 }
943 }
944 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000945 if (LastLineNoResult < Content->NumLines)
946 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000947 }
948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Chris Lattner830a77f2007-07-24 06:43:46 +0000950 // If the spread is large, do a "radix" test as our initial guess, based on
951 // the assumption that lines average to approximately the same length.
952 // NOTE: This is currently disabled, as it does not appear to be profitable in
953 // initial measurements.
954 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +0000955 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattner830a77f2007-07-24 06:43:46 +0000957 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000958 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattner830a77f2007-07-24 06:43:46 +0000960 // Check for -10 and +10 lines.
961 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
962 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
963
964 // If the computed lower bound is less than the query location, move it in.
965 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
966 SourceLineCacheStart[LowerBound] < QueriedFilePos)
967 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattner830a77f2007-07-24 06:43:46 +0000969 // If the computed upper bound is greater than the query location, move it.
970 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
971 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
972 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
973 }
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner830a77f2007-07-24 06:43:46 +0000975 unsigned *Pos
976 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +0000977 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattner88ea93e2009-02-04 01:06:56 +0000979 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000980 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +0000981 LastLineNoFilePos = QueriedFilePos;
982 LastLineNoResult = LineNo;
983 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000984}
985
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000986unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
987 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000988 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000989 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
990 return getLineNumber(LocInfo.first, LocInfo.second);
991}
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000992unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
993 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000994 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000995 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
996 return getLineNumber(LocInfo.first, LocInfo.second);
997}
998
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000999/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001000/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001001/// header, or an "implicit extern C" system header.
1002///
1003/// This state can be modified with flags on GNU linemarker directives like:
1004/// # 4 "foo.h" 3
1005/// which changes all source locations in the current file after that to be
1006/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001007SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001008SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1009 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1010 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1011 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1012
1013 // If there are no #line directives in this file, just return the whole-file
1014 // state.
1015 if (!FI.hasLineDirectives())
1016 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001017
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001018 assert(LineTable && "Can't have linetable entries without a LineTable!");
1019 // See if there is a #line directive before the location.
1020 const LineEntry *Entry =
1021 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001023 // If this is before the first line marker, use the file characteristic.
1024 if (!Entry)
1025 return FI.getFileCharacteristic();
1026
1027 return Entry->FileKind;
1028}
1029
Chris Lattnera6f037c2009-02-17 08:39:06 +00001030/// Return the filename or buffer identifier of the buffer the location is in.
1031/// Note that this name does not respect #line directives. Use getPresumedLoc
1032/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001033const char *SourceManager::getBufferName(SourceLocation Loc,
1034 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001035 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001036
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001037 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001038}
1039
Chris Lattner88ea93e2009-02-04 01:06:56 +00001040
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001041/// getPresumedLoc - This method returns the "presumed" location of a
1042/// SourceLocation specifies. A "presumed location" can be modified by #line
1043/// or GNU line marker directives. This provides a view on the data that a
1044/// user should see in diagnostics, for example.
1045///
1046/// Note that a presumed location is always given as the instantiation point
1047/// of an instantiation location, not at the spelling location.
1048PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1049 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001050
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001051 // Presumed locations are always for instantiation points.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001052 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattner88ea93e2009-02-04 01:06:56 +00001054 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001055 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001056
Chris Lattnerd4293922009-02-04 01:55:42 +00001057 // To get the source name, first consult the FileEntry (if one exists)
1058 // before the MemBuffer as this will avoid unnecessarily paging in the
1059 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001060 const char *Filename;
1061 if (C->Entry)
1062 Filename = C->Entry->getName();
1063 else
1064 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor75f26d62010-11-02 00:39:22 +00001065 bool Invalid = false;
1066 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1067 if (Invalid)
1068 return PresumedLoc();
1069 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1070 if (Invalid)
1071 return PresumedLoc();
1072
Chris Lattnerd4293922009-02-04 01:55:42 +00001073 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattnerd4293922009-02-04 01:55:42 +00001075 // If we have #line directives in this file, update and overwrite the physical
1076 // location info if appropriate.
1077 if (FI.hasLineDirectives()) {
1078 assert(LineTable && "Can't have linetable entries without a LineTable!");
1079 // See if there is a #line directive before this. If so, get it.
1080 if (const LineEntry *Entry =
1081 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001082 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001083 if (Entry->FilenameID != -1)
1084 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001085
1086 // Use the line number specified by the LineEntry. This line number may
1087 // be multiple lines down from the line entry. Add the difference in
1088 // physical line numbers from the query point and the line marker to the
1089 // total.
1090 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1091 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattner20c50ba2009-02-04 02:15:40 +00001093 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001094
Chris Lattner1c967782009-02-04 06:25:26 +00001095 // Handle virtual #include manipulation.
1096 if (Entry->IncludeOffset) {
1097 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1098 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1099 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001100 }
1101 }
1102
1103 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001104}
1105
1106//===----------------------------------------------------------------------===//
1107// Other miscellaneous methods.
1108//===----------------------------------------------------------------------===//
1109
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001110/// \brief Get the source location for the given file:line:col triplet.
1111///
1112/// If the source file is included multiple times, the source location will
1113/// be based upon the first inclusion.
1114SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1115 unsigned Line, unsigned Col) const {
1116 assert(SourceFile && "Null source file!");
1117 assert(Line && Col && "Line and column should start from 1!");
1118
1119 fileinfo_iterator FI = FileInfos.find(SourceFile);
1120 if (FI == FileInfos.end())
1121 return SourceLocation();
1122 ContentCache *Content = FI->second;
Mike Stump11289f42009-09-09 15:08:12 +00001123
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001124 // If this is the first use of line information for this buffer, compute the
1125 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001126 if (Content->SourceLineCache == 0) {
1127 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001128 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001129 if (MyInvalid)
1130 return SourceLocation();
1131 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001132
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001133 // Find the first file ID that corresponds to the given file.
1134 FileID FirstFID;
1135
1136 // First, check the main file ID, since it is common to look for a
1137 // location in the main file.
1138 if (!MainFileID.isInvalid()) {
1139 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1140 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1141 FirstFID = MainFileID;
1142 }
1143
1144 if (FirstFID.isInvalid()) {
1145 // The location we're looking for isn't in the main file; look
1146 // through all of the source locations.
1147 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1148 const SLocEntry &SLoc = getSLocEntry(I);
1149 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1150 FirstFID = FileID::get(I);
1151 break;
1152 }
1153 }
1154 }
1155
1156 if (FirstFID.isInvalid())
1157 return SourceLocation();
1158
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001159 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001160 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001161 if (Size > 0)
1162 --Size;
1163 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1164 }
1165
1166 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001167 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1168 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001169 unsigned i = 0;
1170
1171 // Check that the given column is valid.
1172 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1173 ++i;
1174 if (i < Col-1)
1175 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1176
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001177 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001178}
1179
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001180/// Given a decomposed source location, move it up the include/instantiation
1181/// stack to the parent source location. If this is possible, return the
1182/// decomposed version of the parent in Loc and return false. If Loc is the
1183/// top-level entry, return true and don't modify it.
1184static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1185 const SourceManager &SM) {
1186 SourceLocation UpperLoc;
1187 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1188 if (Entry.isInstantiation())
1189 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1190 else
1191 UpperLoc = Entry.getFile().getIncludeLoc();
1192
1193 if (UpperLoc.isInvalid())
1194 return true; // We reached the top.
1195
1196 Loc = SM.getDecomposedLoc(UpperLoc);
1197 return false;
1198}
1199
1200
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001201/// \brief Determines the order of 2 source locations in the translation unit.
1202///
1203/// \returns true if LHS source location comes before RHS, false otherwise.
1204bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1205 SourceLocation RHS) const {
1206 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1207 if (LHS == RHS)
1208 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Argyrios Kyrtzidis338f9aa2010-12-24 02:53:53 +00001210 // If both locations are macro instantiations, the order of their offsets
1211 // reflect the order that the tokens, pointed to by these locations, were
1212 // instantiated (during parsing each token that is instantiated by a macro,
1213 // expands the SLocEntries).
1214 if (LHS.isMacroID() && RHS.isMacroID())
1215 return LHS.getOffset() < RHS.getOffset();
1216
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001217 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1218 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001219
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001220 // If the source locations are in the same file, just compare offsets.
1221 if (LOffs.first == ROffs.first)
1222 return LOffs.second < ROffs.second;
1223
1224 // If we are comparing a source location with multiple locations in the same
1225 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00001226 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1227 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Chris Lattner66d2f922010-05-07 01:17:07 +00001229 // Okay, we missed in the cache, start updating the cache for this query.
1230 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001231
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001232 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner06821c92010-05-07 05:51:13 +00001233 // find a common "ancestor". FileIDs build a tree-like structure that
1234 // reflects the #include hierarchy, and this algorithm needs to find the
1235 // nearest common ancestor between the two locations. For example, if you
1236 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1237 // a location in c.h, we need to find that their nearest common ancestor is
1238 // a.c, and compare the locations of the two #includes to find their relative
1239 // ordering.
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001240 //
Chris Lattner06821c92010-05-07 05:51:13 +00001241 // SourceManager assigns FileIDs in order of parsing. This means that an
1242 // includee always has a larger FileID than an includer. While you might
1243 // think that we could just compare the FileID's here, that doesn't work to
1244 // compare a point at the end of a.c with a point within c.h. Though c.h has
1245 // a larger FileID, we have to compare the include point of c.h to the
1246 // location in a.c.
1247 //
1248 // Despite not being able to directly compare FileID's, we can tell that a
1249 // larger FileID is necessarily more deeply nested than a lower one and use
1250 // this information to walk up the tree to the nearest common ancestor.
1251 do {
1252 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1253 // ROffs, walk up the #include chain.
1254 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001255 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001256 break; // We reached the top.
1257
Chris Lattner06821c92010-05-07 05:51:13 +00001258 } else {
1259 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1260 // nested than LOffs, walk up the #include chain.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001261 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001262 break; // We reached the top.
Chris Lattner66d2f922010-05-07 01:17:07 +00001263 }
Chris Lattner06821c92010-05-07 05:51:13 +00001264 } while (LOffs.first != ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001265
Chris Lattner06821c92010-05-07 05:51:13 +00001266 // If we exited because we found a nearest common ancestor, compare the
1267 // locations within the common file and cache them.
1268 if (LOffs.first == ROffs.first) {
1269 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1270 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001273 // There is no common ancestor, most probably because one location is in the
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001274 // predefines buffer or an AST file.
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001275 // FIXME: We should rearrange the external interface so this simply never
1276 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001277 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1278
1279 // Zip both entries up to the top level record.
1280 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1281 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner06821c92010-05-07 05:51:13 +00001282
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001283 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001284
1285 // Strip off macro instantation locations, going up to the top-level File
1286 // SLocEntry.
1287 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1288 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner06821c92010-05-07 05:51:13 +00001289 if (LIsMB != RIsMB)
Chris Lattner66d2f922010-05-07 01:17:07 +00001290 return LIsMB;
Mike Stump11289f42009-09-09 15:08:12 +00001291
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001292 // Otherwise, just assume FileIDs were created in order.
Chris Lattner66d2f922010-05-07 01:17:07 +00001293 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001294}
Chris Lattner4fa23622009-01-26 00:43:02 +00001295
Chris Lattner22eb9722006-06-18 05:43:12 +00001296/// PrintStats - Print statistics to stderr.
1297///
1298void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001299 llvm::errs() << "\n*** Source Manager Stats:\n";
1300 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1301 << " mem buffers mapped.\n";
1302 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1303 << NextOffset << "B of Sloc address space used.\n";
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 unsigned NumLineNumsComputed = 0;
1306 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001307 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1308 NumLineNumsComputed += I->second->SourceLineCache != 0;
1309 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001312 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1313 << NumLineNumsComputed << " files with line #'s computed.\n";
1314 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1315 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001316}
Douglas Gregor258ae542009-04-27 06:38:32 +00001317
1318ExternalSLocEntrySource::~ExternalSLocEntrySource() { }