blob: 2f974dc642369a8a53ca32f43085757368970d0a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000019#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000021#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/System/Path.h"
23#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000024#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000025#include <cstring>
Douglas Gregoraea67db2010-03-15 22:54:52 +000026
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace SrcMgr;
29using llvm::MemoryBuffer;
30
Chris Lattner23b5dc62009-02-04 00:40:31 +000031//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000032// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000034
Ted Kremenek78d85f52007-10-30 21:08:08 +000035ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000036 if (shouldFreeBuffer())
37 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000038}
39
Ted Kremenekc16c2082009-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 Gregorc8151082010-03-16 22:53:51 +000044 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-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 Gregor29684422009-12-02 06:49:09 +000050/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000051unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000052 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
53 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000054}
55
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000056void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
57 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000058 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000059
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000060 if (shouldFreeBuffer())
61 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000062 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000063 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000064}
65
Douglas Gregor36c35ba2010-03-16 00:35:39 +000066const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000067 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000068 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000069 bool *Invalid) const {
Chris Lattnerb088cd32010-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 Lattner38caec42010-04-20 18:14:03 +000075
Chris Lattnerb088cd32010-11-23 08:50:03 +000076 return Buffer.getPointer();
77 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000078
Chris Lattnerb088cd32010-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 Kremenek5b034ad2009-01-06 22:43:04 +0000150 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000151
Douglas Gregorc8151082010-03-16 22:53:51 +0000152 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000153 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000154
155 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000156}
157
Chris Lattner5b9a5042009-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 Stump1eb44332009-09-09 15:08:12 +0000161 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000162 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
163 if (Entry.getValue() != ~0U)
164 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattner5b9a5042009-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 Lattnerac50e342009-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 Lattner23b5dc62009-02-04 00:40:31 +0000175void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000176 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000177 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner23b5dc62009-02-04 00:40:31 +0000179 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
180 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner9d79eba2009-02-04 05:21:58 +0000182 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000183 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattner137b6a62009-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 Lattner9d79eba2009-02-04 05:21:58 +0000193 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000194 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000195 }
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner137b6a62009-02-04 06:25:26 +0000197 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
198 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000199}
200
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattner9d79eba2009-02-04 05:21:58 +0000212 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattner9d79eba2009-02-04 05:21:58 +0000214 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
215 "Adding line entries out of order!");
216
Chris Lattner137b6a62009-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 Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattner137b6a62009-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 Stump1eb44332009-09-09 15:08:12 +0000232
Chris Lattner137b6a62009-02-04 06:25:26 +0000233 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
234 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000235}
236
237
Chris Lattner3cd949c2009-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 Stump1eb44332009-09-09 15:08:12 +0000240const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-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 Lattner6c1fbe02009-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 Lattner3cd949c2009-02-04 01:55:42 +0000249
Chris Lattner6c1fbe02009-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 Lattner3cd949c2009-02-04 01:55:42 +0000255}
Chris Lattnerac50e342009-02-03 22:13:05 +0000256
Douglas Gregorbd945002009-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 Stump1eb44332009-09-09 15:08:12 +0000259void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000260 const std::vector<LineEntry> &Entries) {
261 LineEntries[FID] = Entries;
262}
Chris Lattnerac50e342009-02-03 22:13:05 +0000263
Chris Lattner5b9a5042009-01-26 07:57:50 +0000264/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000265///
Chris Lattner5b9a5042009-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 Lattner4c4ea172009-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 Lattnerac50e342009-02-03 22:13:05 +0000278 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnerac50e342009-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 Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattnerac50e342009-02-03 22:13:05 +0000285 if (LineTable == 0)
286 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000287 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000288}
289
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner9d79eba2009-02-04 05:21:58 +0000303 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
304 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner9d79eba2009-02-04 05:21:58 +0000309 if (LineTable == 0)
310 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner9d79eba2009-02-04 05:21:58 +0000320 unsigned EntryExit = 0;
321 if (IsFileEntry)
322 EntryExit = 1;
323 else if (IsFileExit)
324 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner9d79eba2009-02-04 05:21:58 +0000326 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
327 EntryExit, FileKind);
328}
329
Douglas Gregorbd945002009-04-13 16:31:14 +0000330LineTableInfo &SourceManager::getLineTable() {
331 if (LineTable == 0)
332 LineTable = new LineTableInfo();
333 return *LineTable;
334}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000335
Chris Lattner23b5dc62009-02-04 00:40:31 +0000336//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000337// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000338//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000339
Chris Lattner39b49bc2010-11-23 08:35:12 +0000340SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
341 : Diag(Diag), FileMgr(FileMgr),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000342 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
343 NumBinaryProbes(0) {
344 clearIDTables();
345 Diag.setSourceManager(this);
346}
347
Chris Lattner5b9a5042009-01-26 07:57:50 +0000348SourceManager::~SourceManager() {
349 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner0d0bf8c2009-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 Lattner5b9a5042009-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 Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner5b9a5042009-01-26 07:57:50 +0000372 if (LineTable)
373 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner5b9a5042009-01-26 07:57:50 +0000375 // Use up FileID #0 as an invalid instantiation.
376 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000377 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000378}
379
Chris Lattnerde7aeef2009-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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000387 ContentCache *&Entry = FileInfos[FileEnt];
388 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner00282d62009-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 Lattner0d0bf8c2009-02-03 07:30:45 +0000396 new (Entry) ContentCache(FileEnt);
397 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
400
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000401/// createMemBufferContentCache - Create a new ContentCache for the specified
402/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000403const ContentCache*
404SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-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 Lattner0d0bf8c2009-02-03 07:30:45 +0000411 new (Entry) ContentCache();
412 MemBufferInfos.push_back(Entry);
413 Entry->setBuffer(Buffer);
414 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000415}
416
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000417void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
418 unsigned NumSLocEntries,
419 unsigned NextOffset) {
420 ExternalSLocEntries = Source;
421 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-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 Gregor7f94b0b2009-04-27 06:38:32 +0000425 SLocEntryLoaded.resize(NumSLocEntries + 1);
426 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000427 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000428}
429
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000430void SourceManager::ClearPreallocatedSLocEntries() {
431 unsigned I = 0;
432 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
433 if (!SLocEntryLoaded[I])
434 break;
435
436 // We've already loaded all preallocated source location entries.
437 if (I == SLocEntryLoaded.size())
438 return;
439
440 // Remove everything from location I onward.
441 SLocEntryTable.resize(I);
442 SLocEntryLoaded.clear();
443 ExternalSLocEntries = 0;
444}
445
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000446
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000447//===----------------------------------------------------------------------===//
448// Methods to create new FileID's and instantiations.
449//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000450
Dan Gohman3f86b782010-08-26 21:27:06 +0000451/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000452/// include position. This works regardless of whether the ContentCache
453/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000454FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000455 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000456 SrcMgr::CharacteristicKind FileCharacter,
457 unsigned PreallocatedID,
458 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000459 if (PreallocatedID) {
460 // If we're filling in a preallocated ID, just load in the file
461 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000462 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000463 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000464 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000465 "Source location entry already loaded");
466 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000467 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000468 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
469 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000470 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000471 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000472 }
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000475 FileInfo::get(IncludePos, File,
476 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000477 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000478 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
479 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000481 // Set LastFileIDLookup to the newly created file. The next getFileID call is
482 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000483 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000484 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000485}
486
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000487/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000488/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000489/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000490SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000491 SourceLocation ILocStart,
492 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000493 unsigned TokLength,
494 unsigned PreallocatedID,
495 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000496 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000497 if (PreallocatedID) {
498 // If we're filling in a preallocated ID, just load in the
499 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000500 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000501 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000502 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000503 "Source location entry already loaded");
504 assert(Offset && "Preallocate source location cannot have zero offset");
505 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
506 SLocEntryLoaded[PreallocatedID] = true;
507 return SourceLocation::getMacroLoc(Offset);
508 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000509 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000510 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
511 NextOffset += TokLength+1;
512 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000513}
514
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000515const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000516SourceManager::getMemoryBufferForFile(const FileEntry *File,
517 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000518 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000519 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000520 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000521}
522
Dan Gohman0d06e992010-10-26 20:47:28 +0000523void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000524 const llvm::MemoryBuffer *Buffer,
525 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000526 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000527 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000528
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000529 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000530}
531
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000532llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000533 bool MyInvalid = false;
534 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000535 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000536 *Invalid = MyInvalid;
537
538 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000539 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000540
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000541 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000542}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000543
Chris Lattner23b5dc62009-02-04 00:40:31 +0000544//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000545// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000546//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000547
548/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
549/// method that is used for all SourceManager queries that start with a
550/// SourceLocation object. It is responsible for finding the entry in
551/// SLocEntryTable which contains the specified location.
552///
553FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
554 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000556 // After the first and second level caches, I see two common sorts of
557 // behavior: 1) a lot of searched FileID's are "near" the cached file location
558 // or are "near" the cached instantiation location. 2) others are just
559 // completely random and may be a very long way away.
560 //
561 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
562 // then we fall back to a less cache efficient, but more scalable, binary
563 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000565 // See if this is near the file point - worst case we start scanning from the
566 // most newly created FileID.
567 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000569 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
570 // Neither loc prunes our search.
571 I = SLocEntryTable.end();
572 } else {
573 // Perhaps it is near the file point.
574 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
575 }
576
577 // Find the FileID that contains this. "I" is an iterator that points to a
578 // FileID whose offset is known to be larger than SLocOffset.
579 unsigned NumProbes = 0;
580 while (1) {
581 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000582 if (ExternalSLocEntries)
583 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000584 if (I->getOffset() <= SLocOffset) {
585#if 0
586 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
587 I-SLocEntryTable.begin(),
588 I->isInstantiation() ? "inst" : "file",
589 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
590#endif
591 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000592
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000593 // If this isn't an instantiation, remember it. We have good locality
594 // across FileID lookups.
595 if (!I->isInstantiation())
596 LastFileIDLookup = Res;
597 NumLinearScans += NumProbes+1;
598 return Res;
599 }
600 if (++NumProbes == 8)
601 break;
602 }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000604 // Convert "I" back into an index. We know that it is an entry whose index is
605 // larger than the offset we are looking for.
606 unsigned GreaterIndex = I-SLocEntryTable.begin();
607 // LessIndex - This is the lower bound of the range that we're searching.
608 // We know that the offset corresponding to the FileID is is less than
609 // SLocOffset.
610 unsigned LessIndex = 0;
611 NumProbes = 0;
612 while (1) {
613 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000614 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000616 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000618 // If the offset of the midpoint is too large, chop the high side of the
619 // range to the midpoint.
620 if (MidOffset > SLocOffset) {
621 GreaterIndex = MiddleIndex;
622 continue;
623 }
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000625 // If the middle index contains the value, succeed and return.
626 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
627#if 0
628 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
629 I-SLocEntryTable.begin(),
630 I->isInstantiation() ? "inst" : "file",
631 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
632#endif
633 FileID Res = FileID::get(MiddleIndex);
634
635 // If this isn't an instantiation, remember it. We have good locality
636 // across FileID lookups.
637 if (!I->isInstantiation())
638 LastFileIDLookup = Res;
639 NumBinaryProbes += NumProbes;
640 return Res;
641 }
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000643 // Otherwise, move the low-side up to the middle index.
644 LessIndex = MiddleIndex;
645 }
646}
647
Chris Lattneraddb7972009-01-26 20:04:19 +0000648SourceLocation SourceManager::
649getInstantiationLocSlowCase(SourceLocation Loc) const {
650 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000651 // Note: If Loc indicates an offset into a token that came from a macro
652 // expansion (e.g. the 5th character of the token) we do not want to add
653 // this offset when going to the instantiation location. The instatiation
654 // location is the macro invocation, which the offset has nothing to do
655 // with. This is unlike when we get the spelling loc, because the offset
656 // directly correspond to the token whose spelling we're inspecting.
657 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000658 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000659 } while (!Loc.isFileID());
660
661 return Loc;
662}
663
664SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
665 do {
666 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
667 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
668 Loc = Loc.getFileLocWithOffset(LocInfo.second);
669 } while (!Loc.isFileID());
670 return Loc;
671}
672
673
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000674std::pair<FileID, unsigned>
675SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
676 unsigned Offset) const {
677 // If this is an instantiation record, walk through all the instantiation
678 // points.
679 FileID FID;
680 SourceLocation Loc;
681 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000682 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000684 FID = getFileID(Loc);
685 E = &getSLocEntry(FID);
686 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000687 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000689 return std::make_pair(FID, Offset);
690}
691
692std::pair<FileID, unsigned>
693SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
694 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000695 // If this is an instantiation record, walk through all the instantiation
696 // points.
697 FileID FID;
698 SourceLocation Loc;
699 do {
700 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000702 FID = getFileID(Loc);
703 E = &getSLocEntry(FID);
704 Offset += Loc.getOffset()-E->getOffset();
705 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707 return std::make_pair(FID, Offset);
708}
709
Chris Lattner387616e2009-02-17 08:04:48 +0000710/// getImmediateSpellingLoc - Given a SourceLocation object, return the
711/// spelling location referenced by the ID. This is the first level down
712/// towards the place where the characters that make up the lexed token can be
713/// found. This should not generally be used by clients.
714SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
715 if (Loc.isFileID()) return Loc;
716 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
717 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
718 return Loc.getFileLocWithOffset(LocInfo.second);
719}
720
721
Chris Lattnere7fb4842009-02-15 20:52:18 +0000722/// getImmediateInstantiationRange - Loc is required to be an instantiation
723/// location. Return the start/end of the instantiation information.
724std::pair<SourceLocation,SourceLocation>
725SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
726 assert(Loc.isMacroID() && "Not an instantiation loc!");
727 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
728 return II.getInstantiationLocRange();
729}
730
Chris Lattner66781332009-02-15 21:26:50 +0000731/// getInstantiationRange - Given a SourceLocation object, return the
732/// range of tokens covered by the instantiation in the ultimate file.
733std::pair<SourceLocation,SourceLocation>
734SourceManager::getInstantiationRange(SourceLocation Loc) const {
735 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattner66781332009-02-15 21:26:50 +0000737 std::pair<SourceLocation,SourceLocation> Res =
738 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner66781332009-02-15 21:26:50 +0000740 // Fully resolve the start and end locations to their ultimate instantiation
741 // points.
742 while (!Res.first.isFileID())
743 Res.first = getImmediateInstantiationRange(Res.first).first;
744 while (!Res.second.isFileID())
745 Res.second = getImmediateInstantiationRange(Res.second).second;
746 return Res;
747}
748
Chris Lattnere7fb4842009-02-15 20:52:18 +0000749
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000750
751//===----------------------------------------------------------------------===//
752// Queries about the code at a SourceLocation.
753//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000754
755/// getCharacterData - Return a pointer to the start of the specified location
756/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000757const char *SourceManager::getCharacterData(SourceLocation SL,
758 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 // Note that this is a hot function in the getSpelling() path, which is
760 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000761 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Ted Kremenekc16c2082009-01-06 01:55:26 +0000763 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000764 bool CharDataInvalid = false;
765 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +0000766 = getSLocEntry(LocInfo.first).getFile().getContentCache()
767 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000768 if (Invalid)
769 *Invalid = CharDataInvalid;
770 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
Chris Lattner9dc1f532007-07-20 16:37:10 +0000774/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000775/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000776unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
777 bool *Invalid) const {
778 bool MyInvalid = false;
779 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
780 if (Invalid)
781 *Invalid = MyInvalid;
782
783 if (MyInvalid)
784 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 unsigned LineStart = FilePos;
787 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
788 --LineStart;
789 return FilePos-LineStart+1;
790}
791
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000792// isInvalid - Return the result of calling loc.isInvalid(), and
793// if Invalid is not null, set its value to same.
794static bool isInvalid(SourceLocation Loc, bool *Invalid) {
795 bool MyInvalid = Loc.isInvalid();
796 if (Invalid)
797 *Invalid = MyInvalid;
798 return MyInvalid;
799}
800
Douglas Gregor50f6af72010-03-16 05:20:39 +0000801unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
802 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000803 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000804 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000805 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000806}
807
Douglas Gregor50f6af72010-03-16 05:20:39 +0000808unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
809 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000810 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000811 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000812 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000813}
814
Chandler Carruth14bd9652010-10-23 08:44:57 +0000815static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000816ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
817 llvm::BumpPtrAllocator &Alloc,
818 const SourceManager &SM, bool &Invalid);
819static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
820 llvm::BumpPtrAllocator &Alloc,
821 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000822 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000823 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
824 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000825 if (Invalid)
826 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000828 // Find the file offsets of all of the *physical* source lines. This does
829 // not look at trigraphs, escaped newlines, or anything else tricky.
830 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000832 // Line #1 starts at char 0.
833 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000835 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
836 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
837 unsigned Offs = 0;
838 while (1) {
839 // Skip over the contents of the line.
840 // TODO: Vectorize this? This is very performance sensitive for programs
841 // with lots of diagnostics and in -E mode.
842 const unsigned char *NextBuf = (const unsigned char *)Buf;
843 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
844 ++NextBuf;
845 Offs += NextBuf-Buf;
846 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000848 if (Buf[0] == '\n' || Buf[0] == '\r') {
849 // If this is \n\r or \r\n, skip both characters.
850 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
851 ++Offs, ++Buf;
852 ++Offs, ++Buf;
853 LineOffsets.push_back(Offs);
854 } else {
855 // Otherwise, this is a null. If end of file, exit.
856 if (Buf == End) break;
857 // Otherwise, skip the null.
858 ++Offs, ++Buf;
859 }
860 }
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000862 // Copy the offsets into the FileInfo structure.
863 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000864 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000865 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
866}
Reid Spencer5f016e22007-07-11 17:01:13 +0000867
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000868/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000869/// for the position indicated. This requires building and caching a table of
870/// line offsets for the MemoryBuffer, so this is not cheap: use only when
871/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000872unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
873 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000874 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000875 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000876 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000877 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000878 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000879 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000882 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000883 if (Content->SourceLineCache == 0) {
884 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000885 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000886 if (Invalid)
887 *Invalid = MyInvalid;
888 if (MyInvalid)
889 return 1;
890 } else if (Invalid)
891 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // Okay, we know we have a line number table. Do a binary search to find the
894 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000895 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000896 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000897 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner30fc9332009-02-04 01:06:56 +0000899 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000900
Daniel Dunbar4106d692009-05-18 17:30:52 +0000901 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000902 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000903 //
904 // If it is worth being optimized, then in my opinion it could be more
905 // performant, simpler, and more obviously correct by just "galloping" outward
906 // from the queried file position. In fact, this could be incorporated into a
907 // generic algorithm such as lower_bound_with_hint.
908 //
909 // If someone gives me a test case where this matters, and I will do it! - DWD
910
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000911 // If the previous query was to the same file, we know both the file pos from
912 // that query and the line number returned. This allows us to narrow the
913 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000914 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000915 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000916 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000917 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000919 // The query is likely to be nearby the previous one. Here we check to
920 // see if it is within 5, 10 or 20 lines. It can be far away in cases
921 // where big comment blocks and vertical whitespace eat up lines but
922 // contribute no tokens.
923 if (SourceLineCache+5 < SourceLineCacheEnd) {
924 if (SourceLineCache[5] > QueriedFilePos)
925 SourceLineCacheEnd = SourceLineCache+5;
926 else if (SourceLineCache+10 < SourceLineCacheEnd) {
927 if (SourceLineCache[10] > QueriedFilePos)
928 SourceLineCacheEnd = SourceLineCache+10;
929 else if (SourceLineCache+20 < SourceLineCacheEnd) {
930 if (SourceLineCache[20] > QueriedFilePos)
931 SourceLineCacheEnd = SourceLineCache+20;
932 }
933 }
934 }
935 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000936 if (LastLineNoResult < Content->NumLines)
937 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000938 }
939 }
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000941 // If the spread is large, do a "radix" test as our initial guess, based on
942 // the assumption that lines average to approximately the same length.
943 // NOTE: This is currently disabled, as it does not appear to be profitable in
944 // initial measurements.
945 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000946 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000948 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000949 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000951 // Check for -10 and +10 lines.
952 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
953 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
954
955 // If the computed lower bound is less than the query location, move it in.
956 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
957 SourceLineCacheStart[LowerBound] < QueriedFilePos)
958 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000960 // If the computed upper bound is greater than the query location, move it.
961 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
962 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
963 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000966 unsigned *Pos
967 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000968 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner30fc9332009-02-04 01:06:56 +0000970 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000971 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000972 LastLineNoFilePos = QueriedFilePos;
973 LastLineNoResult = LineNo;
974 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975}
976
Douglas Gregor50f6af72010-03-16 05:20:39 +0000977unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
978 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000979 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +0000980 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
981 return getLineNumber(LocInfo.first, LocInfo.second);
982}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000983unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
984 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000985 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +0000986 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
987 return getLineNumber(LocInfo.first, LocInfo.second);
988}
989
Chris Lattner6b306672009-02-04 05:33:01 +0000990/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000991/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000992/// header, or an "implicit extern C" system header.
993///
994/// This state can be modified with flags on GNU linemarker directives like:
995/// # 4 "foo.h" 3
996/// which changes all source locations in the current file after that to be
997/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000998SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000999SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1000 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1001 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1002 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1003
1004 // If there are no #line directives in this file, just return the whole-file
1005 // state.
1006 if (!FI.hasLineDirectives())
1007 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner6b306672009-02-04 05:33:01 +00001009 assert(LineTable && "Can't have linetable entries without a LineTable!");
1010 // See if there is a #line directive before the location.
1011 const LineEntry *Entry =
1012 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner6b306672009-02-04 05:33:01 +00001014 // If this is before the first line marker, use the file characteristic.
1015 if (!Entry)
1016 return FI.getFileCharacteristic();
1017
1018 return Entry->FileKind;
1019}
1020
Chris Lattnerbff5c512009-02-17 08:39:06 +00001021/// Return the filename or buffer identifier of the buffer the location is in.
1022/// Note that this name does not respect #line directives. Use getPresumedLoc
1023/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001024const char *SourceManager::getBufferName(SourceLocation Loc,
1025 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001026 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregor50f6af72010-03-16 05:20:39 +00001028 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001029}
1030
Chris Lattner30fc9332009-02-04 01:06:56 +00001031
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001032/// getPresumedLoc - This method returns the "presumed" location of a
1033/// SourceLocation specifies. A "presumed location" can be modified by #line
1034/// or GNU line marker directives. This provides a view on the data that a
1035/// user should see in diagnostics, for example.
1036///
1037/// Note that a presumed location is always given as the instantiation point
1038/// of an instantiation location, not at the spelling location.
1039PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1040 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001042 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001043 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner30fc9332009-02-04 01:06:56 +00001045 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001046 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chris Lattner3cd949c2009-02-04 01:55:42 +00001048 // To get the source name, first consult the FileEntry (if one exists)
1049 // before the MemBuffer as this will avoid unnecessarily paging in the
1050 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001051 const char *Filename;
1052 if (C->Entry)
1053 Filename = C->Entry->getName();
1054 else
1055 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregorc417fa02010-11-02 00:39:22 +00001056 bool Invalid = false;
1057 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1058 if (Invalid)
1059 return PresumedLoc();
1060 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1061 if (Invalid)
1062 return PresumedLoc();
1063
Chris Lattner3cd949c2009-02-04 01:55:42 +00001064 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner3cd949c2009-02-04 01:55:42 +00001066 // If we have #line directives in this file, update and overwrite the physical
1067 // location info if appropriate.
1068 if (FI.hasLineDirectives()) {
1069 assert(LineTable && "Can't have linetable entries without a LineTable!");
1070 // See if there is a #line directive before this. If so, get it.
1071 if (const LineEntry *Entry =
1072 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001073 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001074 if (Entry->FilenameID != -1)
1075 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001076
1077 // Use the line number specified by the LineEntry. This line number may
1078 // be multiple lines down from the line entry. Add the difference in
1079 // physical line numbers from the query point and the line marker to the
1080 // total.
1081 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1082 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001084 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattner137b6a62009-02-04 06:25:26 +00001086 // Handle virtual #include manipulation.
1087 if (Entry->IncludeOffset) {
1088 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1089 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1090 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001091 }
1092 }
1093
1094 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001095}
1096
1097//===----------------------------------------------------------------------===//
1098// Other miscellaneous methods.
1099//===----------------------------------------------------------------------===//
1100
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001101/// \brief Get the source location for the given file:line:col triplet.
1102///
1103/// If the source file is included multiple times, the source location will
1104/// be based upon the first inclusion.
1105SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1106 unsigned Line, unsigned Col) const {
1107 assert(SourceFile && "Null source file!");
1108 assert(Line && Col && "Line and column should start from 1!");
1109
1110 fileinfo_iterator FI = FileInfos.find(SourceFile);
1111 if (FI == FileInfos.end())
1112 return SourceLocation();
1113 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001115 // If this is the first use of line information for this buffer, compute the
1116 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001117 if (Content->SourceLineCache == 0) {
1118 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001119 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001120 if (MyInvalid)
1121 return SourceLocation();
1122 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001123
Douglas Gregor4a160e12009-12-02 05:34:39 +00001124 // Find the first file ID that corresponds to the given file.
1125 FileID FirstFID;
1126
1127 // First, check the main file ID, since it is common to look for a
1128 // location in the main file.
1129 if (!MainFileID.isInvalid()) {
1130 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1131 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1132 FirstFID = MainFileID;
1133 }
1134
1135 if (FirstFID.isInvalid()) {
1136 // The location we're looking for isn't in the main file; look
1137 // through all of the source locations.
1138 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1139 const SLocEntry &SLoc = getSLocEntry(I);
1140 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1141 FirstFID = FileID::get(I);
1142 break;
1143 }
1144 }
1145 }
1146
1147 if (FirstFID.isInvalid())
1148 return SourceLocation();
1149
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001150 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001151 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001152 if (Size > 0)
1153 --Size;
1154 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1155 }
1156
1157 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001158 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1159 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001160 unsigned i = 0;
1161
1162 // Check that the given column is valid.
1163 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1164 ++i;
1165 if (i < Col-1)
1166 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1167
Douglas Gregor4a160e12009-12-02 05:34:39 +00001168 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001169}
1170
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001171/// Given a decomposed source location, move it up the include/instantiation
1172/// stack to the parent source location. If this is possible, return the
1173/// decomposed version of the parent in Loc and return false. If Loc is the
1174/// top-level entry, return true and don't modify it.
1175static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1176 const SourceManager &SM) {
1177 SourceLocation UpperLoc;
1178 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1179 if (Entry.isInstantiation())
1180 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1181 else
1182 UpperLoc = Entry.getFile().getIncludeLoc();
1183
1184 if (UpperLoc.isInvalid())
1185 return true; // We reached the top.
1186
1187 Loc = SM.getDecomposedLoc(UpperLoc);
1188 return false;
1189}
1190
1191
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001192/// \brief Determines the order of 2 source locations in the translation unit.
1193///
1194/// \returns true if LHS source location comes before RHS, false otherwise.
1195bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1196 SourceLocation RHS) const {
1197 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1198 if (LHS == RHS)
1199 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001201 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1202 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001204 // If the source locations are in the same file, just compare offsets.
1205 if (LOffs.first == ROffs.first)
1206 return LOffs.second < ROffs.second;
1207
1208 // If we are comparing a source location with multiple locations in the same
1209 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001210 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1211 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001213 // Okay, we missed in the cache, start updating the cache for this query.
1214 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001216 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001217 // find a common "ancestor". FileIDs build a tree-like structure that
1218 // reflects the #include hierarchy, and this algorithm needs to find the
1219 // nearest common ancestor between the two locations. For example, if you
1220 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1221 // a location in c.h, we need to find that their nearest common ancestor is
1222 // a.c, and compare the locations of the two #includes to find their relative
1223 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001224 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001225 // SourceManager assigns FileIDs in order of parsing. This means that an
1226 // includee always has a larger FileID than an includer. While you might
1227 // think that we could just compare the FileID's here, that doesn't work to
1228 // compare a point at the end of a.c with a point within c.h. Though c.h has
1229 // a larger FileID, we have to compare the include point of c.h to the
1230 // location in a.c.
1231 //
1232 // Despite not being able to directly compare FileID's, we can tell that a
1233 // larger FileID is necessarily more deeply nested than a lower one and use
1234 // this information to walk up the tree to the nearest common ancestor.
1235 do {
1236 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1237 // ROffs, walk up the #include chain.
1238 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001239 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001240 break; // We reached the top.
1241
Chris Lattner48296ba2010-05-07 05:51:13 +00001242 } else {
1243 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1244 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001245 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001246 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001247 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001248 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner48296ba2010-05-07 05:51:13 +00001250 // If we exited because we found a nearest common ancestor, compare the
1251 // locations within the common file and cache them.
1252 if (LOffs.first == ROffs.first) {
1253 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1254 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001255 }
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001257 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001258 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001259 // FIXME: We should rearrange the external interface so this simply never
1260 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001261 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1262
1263 // Zip both entries up to the top level record.
1264 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1265 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001266
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001267 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001268
1269 // Strip off macro instantation locations, going up to the top-level File
1270 // SLocEntry.
1271 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1272 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001273 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001274 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001276 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001277 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001278}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001279
Reid Spencer5f016e22007-07-11 17:01:13 +00001280/// PrintStats - Print statistics to stderr.
1281///
1282void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001283 llvm::errs() << "\n*** Source Manager Stats:\n";
1284 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1285 << " mem buffers mapped.\n";
1286 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1287 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 unsigned NumLineNumsComputed = 0;
1290 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001291 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1292 NumLineNumsComputed += I->second->SourceLineCache != 0;
1293 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001296 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1297 << NumLineNumsComputed << " files with line #'s computed.\n";
1298 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1299 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001300}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001301
1302ExternalSLocEntrySource::~ExternalSLocEntrySource() { }