blob: d5e71e9363d6542e8111be35be1131de42c13e9a [file] [log] [blame]
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001//===- SourceManager.cpp - Track and cache source files -------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
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 Gregor802b7762010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000017#include "clang/Basic/LLVM.h"
18#include "clang/Basic/SourceLocation.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000020#include "llvm/ADT/DenseMap.h"
Douglas Gregore6642762011-02-03 17:17:35 +000021#include "llvm/ADT/Optional.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000022#include "llvm/ADT/None.h"
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000024#include "llvm/ADT/SmallVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000026#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/Allocator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/Support/Capacity.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000029#include "llvm/Support/Compiler.h"
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/FileSystem.h"
32#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000033#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000034#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000036#include <algorithm>
Eugene Zelenko918e0ca2017-11-03 22:35:27 +000037#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <memory>
41#include <tuple>
42#include <utility>
43#include <vector>
Douglas Gregor802b7762010-03-15 22:54:52 +000044
Chris Lattner22eb9722006-06-18 05:43:12 +000045using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000046using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000047using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000048
Chris Lattner153a0f12009-02-04 00:40:31 +000049//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000050// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000051//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000052
Ted Kremenekc08bca62007-10-30 21:08:08 +000053ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000054 if (shouldFreeBuffer())
55 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000056}
57
Chandler Carruth64ee7822011-07-26 05:17:23 +000058/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
59/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000060unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000061 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000062}
63
Ted Kremenek8d587902011-04-28 20:36:42 +000064/// Returns the kind of memory used to back the memory buffer for
65/// this content cache. This is used for performance analysis.
66llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
67 assert(Buffer.getPointer());
68
69 // Should be unreachable, but keep for sanity.
70 if (!Buffer.getPointer())
71 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
David Blaikie66cc07b2014-06-27 17:40:03 +000072
73 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenek8d587902011-04-28 20:36:42 +000074 return buf->getBufferKind();
75}
76
Ted Kremenek12c2af42009-01-06 01:55:26 +000077/// getSize - Returns the size of the content encapsulated by this ContentCache.
78/// This can be the size of the source file or the size of an arbitrary
79/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000080/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000081unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000082 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000083 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000084}
85
David Blaikie66cc07b2014-06-27 17:40:03 +000086void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +000087 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidiscc6107d2011-12-10 01:38:26 +000088 assert(0 && "Replacing with the same buffer");
89 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
90 return;
91 }
Richard Smithf878a842017-06-05 22:05:31 +000092
Douglas Gregor3f4bea02010-07-26 21:36:20 +000093 if (shouldFreeBuffer())
94 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000095 Buffer.setPointer(B);
Richard Smithf878a842017-06-05 22:05:31 +000096 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000097}
98
David Blaikie66cc07b2014-06-27 17:40:03 +000099llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
100 const SourceManager &SM,
101 SourceLocation Loc,
102 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +0000103 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +0000104 // computed it, just return what we have.
Craig Topperf1186c52014-05-08 06:41:40 +0000105 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattner5631b052010-11-23 08:50:03 +0000106 if (Invalid)
107 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +0000108
Chris Lattner5631b052010-11-23 08:50:03 +0000109 return Buffer.getPointer();
110 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +0000111
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000112 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Benjamin Kramera8857962014-10-26 22:44:13 +0000113 auto BufferOrError =
114 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
Chris Lattner5631b052010-11-23 08:50:03 +0000115
116 // If we were unable to open the file, then we are in an inconsistent
117 // situation where the content cache referenced a file which no longer
118 // exists. Most likely, we were using a stat cache with an invalid entry but
119 // the file could also have been removed during processing. Since we can't
120 // really deal with this situation, just create an empty buffer.
121 //
122 // FIXME: This is definitely not ideal, but our immediate clients can't
123 // currently handle returning a null entry here. Ideally we should detect
124 // that we are in an inconsistent situation and error out as quickly as
125 // possible.
Benjamin Kramera8857962014-10-26 22:44:13 +0000126 if (!BufferOrError) {
Craig Topperbf3e3272014-08-30 16:55:52 +0000127 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Pavel Labathbf8519b2017-12-20 11:34:38 +0000128 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
129 ContentsEntry->getSize(), "<invalid>");
130 char *Ptr = BackupBuffer->getBufferStart();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000131 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000132 Ptr[i] = FillStr[i % FillStr.size()];
Pavel Labathbf8519b2017-12-20 11:34:38 +0000133 Buffer.setPointer(BackupBuffer.release());
Chris Lattner5631b052010-11-23 08:50:03 +0000134
135 if (Diag.isDiagnosticInFlight())
Benjamin Kramera8857962014-10-26 22:44:13 +0000136 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
137 ContentsEntry->getName(),
138 BufferOrError.getError().message());
139 else
Chris Lattner5631b052010-11-23 08:50:03 +0000140 Diag.Report(Loc, diag::err_cannot_open_file)
Benjamin Kramera8857962014-10-26 22:44:13 +0000141 << ContentsEntry->getName() << BufferOrError.getError().message();
Chris Lattner5631b052010-11-23 08:50:03 +0000142
143 Buffer.setInt(Buffer.getInt() | InvalidFlag);
144
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
147 }
Benjamin Kramera8857962014-10-26 22:44:13 +0000148
149 Buffer.setPointer(BufferOrError->release());
150
Chris Lattner5631b052010-11-23 08:50:03 +0000151 // Check that the file's size is the same as in the file entry (which may
152 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000153 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000154 if (Diag.isDiagnosticInFlight())
155 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000156 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000157 else
158 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000159 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000160
161 Buffer.setInt(Buffer.getInt() | InvalidFlag);
162 if (Invalid) *Invalid = true;
163 return Buffer.getPointer();
164 }
Eric Christopher7f36a792011-04-09 00:01:04 +0000165
Chris Lattner5631b052010-11-23 08:50:03 +0000166 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher7f36a792011-04-09 00:01:04 +0000167 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattner5631b052010-11-23 08:50:03 +0000168 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000169 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher7f36a792011-04-09 00:01:04 +0000170 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattner5631b052010-11-23 08:50:03 +0000171 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
172 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
David Zarzyckib0c752d2018-02-26 18:42:30 +0000173 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
174 "UTF-32 (BE)")
175 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
176 "UTF-32 (LE)")
Chris Lattner5631b052010-11-23 08:50:03 +0000177 .StartsWith("\x2B\x2F\x76", "UTF-7")
178 .StartsWith("\xF7\x64\x4C", "UTF-1")
179 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
180 .StartsWith("\x0E\xFE\xFF", "SDSU")
181 .StartsWith("\xFB\xEE\x28", "BOCU-1")
182 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Craig Topperf1186c52014-05-08 06:41:40 +0000183 .Default(nullptr);
Chris Lattner5631b052010-11-23 08:50:03 +0000184
Eric Christopher7f36a792011-04-09 00:01:04 +0000185 if (InvalidBOM) {
Chris Lattner5631b052010-11-23 08:50:03 +0000186 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher7f36a792011-04-09 00:01:04 +0000187 << InvalidBOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000188 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000189 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000190
Douglas Gregor82752ec2010-03-16 22:53:51 +0000191 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000192 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000193
194 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000195}
196
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000197unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
David Blaikie13156b62014-11-19 03:06:06 +0000198 auto IterBool =
199 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
200 if (IterBool.second)
201 FilenamesByID.push_back(&*IterBool.first);
202 return IterBool.first->second;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000203}
204
Reid Klecknereb00ee02017-05-22 21:42:58 +0000205/// Add a line note to the line table that indicates that there is a \#line or
206/// GNU line marker at the specified FID/Offset location which changes the
207/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
208/// change the presumed \#include stack. If it is 1, this is a file entry, if
209/// it is 2 then this is a file exit. FileKind specifies whether this is a
210/// system header or extern C system header.
211void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
212 int FilenameID, unsigned EntryExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000213 SrcMgr::CharacteristicKind FileKind) {
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000214 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000215
Reid Klecknereb00ee02017-05-22 21:42:58 +0000216 // An unspecified FilenameID means use the last filename if available, or the
217 // main source file otherwise.
218 if (FilenameID == -1 && !Entries.empty())
219 FilenameID = Entries.back().FilenameID;
220
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000221 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
222 "Adding line entries out of order!");
223
Chris Lattner1c967782009-02-04 06:25:26 +0000224 unsigned IncludeOffset = 0;
225 if (EntryExit == 0) { // No #include stack change.
226 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
227 } else if (EntryExit == 1) {
228 IncludeOffset = Offset-1;
229 } else if (EntryExit == 2) {
230 assert(!Entries.empty() && Entries.back().IncludeOffset &&
231 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000232
Chris Lattner1c967782009-02-04 06:25:26 +0000233 // Get the include loc of the last entries' include loc as our include loc.
234 IncludeOffset = 0;
235 if (const LineEntry *PrevEntry =
236 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
237 IncludeOffset = PrevEntry->IncludeOffset;
238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattner1c967782009-02-04 06:25:26 +0000240 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
241 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000242}
243
Chris Lattnerd4293922009-02-04 01:55:42 +0000244/// FindNearestLineEntry - Find the line entry nearest to FID that is before
245/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000246const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000247 unsigned Offset) {
248 const std::vector<LineEntry> &Entries = LineEntries[FID];
249 assert(!Entries.empty() && "No #line entries for this FID after all!");
250
Chris Lattner334a2ad2009-02-04 04:46:59 +0000251 // It is very common for the query to be after the last #line, check this
252 // first.
253 if (Entries.back().FileOffset <= Offset)
254 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000255
Chris Lattner334a2ad2009-02-04 04:46:59 +0000256 // Do a binary search to find the maximal element that is still before Offset.
257 std::vector<LineEntry>::const_iterator I =
258 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Craig Topperf1186c52014-05-08 06:41:40 +0000259 if (I == Entries.begin()) return nullptr;
Chris Lattner334a2ad2009-02-04 04:46:59 +0000260 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000261}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000262
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000263/// \brief Add a new line entry that has already been encoded into
264/// the internal representation of the line table.
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000265void LineTableInfo::AddEntry(FileID FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000266 const std::vector<LineEntry> &Entries) {
267 LineEntries[FID] = Entries;
268}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000269
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000270/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000271unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000272 return getLineTable().getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000273}
274
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000275/// AddLineNote - Add a line note to the line table for the FileID and offset
276/// specified by Loc. If FilenameID is -1, it is considered to be
277/// unspecified.
278void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000279 int FilenameID, bool IsFileEntry,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000280 bool IsFileExit,
281 SrcMgr::CharacteristicKind FileKind) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000282 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000283
284 bool Invalid = false;
285 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
286 if (!Entry.isFile() || Invalid)
287 return;
Reid Klecknereb00ee02017-05-22 21:42:58 +0000288
Douglas Gregor49f754f2011-04-20 00:21:03 +0000289 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000290
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000291 // Remember that this file has #line directives now if it doesn't already.
292 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000293
Vedant Kumar5eeeab72015-11-12 00:11:19 +0000294 (void) getLineTable();
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000296 unsigned EntryExit = 0;
297 if (IsFileEntry)
298 EntryExit = 1;
299 else if (IsFileExit)
300 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000301
Douglas Gregor02c2dbf2012-06-08 16:40:28 +0000302 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000303 EntryExit, FileKind);
304}
305
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000306LineTableInfo &SourceManager::getLineTable() {
Craig Topperf1186c52014-05-08 06:41:40 +0000307 if (!LineTable)
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000308 LineTable = new LineTableInfo();
309 return *LineTable;
310}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000311
Chris Lattner153a0f12009-02-04 00:40:31 +0000312//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000313// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000314//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000315
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000316SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
317 bool UserFilesAreVolatile)
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000318 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000319 clearIDTables();
320 Diag.setSourceManager(this);
321}
322
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000323SourceManager::~SourceManager() {
324 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattnerc8233df2009-02-03 07:30:45 +0000326 // Delete FileEntry objects corresponding to content caches. Since the actual
327 // content cache objects are bump pointer allocated, we just have to run the
328 // dtors, but we call the deallocate method for completeness.
329 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000330 if (MemBufferInfos[i]) {
331 MemBufferInfos[i]->~ContentCache();
332 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
333 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000334 }
335 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
336 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidisaf41b3f2011-12-15 23:37:55 +0000337 if (I->second) {
338 I->second->~ContentCache();
339 ContentCacheAlloc.Deallocate(I->second);
340 }
Chris Lattnerc8233df2009-02-03 07:30:45 +0000341 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000342}
343
344void SourceManager::clearIDTables() {
345 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000346 LocalSLocEntryTable.clear();
347 LoadedSLocEntryTable.clear();
348 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000349 LastLineNoFileIDQuery = FileID();
Craig Topperf1186c52014-05-08 06:41:40 +0000350 LastLineNoContentCache = nullptr;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000351 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000353 if (LineTable)
354 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000355
Chandler Carruth64ee7822011-07-26 05:17:23 +0000356 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000357 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000358 CurrentLoadedOffset = MaxLoadedOffset;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000359 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000360}
361
Richard Smithab755972017-06-05 18:10:11 +0000362void SourceManager::initializeForReplay(const SourceManager &Old) {
363 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
364
365 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
366 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
367 Clone->OrigEntry = Cache->OrigEntry;
368 Clone->ContentsEntry = Cache->ContentsEntry;
369 Clone->BufferOverridden = Cache->BufferOverridden;
370 Clone->IsSystemFile = Cache->IsSystemFile;
371 Clone->IsTransient = Cache->IsTransient;
372 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
373 return Clone;
374 };
375
Richard Smithab755972017-06-05 18:10:11 +0000376 // Ensure all SLocEntries are loaded from the external source.
377 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
378 if (!Old.SLocEntryLoaded[I])
379 Old.loadSLocEntry(I, nullptr);
380
381 // Inherit any content cache data from the old source manager.
382 for (auto &FileInfo : Old.FileInfos) {
383 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
384 if (Slot)
385 continue;
386 Slot = CloneContentCache(FileInfo.second);
387 }
388}
389
Chris Lattner4fa23622009-01-26 00:43:02 +0000390/// getOrCreateContentCache - Create or return a cached ContentCache for the
391/// specified file.
392const ContentCache *
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000393SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
394 bool isSystemFile) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattner22eb9722006-06-18 05:43:12 +0000397 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000398 ContentCache *&Entry = FileInfos[FileEnt];
399 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chandler Carruth47c48082014-04-15 21:34:12 +0000401 // Nope, create a new Cache entry.
402 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000403
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000404 if (OverriddenFilesInfo) {
405 // If the file contents are overridden with contents from another file,
406 // pass that file to ContentCache.
407 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
408 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
409 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
410 new (Entry) ContentCache(FileEnt);
411 else
412 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
413 : overI->second,
414 overI->second);
415 } else {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000416 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000417 }
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000418
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000419 Entry->IsSystemFile = isSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +0000420 Entry->IsTransient = FilesAreTransient;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000421
Chris Lattnerc8233df2009-02-03 07:30:45 +0000422 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000423}
424
Richard Smith6d9bc272017-09-09 01:14:04 +0000425/// Create a new ContentCache for the specified memory buffer.
426/// This does no caching.
427const ContentCache *
428SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer,
429 bool DoNotFree) {
Chandler Carruth47c48082014-04-15 21:34:12 +0000430 // Add a new ContentCache to the MemBufferInfos list and return it.
431 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000432 new (Entry) ContentCache();
433 MemBufferInfos.push_back(Entry);
Richard Smith6d9bc272017-09-09 01:14:04 +0000434 Entry->replaceBuffer(Buffer, DoNotFree);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000435 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000436}
437
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000438const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
439 bool *Invalid) const {
440 assert(!SLocEntryLoaded[Index]);
441 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
442 if (Invalid)
443 *Invalid = true;
444 // If the file of the SLocEntry changed we could still have loaded it.
445 if (!SLocEntryLoaded[Index]) {
446 // Try to recover; create a SLocEntry so the rest of clang can handle it.
447 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
448 FileInfo::get(SourceLocation(),
449 getFakeContentCacheForRecovery(),
450 SrcMgr::C_User));
451 }
452 }
453
454 return LoadedSLocEntryTable[Index];
455}
456
Douglas Gregor925296b2011-07-19 16:10:42 +0000457std::pair<int, unsigned>
458SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
459 unsigned TotalSize) {
460 assert(ExternalSLocEntries && "Don't have an external sloc source");
Richard Smith78d81ec2015-08-12 22:25:24 +0000461 // Make sure we're not about to run out of source locations.
462 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
463 return std::make_pair(0, 0);
Douglas Gregor925296b2011-07-19 16:10:42 +0000464 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
465 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
466 CurrentLoadedOffset -= TotalSize;
Douglas Gregor925296b2011-07-19 16:10:42 +0000467 int ID = LoadedSLocEntryTable.size();
468 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor0bc12932009-04-27 21:28:04 +0000469}
470
Douglas Gregor49f754f2011-04-20 00:21:03 +0000471/// \brief As part of recovering from missing or changed content, produce a
472/// fake, non-empty buffer.
David Blaikie66cc07b2014-06-27 17:40:03 +0000473llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000474 if (!FakeBufferForRecovery)
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000475 FakeBufferForRecovery =
476 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000477
478 return FakeBufferForRecovery.get();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000479}
Douglas Gregor258ae542009-04-27 06:38:32 +0000480
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000481/// \brief As part of recovering from missing or changed content, produce a
482/// fake content cache.
483const SrcMgr::ContentCache *
484SourceManager::getFakeContentCacheForRecovery() const {
485 if (!FakeContentCacheForRecovery) {
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000486 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000487 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
488 /*DoNotFree=*/true);
489 }
Rafael Espindolae0f6d882014-08-18 18:33:41 +0000490 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidis969fdfd2012-02-20 23:58:07 +0000491}
492
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000493/// \brief Returns the previous in-order FileID or an invalid FileID if there
494/// is no previous one.
495FileID SourceManager::getPreviousFileID(FileID FID) const {
496 if (FID.isInvalid())
497 return FileID();
498
499 int ID = FID.ID;
500 if (ID == -1)
501 return FileID();
502
503 if (ID > 0) {
504 if (ID-1 == 0)
505 return FileID();
506 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
507 return FileID();
508 }
509
510 return FileID::get(ID-1);
511}
512
513/// \brief Returns the next in-order FileID or an invalid FileID if there is
514/// no next one.
515FileID SourceManager::getNextFileID(FileID FID) const {
516 if (FID.isInvalid())
517 return FileID();
518
519 int ID = FID.ID;
520 if (ID > 0) {
521 if (unsigned(ID+1) >= local_sloc_entry_size())
522 return FileID();
523 } else if (ID+1 >= -1) {
524 return FileID();
525 }
526
527 return FileID::get(ID+1);
528}
529
Chris Lattner4fa23622009-01-26 00:43:02 +0000530//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000531// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000532//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000533
Dan Gohmance46f022010-08-26 21:27:06 +0000534/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000535/// include position. This works regardless of whether the ContentCache
536/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000537FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000538 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000539 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-07-19 16:10:42 +0000540 int LoadedID, unsigned LoadedOffset) {
541 if (LoadedID < 0) {
542 assert(LoadedID != -1 && "Loading sentinel FileID");
543 unsigned Index = unsigned(-LoadedID) - 2;
544 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
545 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
546 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
547 FileInfo::get(IncludePos, File, FileCharacter));
548 SLocEntryLoaded[Index] = true;
549 return FileID::get(LoadedID);
Douglas Gregor258ae542009-04-27 06:38:32 +0000550 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000551 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
552 FileInfo::get(IncludePos, File,
553 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000554 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-07-19 16:10:42 +0000555 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
556 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
557 "Ran out of source locations!");
558 // We do a +1 here because we want a SourceLocation that means "the end of the
559 // file", e.g. for the "no newline at the end of the file" diagnostic.
560 NextLocalOffset += FileSize + 1;
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattner4fa23622009-01-26 00:43:02 +0000562 // Set LastFileIDLookup to the newly created file. The next getFileID call is
563 // almost guaranteed to be from that file.
Douglas Gregor925296b2011-07-19 16:10:42 +0000564 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000565 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000566}
567
Chandler Carruth402bb382011-07-07 23:56:36 +0000568SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000569SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
570 SourceLocation ExpansionLoc,
571 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000572 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
573 ExpansionLoc);
574 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000575}
576
577SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000578SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
579 SourceLocation ExpansionLocStart,
580 SourceLocation ExpansionLocEnd,
581 unsigned TokLength,
Richard Smithb5f81712018-04-30 05:25:48 +0000582 bool ExpansionIsTokenRange,
Chandler Carruth115b0772011-07-26 03:03:05 +0000583 int LoadedID,
584 unsigned LoadedOffset) {
Richard Smithb5f81712018-04-30 05:25:48 +0000585 ExpansionInfo Info = ExpansionInfo::create(
586 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000587 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000588}
589
Richard Smithb5f81712018-04-30 05:25:48 +0000590SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
591 SourceLocation TokenStart,
592 SourceLocation TokenEnd) {
593 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
594 "token spans multiple files");
595 return createExpansionLocImpl(
596 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
597 TokenEnd.getOffset() - TokenStart.getOffset());
598}
599
Chandler Carruth115b0772011-07-26 03:03:05 +0000600SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000601SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000602 unsigned TokLength,
603 int LoadedID,
604 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000605 if (LoadedID < 0) {
606 assert(LoadedID != -1 && "Loading sentinel FileID");
607 unsigned Index = unsigned(-LoadedID) - 2;
608 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
609 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000610 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000611 SLocEntryLoaded[Index] = true;
612 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000613 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000614 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000615 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
616 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
617 "Ran out of source locations!");
618 // See createFileID for that +1.
619 NextLocalOffset += TokLength + 1;
620 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000621}
622
David Blaikie66cc07b2014-06-27 17:40:03 +0000623llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
624 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000625 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000626 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000627 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000628}
629
Dan Gohman5d223dc2010-10-26 20:47:28 +0000630void SourceManager::overrideFileContents(const FileEntry *SourceFile,
David Blaikie66cc07b2014-06-27 17:40:03 +0000631 llvm::MemoryBuffer *Buffer,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000632 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000633 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000634 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000635
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000636 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor9dc32122011-11-16 20:05:18 +0000637 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000638
639 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000640}
641
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000642void SourceManager::overrideFileContents(const FileEntry *SourceFile,
643 const FileEntry *NewFile) {
644 assert(SourceFile->getSize() == NewFile->getSize() &&
645 "Different sizes, use the FileManager to create a virtual file with "
646 "the correct size");
647 assert(FileInfos.count(SourceFile) == 0 &&
648 "This function should be called at the initialization stage, before "
649 "any parsing occurs.");
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000650 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
651}
652
653void SourceManager::disableFileContentsOverride(const FileEntry *File) {
654 if (!isFileOverridden(File))
655 return;
656
657 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Craig Topperf1186c52014-05-08 06:41:40 +0000658 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000659 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
660
661 assert(OverriddenFilesInfo);
662 OverriddenFilesInfo->OverriddenFiles.erase(File);
663 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000664}
665
Richard Smitha8cfffa2015-11-26 02:04:16 +0000666void SourceManager::setFileIsTransient(const FileEntry *File) {
Richard Smithfb1e7f72015-08-14 05:02:58 +0000667 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
Richard Smitha8cfffa2015-11-26 02:04:16 +0000668 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
Richard Smithfb1e7f72015-08-14 05:02:58 +0000669}
670
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000671StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000672 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000673 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000674 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor86af9842011-01-31 22:42:36 +0000675 if (Invalid)
676 *Invalid = true;
677 return "<<<<<INVALID SOURCE LOCATION>>>>>";
678 }
David Blaikie66cc07b2014-06-27 17:40:03 +0000679
680 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
681 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000682 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000683 *Invalid = MyInvalid;
684
685 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000686 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000687
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000688 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000689}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000690
Chris Lattner153a0f12009-02-04 00:40:31 +0000691//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000692// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000693//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000694
Douglas Gregor925296b2011-07-19 16:10:42 +0000695/// \brief Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000696///
Douglas Gregor925296b2011-07-19 16:10:42 +0000697/// This is the cache-miss path of getFileID. Not as hot as that function, but
698/// still very important. It is responsible for finding the entry in the
699/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000700FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000701 if (!SLocOffset)
702 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000703
Douglas Gregor925296b2011-07-19 16:10:42 +0000704 // Now it is time to search for the correct file. See where the SLocOffset
705 // sits in the global view and consult local or loaded buffers for it.
706 if (SLocOffset < NextLocalOffset)
707 return getFileIDLocal(SLocOffset);
708 return getFileIDLoaded(SLocOffset);
709}
710
711/// \brief Return the FileID for a SourceLocation with a low offset.
712///
713/// This function knows that the SourceLocation is in a local buffer, not a
714/// loaded one.
715FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
716 assert(SLocOffset < NextLocalOffset && "Bad function choice");
717
Chris Lattner4fa23622009-01-26 00:43:02 +0000718 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000719 // behavior: 1) a lot of searched FileID's are "near" the cached file
720 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000721 // completely random and may be a very long way away.
722 //
723 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
724 // then we fall back to a less cache efficient, but more scalable, binary
725 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattner4fa23622009-01-26 00:43:02 +0000727 // See if this is near the file point - worst case we start scanning from the
728 // most newly created FileID.
Benjamin Kramer2999b772013-02-22 18:29:39 +0000729 const SrcMgr::SLocEntry *I;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Douglas Gregor925296b2011-07-19 16:10:42 +0000731 if (LastFileIDLookup.ID < 0 ||
732 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000733 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000734 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000735 } else {
736 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000737 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000738 }
739
740 // Find the FileID that contains this. "I" is an iterator that points to a
741 // FileID whose offset is known to be larger than SLocOffset.
742 unsigned NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000743 while (true) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000744 --I;
745 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000746 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000747
Chandler Carruth64ee7822011-07-26 05:17:23 +0000748 // If this isn't an expansion, remember it. We have good locality across
749 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000750 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000751 LastFileIDLookup = Res;
752 NumLinearScans += NumProbes+1;
753 return Res;
754 }
755 if (++NumProbes == 8)
756 break;
757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattner4fa23622009-01-26 00:43:02 +0000759 // Convert "I" back into an index. We know that it is an entry whose index is
760 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000761 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000762 // LessIndex - This is the lower bound of the range that we're searching.
763 // We know that the offset corresponding to the FileID is is less than
764 // SLocOffset.
765 unsigned LessIndex = 0;
766 NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000767 while (true) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000768 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000769 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000770 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000771 if (Invalid)
772 return FileID::get(0);
773
Chris Lattner4fa23622009-01-26 00:43:02 +0000774 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000775
Chris Lattner4fa23622009-01-26 00:43:02 +0000776 // If the offset of the midpoint is too large, chop the high side of the
777 // range to the midpoint.
778 if (MidOffset > SLocOffset) {
779 GreaterIndex = MiddleIndex;
780 continue;
781 }
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner4fa23622009-01-26 00:43:02 +0000783 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000784 // FIXME: This could be made faster by using a function that's aware of
785 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000786 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000787 FileID Res = FileID::get(MiddleIndex);
788
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000789 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000790 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000791 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000792 LastFileIDLookup = Res;
793 NumBinaryProbes += NumProbes;
794 return Res;
795 }
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattner4fa23622009-01-26 00:43:02 +0000797 // Otherwise, move the low-side up to the middle index.
798 LessIndex = MiddleIndex;
799 }
800}
801
Douglas Gregor925296b2011-07-19 16:10:42 +0000802/// \brief Return the FileID for a SourceLocation with a high offset.
803///
804/// This function knows that the SourceLocation is in a loaded buffer, not a
805/// local one.
806FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000807 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000808 if (SLocOffset < CurrentLoadedOffset) {
809 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000810 return FileID();
Argyrios Kyrtzidis8edffaa2011-10-25 00:29:44 +0000811 }
Argyrios Kyrtzidis25029d42011-10-03 23:43:01 +0000812
Douglas Gregor925296b2011-07-19 16:10:42 +0000813 // Essentially the same as the local case, but the loaded array is sorted
814 // in the other direction.
815
816 // First do a linear scan from the last lookup position, if possible.
817 unsigned I;
818 int LastID = LastFileIDLookup.ID;
819 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
820 I = 0;
821 else
822 I = (-LastID - 2) + 1;
823
824 unsigned NumProbes;
825 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
826 // Make sure the entry is loaded!
827 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
828 if (E.getOffset() <= SLocOffset) {
829 FileID Res = FileID::get(-int(I) - 2);
830
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000831 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000832 LastFileIDLookup = Res;
833 NumLinearScans += NumProbes + 1;
834 return Res;
835 }
836 }
837
838 // Linear scan failed. Do the binary search. Note the reverse sorting of the
839 // table: GreaterIndex is the one where the offset is greater, which is
840 // actually a lower index!
841 unsigned GreaterIndex = I;
842 unsigned LessIndex = LoadedSLocEntryTable.size();
843 NumProbes = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +0000844 while (true) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000845 ++NumProbes;
846 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
847 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000848 if (E.getOffset() == 0)
849 return FileID(); // invalid entry.
Douglas Gregor925296b2011-07-19 16:10:42 +0000850
851 ++NumProbes;
852
853 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7dc4f332013-03-01 03:26:00 +0000854 // Sanity checking, otherwise a bug may lead to hanging in release build.
855 if (GreaterIndex == MiddleIndex) {
856 assert(0 && "binary search missed the entry");
857 return FileID();
858 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000859 GreaterIndex = MiddleIndex;
860 continue;
861 }
862
863 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
864 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000865 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000866 LastFileIDLookup = Res;
867 NumBinaryProbes += NumProbes;
868 return Res;
869 }
870
Argyrios Kyrtzidis1ca73442013-03-01 03:43:33 +0000871 // Sanity checking, otherwise a bug may lead to hanging in release build.
872 if (LessIndex == MiddleIndex) {
873 assert(0 && "binary search missed the entry");
874 return FileID();
875 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000876 LessIndex = MiddleIndex;
877 }
878}
879
Chris Lattner659ac5f2009-01-26 20:04:19 +0000880SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000881getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000882 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000883 // Note: If Loc indicates an offset into a token that came from a macro
884 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000885 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000886 // location is the macro invocation, which the offset has nothing to do
887 // with. This is unlike when we get the spelling loc, because the offset
888 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000889 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000890 } while (!Loc.isFileID());
891
892 return Loc;
893}
894
895SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
896 do {
897 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000898 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000899 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattner659ac5f2009-01-26 20:04:19 +0000900 } while (!Loc.isFileID());
901 return Loc;
902}
903
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000904SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
905 do {
906 if (isMacroArgExpansion(Loc))
907 Loc = getImmediateSpellingLoc(Loc);
908 else
Richard Smithb5f81712018-04-30 05:25:48 +0000909 Loc = getImmediateExpansionRange(Loc).getBegin();
Argyrios Kyrtzidis7f6b0292011-10-12 07:07:40 +0000910 } while (!Loc.isFileID());
911 return Loc;
912}
913
Chris Lattner659ac5f2009-01-26 20:04:19 +0000914
Chris Lattner4fa23622009-01-26 00:43:02 +0000915std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000916SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000917 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000918 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000919 FileID FID;
920 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000921 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000922 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000923 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner4fa23622009-01-26 00:43:02 +0000925 FID = getFileID(Loc);
926 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000927 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000928 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner4fa23622009-01-26 00:43:02 +0000930 return std::make_pair(FID, Offset);
931}
932
933std::pair<FileID, unsigned>
934SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
935 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000936 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000937 FileID FID;
938 SourceLocation Loc;
939 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000940 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000941 Loc = Loc.getLocWithOffset(Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner31af4e02009-01-26 19:41:58 +0000943 FID = getFileID(Loc);
944 E = &getSLocEntry(FID);
Argyrios Kyrtzidis2797df62011-08-23 21:02:41 +0000945 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000946 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chris Lattner4fa23622009-01-26 00:43:02 +0000948 return std::make_pair(FID, Offset);
949}
950
Chris Lattner8ad52d52009-02-17 08:04:48 +0000951/// getImmediateSpellingLoc - Given a SourceLocation object, return the
952/// spelling location referenced by the ID. This is the first level down
953/// towards the place where the characters that make up the lexed token can be
954/// found. This should not generally be used by clients.
955SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
956 if (Loc.isFileID()) return Loc;
957 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000958 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000959 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner8ad52d52009-02-17 08:04:48 +0000960}
961
Chandler Carruth64ee7822011-07-26 05:17:23 +0000962/// getImmediateExpansionRange - Loc is required to be an expansion location.
963/// Return the start/end of the expansion information.
Richard Smithb5f81712018-04-30 05:25:48 +0000964CharSourceRange
Chandler Carruthca757582011-07-25 20:52:21 +0000965SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000966 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000967 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000968 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000969}
970
George Karpenkov441e8fd2018-02-09 23:30:07 +0000971SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
972 while (isMacroArgExpansion(Loc))
973 Loc = getImmediateSpellingLoc(Loc);
974 return Loc;
975}
976
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000977/// getExpansionRange - Given a SourceLocation object, return the range of
978/// tokens covered by the expansion in the ultimate file.
Richard Smithb5f81712018-04-30 05:25:48 +0000979CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
980 if (Loc.isFileID())
981 return CharSourceRange(SourceRange(Loc, Loc), true);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Richard Smithb5f81712018-04-30 05:25:48 +0000983 CharSourceRange Res = getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chandler Carruth64ee7822011-07-26 05:17:23 +0000985 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000986 // points.
Richard Smithb5f81712018-04-30 05:25:48 +0000987 while (!Res.getBegin().isFileID())
988 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
989 while (!Res.getEnd().isFileID()) {
990 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
991 Res.setEnd(EndRange.getEnd());
992 Res.setTokenRange(EndRange.isTokenRange());
993 }
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000994 return Res;
995}
996
Richard Trieuc3096242015-09-24 01:21:01 +0000997bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
998 SourceLocation *StartLoc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +0000999 if (!Loc.isMacroID()) return false;
1000
1001 FileID FID = getFileID(Loc);
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001002 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Richard Trieuc3096242015-09-24 01:21:01 +00001003 if (!Expansion.isMacroArgExpansion()) return false;
1004
1005 if (StartLoc)
1006 *StartLoc = Expansion.getExpansionLocStart();
1007 return true;
Chandler Carruth402bb382011-07-07 23:56:36 +00001008}
Chris Lattner9dc9c202009-02-15 20:52:18 +00001009
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +00001010bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1011 if (!Loc.isMacroID()) return false;
1012
1013 FileID FID = getFileID(Loc);
1014 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1015 return Expansion.isMacroBodyExpansion();
1016}
1017
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +00001018bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1019 SourceLocation *MacroBegin) const {
1020 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1021
1022 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1023 if (DecompLoc.second > 0)
1024 return false; // Does not point at the start of expansion range.
1025
1026 bool Invalid = false;
1027 const SrcMgr::ExpansionInfo &ExpInfo =
1028 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1029 if (Invalid)
1030 return false;
1031 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1032
1033 if (ExpInfo.isMacroArgExpansion()) {
1034 // For macro argument expansions, check if the previous FileID is part of
1035 // the same argument expansion, in which case this Loc is not at the
1036 // beginning of the expansion.
1037 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1038 if (!PrevFID.isInvalid()) {
1039 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1040 if (Invalid)
1041 return false;
1042 if (PrevEntry.isExpansion() &&
1043 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1044 return false;
1045 }
1046 }
1047
1048 if (MacroBegin)
1049 *MacroBegin = ExpLoc;
1050 return true;
1051}
1052
1053bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1054 SourceLocation *MacroEnd) const {
1055 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1056
1057 FileID FID = getFileID(Loc);
1058 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1059 if (isInFileID(NextLoc, FID))
1060 return false; // Does not point at the end of expansion range.
1061
1062 bool Invalid = false;
1063 const SrcMgr::ExpansionInfo &ExpInfo =
1064 getSLocEntry(FID, &Invalid).getExpansion();
1065 if (Invalid)
1066 return false;
1067
1068 if (ExpInfo.isMacroArgExpansion()) {
1069 // For macro argument expansions, check if the next FileID is part of the
1070 // same argument expansion, in which case this Loc is not at the end of the
1071 // expansion.
1072 FileID NextFID = getNextFileID(FID);
1073 if (!NextFID.isInvalid()) {
1074 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1075 if (Invalid)
1076 return false;
1077 if (NextEntry.isExpansion() &&
1078 NextEntry.getExpansion().getExpansionLocStart() ==
1079 ExpInfo.getExpansionLocStart())
1080 return false;
1081 }
1082 }
1083
1084 if (MacroEnd)
1085 *MacroEnd = ExpInfo.getExpansionLocEnd();
1086 return true;
1087}
1088
Chris Lattner4fa23622009-01-26 00:43:02 +00001089//===----------------------------------------------------------------------===//
1090// Queries about the code at a SourceLocation.
1091//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +00001092
Chris Lattnerd01e2912006-06-18 16:22:51 +00001093/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +00001094/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001095const char *SourceManager::getCharacterData(SourceLocation SL,
1096 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +00001097 // Note that this is a hot function in the getSpelling() path, which is
1098 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +00001099 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +00001100
Ted Kremenek12c2af42009-01-06 01:55:26 +00001101 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001102 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001103 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1104 if (CharDataInvalid || !Entry.isFile()) {
1105 if (Invalid)
1106 *Invalid = true;
1107
1108 return "<<<<INVALID BUFFER>>>>";
1109 }
David Blaikie66cc07b2014-06-27 17:40:03 +00001110 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1111 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001112 if (Invalid)
1113 *Invalid = CharDataInvalid;
1114 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001115}
1116
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001117/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001118/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001119unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1120 bool *Invalid) const {
1121 bool MyInvalid = false;
David Blaikie66cc07b2014-06-27 17:40:03 +00001122 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001123 if (Invalid)
1124 *Invalid = MyInvalid;
1125
1126 if (MyInvalid)
1127 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001129 // It is okay to request a position just past the end of the buffer.
1130 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001131 if (Invalid)
Jordan Rose8d63d5b2012-06-19 03:09:38 +00001132 *Invalid = true;
Argyrios Kyrtzidis6c8d29f2011-12-10 00:30:38 +00001133 return 1;
1134 }
1135
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001136 const char *Buf = MemBuf->getBufferStart();
Craig Topper5e79ee02012-10-19 04:40:38 +00001137 // See if we just calculated the line number for this FilePos and can use
1138 // that to lookup the start of the line instead of searching for it.
1139 if (LastLineNoFileIDQuery == FID &&
Craig Topperf1186c52014-05-08 06:41:40 +00001140 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperf3b839b2012-12-16 05:58:32 +00001141 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topper5e79ee02012-10-19 04:40:38 +00001142 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1143 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1144 unsigned LineEnd = SourceLineCache[LastLineNoResult];
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001145 if (FilePos >= LineStart && FilePos < LineEnd) {
1146 // LineEnd is the LineStart of the next line.
1147 // A line ends with separator LF or CR+LF on Windows.
1148 // FilePos might point to the last separator,
1149 // but we need a column number at most 1 + the last column.
1150 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1151 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1152 --FilePos;
1153 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001154 return FilePos - LineStart + 1;
Chih-Hung Hsieha0b99e42017-04-06 18:36:50 +00001155 }
Craig Topper5e79ee02012-10-19 04:40:38 +00001156 }
1157
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 unsigned LineStart = FilePos;
1159 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1160 --LineStart;
1161 return FilePos-LineStart+1;
1162}
1163
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001164// isInvalid - Return the result of calling loc.isInvalid(), and
1165// if Invalid is not null, set its value to same.
Richard Smith41e66292016-04-28 18:26:32 +00001166template<typename LocType>
1167static bool isInvalid(LocType Loc, bool *Invalid) {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001168 bool MyInvalid = Loc.isInvalid();
1169 if (Invalid)
1170 *Invalid = MyInvalid;
1171 return MyInvalid;
1172}
1173
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001174unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1175 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001176 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +00001177 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001178 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001179}
1180
Chandler Carruth42f35f92011-07-25 20:57:57 +00001181unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1182 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001183 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001184 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001185 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +00001186}
1187
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001188unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1189 bool *Invalid) const {
Richard Smith41e66292016-04-28 18:26:32 +00001190 PresumedLoc PLoc = getPresumedLoc(Loc);
1191 if (isInvalid(PLoc, Invalid)) return 0;
1192 return PLoc.getColumn();
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001193}
1194
Benjamin Kramer543036a2012-04-06 20:49:55 +00001195#ifdef __SSE2__
1196#include <emmintrin.h>
1197#endif
1198
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001199static LLVM_ATTRIBUTE_NOINLINE void
David Blaikie9c902b52011-09-25 23:23:43 +00001200ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001201 llvm::BumpPtrAllocator &Alloc,
1202 const SourceManager &SM, bool &Invalid);
David Blaikie9c902b52011-09-25 23:23:43 +00001203static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001204 llvm::BumpPtrAllocator &Alloc,
1205 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +00001206 // Note that calling 'getBuffer()' may lazily page in the file.
David Blaikie66cc07b2014-06-27 17:40:03 +00001207 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001208 if (Invalid)
1209 return;
Mike Stump11289f42009-09-09 15:08:12 +00001210
Chris Lattner8996fff2007-07-24 05:57:19 +00001211 // Find the file offsets of all of the *physical* source lines. This does
1212 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001214
Chris Lattner8996fff2007-07-24 05:57:19 +00001215 // Line #1 starts at char 0.
1216 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner8996fff2007-07-24 05:57:19 +00001218 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1219 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1220 unsigned Offs = 0;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001221 while (true) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001222 // Skip over the contents of the line.
Chris Lattner8996fff2007-07-24 05:57:19 +00001223 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001224
1225#ifdef __SSE2__
1226 // Try to skip to the next newline using SSE instructions. This is very
1227 // performance sensitive for programs with lots of diagnostics and in -E
1228 // mode.
1229 __m128i CRs = _mm_set1_epi8('\r');
1230 __m128i LFs = _mm_set1_epi8('\n');
1231
1232 // First fix up the alignment to 16 bytes.
1233 while (((uintptr_t)NextBuf & 0xF) != 0) {
1234 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1235 goto FoundSpecialChar;
1236 ++NextBuf;
1237 }
1238
1239 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1240 while (NextBuf+16 <= End) {
Roman Divackye6377112012-09-06 15:59:27 +00001241 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001242 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1243 _mm_cmpeq_epi8(Chunk, LFs));
1244 unsigned Mask = _mm_movemask_epi8(Cmp);
1245
1246 // If we found a newline, adjust the pointer and jump to the handling code.
1247 if (Mask != 0) {
Michael J. Spencer8c398402013-05-24 21:42:04 +00001248 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramer543036a2012-04-06 20:49:55 +00001249 goto FoundSpecialChar;
1250 }
1251 NextBuf += 16;
1252 }
1253#endif
1254
Chris Lattner8996fff2007-07-24 05:57:19 +00001255 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1256 ++NextBuf;
Benjamin Kramer543036a2012-04-06 20:49:55 +00001257
1258#ifdef __SSE2__
1259FoundSpecialChar:
1260#endif
Chris Lattner8996fff2007-07-24 05:57:19 +00001261 Offs += NextBuf-Buf;
1262 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +00001263
Chris Lattner8996fff2007-07-24 05:57:19 +00001264 if (Buf[0] == '\n' || Buf[0] == '\r') {
1265 // If this is \n\r or \r\n, skip both characters.
Richard Trieucc3949d2016-02-18 22:34:54 +00001266 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1267 ++Offs;
1268 ++Buf;
1269 }
1270 ++Offs;
1271 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001272 LineOffsets.push_back(Offs);
1273 } else {
1274 // Otherwise, this is a null. If end of file, exit.
1275 if (Buf == End) break;
1276 // Otherwise, skip the null.
Richard Trieucc3949d2016-02-18 22:34:54 +00001277 ++Offs;
1278 ++Buf;
Chris Lattner8996fff2007-07-24 05:57:19 +00001279 }
1280 }
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner8996fff2007-07-24 05:57:19 +00001282 // Copy the offsets into the FileInfo structure.
1283 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001284 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001285 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1286}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001287
Chris Lattner53e384f2009-01-16 07:00:02 +00001288/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001289/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001290/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001291/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001292unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1293 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001294 if (FID.isInvalid()) {
1295 if (Invalid)
1296 *Invalid = true;
1297 return 1;
1298 }
1299
Chris Lattnerd32480d2009-01-17 06:22:33 +00001300 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001301 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001302 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001303 else {
1304 bool MyInvalid = false;
1305 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1306 if (MyInvalid || !Entry.isFile()) {
1307 if (Invalid)
1308 *Invalid = true;
1309 return 1;
1310 }
1311
1312 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1313 }
1314
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001316 /// SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001317 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001318 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001319 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001320 if (Invalid)
1321 *Invalid = MyInvalid;
1322 if (MyInvalid)
1323 return 1;
1324 } else if (Invalid)
1325 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001326
1327 // Okay, we know we have a line number table. Do a binary search to find the
1328 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001329 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001330 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001331 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattner88ea93e2009-02-04 01:06:56 +00001333 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001334
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001335 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001336 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001337 //
1338 // If it is worth being optimized, then in my opinion it could be more
1339 // performant, simpler, and more obviously correct by just "galloping" outward
1340 // from the queried file position. In fact, this could be incorporated into a
1341 // generic algorithm such as lower_bound_with_hint.
1342 //
1343 // If someone gives me a test case where this matters, and I will do it! - DWD
1344
Chris Lattner8996fff2007-07-24 05:57:19 +00001345 // If the previous query was to the same file, we know both the file pos from
1346 // that query and the line number returned. This allows us to narrow the
1347 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001348 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001349 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001350 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001351 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001352
Chris Lattner8996fff2007-07-24 05:57:19 +00001353 // The query is likely to be nearby the previous one. Here we check to
1354 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1355 // where big comment blocks and vertical whitespace eat up lines but
1356 // contribute no tokens.
1357 if (SourceLineCache+5 < SourceLineCacheEnd) {
1358 if (SourceLineCache[5] > QueriedFilePos)
1359 SourceLineCacheEnd = SourceLineCache+5;
1360 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1361 if (SourceLineCache[10] > QueriedFilePos)
1362 SourceLineCacheEnd = SourceLineCache+10;
1363 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1364 if (SourceLineCache[20] > QueriedFilePos)
1365 SourceLineCacheEnd = SourceLineCache+20;
1366 }
1367 }
1368 }
1369 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001370 if (LastLineNoResult < Content->NumLines)
1371 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001372 }
1373 }
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner830a77f2007-07-24 06:43:46 +00001375 unsigned *Pos
1376 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001377 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattner88ea93e2009-02-04 01:06:56 +00001379 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001380 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001381 LastLineNoFilePos = QueriedFilePos;
1382 LastLineNoResult = LineNo;
1383 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001384}
1385
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001386unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1387 bool *Invalid) const {
1388 if (isInvalid(Loc, Invalid)) return 0;
1389 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1390 return getLineNumber(LocInfo.first, LocInfo.second);
1391}
Chandler Carruthd48db212011-07-25 21:09:52 +00001392unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1393 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001394 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001395 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001396 return getLineNumber(LocInfo.first, LocInfo.second);
1397}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001398unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001399 bool *Invalid) const {
Richard Smith9c527672016-04-28 19:54:51 +00001400 PresumedLoc PLoc = getPresumedLoc(Loc);
1401 if (isInvalid(PLoc, Invalid)) return 0;
1402 return PLoc.getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001403}
1404
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001405/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001406/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001407/// header, or an "implicit extern C" system header.
1408///
1409/// This state can be modified with flags on GNU linemarker directives like:
1410/// # 4 "foo.h" 3
1411/// which changes all source locations in the current file after that to be
1412/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001413SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001414SourceManager::getFileCharacteristic(SourceLocation Loc) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001415 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001416 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001417 bool Invalid = false;
1418 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1419 if (Invalid || !SEntry.isFile())
1420 return C_User;
1421
1422 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001423
1424 // If there are no #line directives in this file, just return the whole-file
1425 // state.
1426 if (!FI.hasLineDirectives())
1427 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001428
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001429 assert(LineTable && "Can't have linetable entries without a LineTable!");
1430 // See if there is a #line directive before the location.
1431 const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001432 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001433
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001434 // If this is before the first line marker, use the file characteristic.
1435 if (!Entry)
1436 return FI.getFileCharacteristic();
1437
1438 return Entry->FileKind;
1439}
1440
Chris Lattnera6f037c2009-02-17 08:39:06 +00001441/// Return the filename or buffer identifier of the buffer the location is in.
James Dennett87a2acf2012-06-17 03:22:59 +00001442/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnera6f037c2009-02-17 08:39:06 +00001443/// for normal clients.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001444StringRef SourceManager::getBufferName(SourceLocation Loc,
1445 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001446 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001448 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001449}
1450
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001451/// getPresumedLoc - This method returns the "presumed" location of a
James Dennett87a2acf2012-06-17 03:22:59 +00001452/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001453/// or GNU line marker directives. This provides a view on the data that a
1454/// user should see in diagnostics, for example.
1455///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001456/// Note that a presumed location is always given as the expansion point of an
1457/// expansion location, not at the spelling location.
Richard Smith0b50cb72012-11-14 23:55:25 +00001458PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1459 bool UseLineDirectives) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001460 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chandler Carruth64ee7822011-07-26 05:17:23 +00001462 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001463 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Douglas Gregor49f754f2011-04-20 00:21:03 +00001465 bool Invalid = false;
1466 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1467 if (Invalid || !Entry.isFile())
1468 return PresumedLoc();
1469
1470 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001471 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattnerd4293922009-02-04 01:55:42 +00001473 // To get the source name, first consult the FileEntry (if one exists)
1474 // before the MemBuffer as this will avoid unnecessarily paging in the
1475 // MemBuffer.
Mehdi Amini99d1b292016-10-01 16:38:28 +00001476 StringRef Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001477 if (C->OrigEntry)
1478 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001479 else
1480 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001481
Douglas Gregor75f26d62010-11-02 00:39:22 +00001482 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1483 if (Invalid)
1484 return PresumedLoc();
1485 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1486 if (Invalid)
1487 return PresumedLoc();
1488
Chris Lattnerd4293922009-02-04 01:55:42 +00001489 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001490
Chris Lattnerd4293922009-02-04 01:55:42 +00001491 // If we have #line directives in this file, update and overwrite the physical
1492 // location info if appropriate.
Richard Smith0b50cb72012-11-14 23:55:25 +00001493 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattnerd4293922009-02-04 01:55:42 +00001494 assert(LineTable && "Can't have linetable entries without a LineTable!");
1495 // See if there is a #line directive before this. If so, get it.
1496 if (const LineEntry *Entry =
Douglas Gregor02c2dbf2012-06-08 16:40:28 +00001497 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001498 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001499 if (Entry->FilenameID != -1)
1500 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001501
1502 // Use the line number specified by the LineEntry. This line number may
1503 // be multiple lines down from the line entry. Add the difference in
1504 // physical line numbers from the query point and the line marker to the
1505 // total.
1506 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1507 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Chris Lattner20c50ba2009-02-04 02:15:40 +00001509 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001510
Chris Lattner1c967782009-02-04 06:25:26 +00001511 // Handle virtual #include manipulation.
1512 if (Entry->IncludeOffset) {
1513 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001514 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner1c967782009-02-04 06:25:26 +00001515 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001516 }
1517 }
1518
Mehdi Amini99d1b292016-10-01 16:38:28 +00001519 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001520}
1521
Benjamin Kramere7800df2013-09-27 17:12:50 +00001522/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1523/// in the main file.
1524///
1525/// This computes the "presumed" location for a SourceLocation, then checks
1526/// whether it came from a file other than the main file. This is different
1527/// from isWrittenInMainFile() because it takes line marker directives into
1528/// account.
1529bool SourceManager::isInMainFile(SourceLocation Loc) const {
1530 if (Loc.isInvalid()) return false;
1531
1532 // Presumed locations are always for expansion points.
1533 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1534
1535 bool Invalid = false;
1536 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1537 if (Invalid || !Entry.isFile())
1538 return false;
1539
1540 const SrcMgr::FileInfo &FI = Entry.getFile();
1541
1542 // Check if there is a line directive for this location.
1543 if (FI.hasLineDirectives())
1544 if (const LineEntry *Entry =
1545 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1546 if (Entry->IncludeOffset)
1547 return false;
1548
1549 return FI.getIncludeLoc().isInvalid();
1550}
1551
James Dennettaa61cbb2013-11-24 01:47:49 +00001552/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001553unsigned SourceManager::getFileIDSize(FileID FID) const {
1554 bool Invalid = false;
1555 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1556 if (Invalid)
1557 return 0;
1558
1559 int ID = FID.ID;
1560 unsigned NextOffset;
1561 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1562 NextOffset = getNextLocalOffset();
1563 else if (ID+1 == -1)
1564 NextOffset = MaxLoadedOffset;
1565 else
1566 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1567
1568 return NextOffset - Entry.getOffset() - 1;
1569}
1570
Chris Lattner4fa23622009-01-26 00:43:02 +00001571//===----------------------------------------------------------------------===//
1572// Other miscellaneous methods.
1573//===----------------------------------------------------------------------===//
1574
Douglas Gregore6642762011-02-03 17:17:35 +00001575/// \brief Retrieve the inode for the given file entry, if possible.
1576///
1577/// This routine involves a system call, and therefore should only be used
1578/// in non-performance-critical code.
Rafael Espindola073ff102013-07-29 21:26:52 +00001579static Optional<llvm::sys::fs::UniqueID>
1580getActualFileUID(const FileEntry *File) {
Douglas Gregore6642762011-02-03 17:17:35 +00001581 if (!File)
David Blaikie7a30dc52013-02-21 01:47:18 +00001582 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001583
Rafael Espindola073ff102013-07-29 21:26:52 +00001584 llvm::sys::fs::UniqueID ID;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001585 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie7a30dc52013-02-21 01:47:18 +00001586 return None;
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001587
1588 return ID;
Douglas Gregore6642762011-02-03 17:17:35 +00001589}
1590
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001591/// \brief Get the source location for the given file:line:col triplet.
1592///
1593/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001594/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001595SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001596 unsigned Line,
1597 unsigned Col) const {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001598 assert(SourceFile && "Null source file!");
1599 assert(Line && Col && "Line and column should start from 1!");
1600
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001601 FileID FirstFID = translateFile(SourceFile);
1602 return translateLineCol(FirstFID, Line, Col);
1603}
1604
1605/// \brief Get the FileID for the given file.
1606///
1607/// If the source file is included multiple times, the FileID will be the
1608/// first inclusion.
1609FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1610 assert(SourceFile && "Null source file!");
1611
Douglas Gregore6642762011-02-03 17:17:35 +00001612 // Find the first file ID that corresponds to the given file.
1613 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregore6642762011-02-03 17:17:35 +00001615 // First, check the main file ID, since it is common to look for a
1616 // location in the main file.
Rafael Espindola073ff102013-07-29 21:26:52 +00001617 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikie05785d12013-02-20 22:23:23 +00001618 Optional<StringRef> SourceFileName;
Yaron Keren8b563662015-10-03 10:46:20 +00001619 if (MainFileID.isValid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001620 bool Invalid = false;
1621 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1622 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001623 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001624
Douglas Gregore6642762011-02-03 17:17:35 +00001625 if (MainSLoc.isFile()) {
1626 const ContentCache *MainContentCache
1627 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001628 if (!MainContentCache) {
1629 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001630 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001631 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001632 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001633 // Fall back: check whether we have the same base name and inode
1634 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001635 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001636 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1637 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001638 SourceFileUID = getActualFileUID(SourceFile);
1639 if (SourceFileUID) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001640 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1641 getActualFileUID(MainFile)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001642 if (*SourceFileUID == *MainFileUID) {
Douglas Gregord766be62011-02-16 19:09:24 +00001643 FirstFID = MainFileID;
1644 SourceFile = MainFile;
1645 }
1646 }
Douglas Gregore6642762011-02-03 17:17:35 +00001647 }
1648 }
1649 }
1650 }
1651 }
1652
1653 if (FirstFID.isInvalid()) {
1654 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001655 // through all of the local source locations.
1656 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001657 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001658 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001659 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001660 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001661
Douglas Gregore6642762011-02-03 17:17:35 +00001662 if (SLoc.isFile() &&
1663 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001664 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001665 FirstFID = FileID::get(I);
1666 break;
1667 }
1668 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001669 // If that still didn't help, try the modules.
1670 if (FirstFID.isInvalid()) {
1671 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1672 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1673 if (SLoc.isFile() &&
1674 SLoc.getFile().getContentCache() &&
1675 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1676 FirstFID = FileID::get(-int(I) - 2);
1677 break;
1678 }
1679 }
1680 }
Douglas Gregore6642762011-02-03 17:17:35 +00001681 }
1682
1683 // If we haven't found what we want yet, try again, but this time stat()
1684 // each of the files in case the files have changed since we originally
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001685 // parsed the file.
Douglas Gregore6642762011-02-03 17:17:35 +00001686 if (FirstFID.isInvalid() &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001687 (SourceFileName ||
Douglas Gregore6642762011-02-03 17:17:35 +00001688 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001689 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001690 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001691 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1692 FileID IFileID;
1693 IFileID.ID = I;
1694 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001695 if (Invalid)
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001696 return FileID();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001697
Douglas Gregore6642762011-02-03 17:17:35 +00001698 if (SLoc.isFile()) {
1699 const ContentCache *FileContentCache
1700 = SLoc.getFile().getContentCache();
Craig Topperf1186c52014-05-08 06:41:40 +00001701 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1702 : nullptr;
Douglas Gregore6642762011-02-03 17:17:35 +00001703 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001704 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola073ff102013-07-29 21:26:52 +00001705 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1706 getActualFileUID(Entry)) {
Rafael Espindola74ca78e2013-07-29 18:43:40 +00001707 if (*SourceFileUID == *EntryUID) {
Douglas Gregor6a5be932011-02-11 18:08:15 +00001708 FirstFID = FileID::get(I);
1709 SourceFile = Entry;
1710 break;
1711 }
1712 }
Douglas Gregore6642762011-02-03 17:17:35 +00001713 }
1714 }
1715 }
1716 }
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001717
Ted Kremenekbd1d7fa2012-10-12 22:56:33 +00001718 (void) SourceFile;
Argyrios Kyrtzidis04a6e5f2011-09-27 17:22:25 +00001719 return FirstFID;
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001720}
1721
1722/// \brief Get the source location in \arg FID for the given line:col.
1723/// Returns null location if \arg FID is not a file SLocEntry.
1724SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001725 unsigned Line,
1726 unsigned Col) const {
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001727 // Lines are used as a one-based index into a zero-based array. This assert
1728 // checks for possible buffer underruns.
Gabor Horvathfe2c0ff2015-12-01 09:00:41 +00001729 assert(Line && Col && "Line and column should start from 1!");
Aaron Ballmanef1cf832013-11-18 18:29:00 +00001730
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001731 if (FID.isInvalid())
1732 return SourceLocation();
1733
1734 bool Invalid = false;
1735 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1736 if (Invalid)
1737 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001738
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001739 if (!Entry.isFile())
Douglas Gregore6642762011-02-03 17:17:35 +00001740 return SourceLocation();
1741
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001742 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1743
Douglas Gregore6642762011-02-03 17:17:35 +00001744 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001745 return FileLoc;
Douglas Gregore6642762011-02-03 17:17:35 +00001746
1747 ContentCache *Content
Argyrios Kyrtzidis532c5192011-09-19 20:40:29 +00001748 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregore6642762011-02-03 17:17:35 +00001749 if (!Content)
1750 return SourceLocation();
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001751
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001752 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001753 // SourceLineCache for it on demand.
Craig Topperf1186c52014-05-08 06:41:40 +00001754 if (!Content->SourceLineCache) {
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001755 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001756 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001757 if (MyInvalid)
1758 return SourceLocation();
1759 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001760
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001761 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001762 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001763 if (Size > 0)
1764 --Size;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001765 return FileLoc.getLocWithOffset(Size);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001766 }
1767
David Blaikie66cc07b2014-06-27 17:40:03 +00001768 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001769 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith2a8bc152011-12-19 08:51:05 +00001770 const char *Buf = Buffer->getBufferStart() + FilePos;
1771 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis7c2b28a2011-09-20 22:14:54 +00001772 if (BufLength == 0)
1773 return FileLoc.getLocWithOffset(FilePos);
1774
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001775 unsigned i = 0;
1776
1777 // Check that the given column is valid.
1778 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1779 ++i;
Alexander Kornienko6d8cf832013-07-29 22:26:10 +00001780 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001781}
1782
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001783/// \brief Compute a map of macro argument chunks to their expanded source
1784/// location. Chunks that are not part of a macro argument will map to an
1785/// invalid source location. e.g. if a file contains one macro argument at
1786/// offset 100 with length 10, this is how the map will be formed:
1787/// 0 -> SourceLocation()
1788/// 100 -> Expanded macro arg location
1789/// 110 -> SourceLocation()
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001790void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001791 FileID FID) const {
Yaron Keren8b563662015-10-03 10:46:20 +00001792 assert(FID.isValid());
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001793
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001794 // Initially no macro argument chunk is present.
1795 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1796
1797 int ID = FID.ID;
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001798 while (true) {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001799 ++ID;
1800 // Stop if there are no more FileIDs to check.
1801 if (ID > 0) {
1802 if (unsigned(ID) >= local_sloc_entry_size())
1803 return;
1804 } else if (ID == -1) {
1805 return;
1806 }
1807
Argyrios Kyrtzidisfe683022013-06-07 17:57:59 +00001808 bool Invalid = false;
1809 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1810 if (Invalid)
1811 return;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001812 if (Entry.isFile()) {
1813 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1814 if (IncludeLoc.isInvalid())
1815 continue;
1816 if (!isInFileID(IncludeLoc, FID))
1817 return; // No more files/macros that may be "contained" in this file.
1818
1819 // Skip the files/macros of the #include'd file, we only care about macros
1820 // that lexed macro arguments from our file.
1821 if (Entry.getFile().NumCreatedFIDs)
1822 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1823 continue;
1824 }
1825
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001826 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1827
1828 if (ExpInfo.getExpansionLocStart().isFileID()) {
1829 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1830 return; // No more files/macros that may be "contained" in this file.
1831 }
1832
1833 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001834 continue;
Argyrios Kyrtzidise841c902011-12-21 16:56:35 +00001835
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001836 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1837 ExpInfo.getSpellingLoc(),
1838 SourceLocation::getMacroLoc(Entry.getOffset()),
1839 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001840 }
1841}
1842
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001843void SourceManager::associateFileChunkWithMacroArgExp(
1844 MacroArgsMap &MacroArgsCache,
1845 FileID FID,
1846 SourceLocation SpellLoc,
1847 SourceLocation ExpansionLoc,
1848 unsigned ExpansionLength) const {
1849 if (!SpellLoc.isFileID()) {
1850 unsigned SpellBeginOffs = SpellLoc.getOffset();
1851 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1852
1853 // The spelling range for this macro argument expansion can span multiple
1854 // consecutive FileID entries. Go through each entry contained in the
1855 // spelling range and if one is itself a macro argument expansion, recurse
1856 // and associate the file chunk that it represents.
1857
1858 FileID SpellFID; // Current FileID in the spelling range.
1859 unsigned SpellRelativeOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001860 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001861 while (true) {
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001862 const SLocEntry &Entry = getSLocEntry(SpellFID);
1863 unsigned SpellFIDBeginOffs = Entry.getOffset();
1864 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1865 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1866 const ExpansionInfo &Info = Entry.getExpansion();
1867 if (Info.isMacroArgExpansion()) {
1868 unsigned CurrSpellLength;
1869 if (SpellFIDEndOffs < SpellEndOffs)
1870 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1871 else
1872 CurrSpellLength = ExpansionLength;
1873 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1874 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1875 ExpansionLoc, CurrSpellLength);
1876 }
1877
1878 if (SpellFIDEndOffs >= SpellEndOffs)
1879 return; // we covered all FileID entries in the spelling range.
1880
1881 // Move to the next FileID entry in the spelling range.
1882 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1883 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1884 ExpansionLength -= advance;
1885 ++SpellFID.ID;
1886 SpellRelativeOffs = 0;
1887 }
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001888 }
1889
1890 assert(SpellLoc.isFileID());
1891
1892 unsigned BeginOffs;
1893 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1894 return;
1895
1896 unsigned EndOffs = BeginOffs + ExpansionLength;
1897
1898 // Add a new chunk for this macro argument. A previous macro argument chunk
1899 // may have been lexed again, so e.g. if the map is
1900 // 0 -> SourceLocation()
1901 // 100 -> Expanded loc #1
1902 // 110 -> SourceLocation()
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001903 // and we found a new macro FileID that lexed from offset 105 with length 3,
Argyrios Kyrtzidis73ccdb92012-10-20 00:51:32 +00001904 // the new map will be:
1905 // 0 -> SourceLocation()
1906 // 100 -> Expanded loc #1
1907 // 105 -> Expanded loc #2
1908 // 108 -> Expanded loc #1
1909 // 110 -> SourceLocation()
1910 //
1911 // Since re-lexed macro chunks will always be the same size or less of
1912 // previous chunks, we only need to find where the ending of the new macro
1913 // chunk is mapped to and update the map with new begin/end mappings.
1914
1915 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1916 --I;
1917 SourceLocation EndOffsMappedLoc = I->second;
1918 MacroArgsCache[BeginOffs] = ExpansionLoc;
1919 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1920}
1921
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001922/// \brief If \arg Loc points inside a function macro argument, the returned
1923/// location will be the macro location in which the argument was expanded.
1924/// If a macro argument is used multiple times, the expanded location will
1925/// be at the first expansion of the argument.
1926/// e.g.
1927/// MY_MACRO(foo);
1928/// ^
1929/// Passing a file location pointing at 'foo', will yield a macro location
1930/// where 'foo' was expanded into.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001931SourceLocation
1932SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001933 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001934 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001935
1936 FileID FID;
1937 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001938 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001939 if (FID.isInvalid())
1940 return Loc;
1941
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001942 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1943 if (!MacroArgsCache) {
1944 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
Vedant Kumarecc31442016-10-18 18:19:02 +00001945 computeMacroArgsCache(*MacroArgsCache, FID);
Vedant Kumard2c6a6d2016-10-18 00:23:27 +00001946 }
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001947
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00001948 assert(!MacroArgsCache->empty());
1949 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001950 --I;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001951
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001952 unsigned MacroArgBeginOffs = I->first;
1953 SourceLocation MacroArgExpandedLoc = I->second;
1954 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001955 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001956
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001957 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001958}
1959
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001960std::pair<FileID, unsigned>
1961SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001962 if (FID.isInvalid())
1963 return std::make_pair(FileID(), 0);
1964
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001965 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1966
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00001967 using DecompTy = std::pair<FileID, unsigned>;
1968 using MapTy = llvm::DenseMap<FileID, DecompTy>;
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001969 std::pair<MapTy::iterator, bool>
1970 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1971 DecompTy &DecompLoc = InsertOp.first->second;
1972 if (!InsertOp.second)
1973 return DecompLoc; // already in map.
1974
1975 SourceLocation UpperLoc;
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00001976 bool Invalid = false;
1977 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1978 if (!Invalid) {
1979 if (Entry.isExpansion())
1980 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1981 else
1982 UpperLoc = Entry.getFile().getIncludeLoc();
1983 }
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001984
1985 if (UpperLoc.isValid())
1986 DecompLoc = getDecomposedLoc(UpperLoc);
1987
1988 return DecompLoc;
1989}
1990
Chandler Carruth64ee7822011-07-26 05:17:23 +00001991/// Given a decomposed source location, move it up the include/expansion stack
1992/// to the parent source location. If this is possible, return the decomposed
1993/// version of the parent in Loc and return false. If Loc is the top-level
1994/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001995static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1996 const SourceManager &SM) {
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00001997 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1998 if (UpperLoc.first.isInvalid())
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001999 return true; // We reached the top.
Argyrios Kyrtzidis37613a92013-04-13 01:03:57 +00002000
2001 Loc = UpperLoc;
Chris Lattnera99fa1a2010-05-07 20:35:24 +00002002 return false;
2003}
Ted Kremenek08037042013-02-27 00:00:26 +00002004
2005/// Return the cache entry for comparing the given file IDs
2006/// for isBeforeInTranslationUnit.
2007InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2008 FileID RFID) const {
2009 // This is a magic number for limiting the cache size. It was experimentally
2010 // derived from a small Objective-C project (where the cache filled
2011 // out to ~250 items). We can make it larger if necessary.
2012 enum { MagicCacheSize = 300 };
2013 IsBeforeInTUCacheKey Key(LFID, RFID);
2014
2015 // If the cache size isn't too large, do a lookup and if necessary default
2016 // construct an entry. We can then return it to the caller for direct
2017 // use. When they update the value, the cache will get automatically
2018 // updated as well.
2019 if (IBTUCache.size() < MagicCacheSize)
2020 return IBTUCache[Key];
2021
2022 // Otherwise, do a lookup that will not construct a new value.
2023 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2024 if (I != IBTUCache.end())
2025 return I->second;
2026
2027 // Fall back to the overflow value.
2028 return IBTUCacheOverflow;
2029}
Chris Lattnera99fa1a2010-05-07 20:35:24 +00002030
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002031/// \brief Determines the order of 2 source locations in the translation unit.
2032///
2033/// \returns true if LHS source location comes before RHS, false otherwise.
2034bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2035 SourceLocation RHS) const {
2036 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2037 if (LHS == RHS)
2038 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002039
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002040 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2041 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002042
Argyrios Kyrtzidis5fd822c2013-05-24 23:47:43 +00002043 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2044 // is a serialized one referring to a file that was removed after we loaded
2045 // the PCH.
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002046 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidisd6111d32013-05-25 01:03:03 +00002047 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5dca8642013-05-24 22:24:04 +00002048
Gabor Horvath7848b382017-06-29 06:53:13 +00002049 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2050 if (InSameTU.first)
2051 return InSameTU.second;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002053 // If we arrived here, the location is either in a built-ins buffer or
2054 // associated with global inline asm. PR5662 and PR22576 are examples.
2055
Mehdi Amini99d1b292016-10-01 16:38:28 +00002056 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2057 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2058 bool LIsBuiltins = LB == "<built-in>";
2059 bool RIsBuiltins = RB == "<built-in>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002060 // Sort built-in before non-built-in.
2061 if (LIsBuiltins || RIsBuiltins) {
2062 if (LIsBuiltins != RIsBuiltins)
2063 return LIsBuiltins;
2064 // Both are in built-in buffers, but from different files. We just claim that
2065 // lower IDs come first.
2066 return LOffs.first < ROffs.first;
2067 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002068 bool LIsAsm = LB == "<inline asm>";
2069 bool RIsAsm = RB == "<inline asm>";
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002070 // Sort assembler after built-ins, but before the rest.
2071 if (LIsAsm || RIsAsm) {
2072 if (LIsAsm != RIsAsm)
2073 return RIsAsm;
2074 assert(LOffs.first == ROffs.first);
2075 return false;
2076 }
Mehdi Amini99d1b292016-10-01 16:38:28 +00002077 bool LIsScratch = LB == "<scratch space>";
2078 bool RIsScratch = RB == "<scratch space>";
Yury Gribov154e57f2016-01-28 09:28:18 +00002079 // Sort scratch after inline asm, but before the rest.
2080 if (LIsScratch || RIsScratch) {
2081 if (LIsScratch != RIsScratch)
2082 return LIsScratch;
2083 return LOffs.second < ROffs.second;
2084 }
Joerg Sonnenberger1d3b4312015-03-16 17:54:54 +00002085 llvm_unreachable("Unsortable locations found");
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00002086}
Chris Lattner4fa23622009-01-26 00:43:02 +00002087
Gabor Horvath7848b382017-06-29 06:53:13 +00002088std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2089 std::pair<FileID, unsigned> &LOffs,
2090 std::pair<FileID, unsigned> &ROffs) const {
2091 // If the source locations are in the same file, just compare offsets.
2092 if (LOffs.first == ROffs.first)
2093 return std::make_pair(true, LOffs.second < ROffs.second);
2094
2095 // If we are comparing a source location with multiple locations in the same
2096 // file, we get a big win by caching the result.
2097 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2098 getInBeforeInTUCache(LOffs.first, ROffs.first);
2099
2100 // If we are comparing a source location with multiple locations in the same
2101 // file, we get a big win by caching the result.
2102 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2103 return std::make_pair(
2104 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2105
2106 // Okay, we missed in the cache, start updating the cache for this query.
2107 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2108 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2109
2110 // We need to find the common ancestor. The only way of doing this is to
2111 // build the complete include chain for one and then walking up the chain
2112 // of the other looking for a match.
2113 // We use a map from FileID to Offset to store the chain. Easier than writing
2114 // a custom set hash info that only depends on the first part of a pair.
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00002115 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
Gabor Horvath7848b382017-06-29 06:53:13 +00002116 LocSet LChain;
2117 do {
2118 LChain.insert(LOffs);
2119 // We catch the case where LOffs is in a file included by ROffs and
2120 // quit early. The other way round unfortunately remains suboptimal.
2121 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2122 LocSet::iterator I;
2123 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2124 if (MoveUpIncludeHierarchy(ROffs, *this))
2125 break; // Met at topmost file.
2126 }
2127 if (I != LChain.end())
2128 LOffs = *I;
2129
2130 // If we exited because we found a nearest common ancestor, compare the
2131 // locations within the common file and cache them.
2132 if (LOffs.first == ROffs.first) {
2133 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2134 return std::make_pair(
2135 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2136 }
2137 // Clear the lookup cache, it depends on a common location.
2138 IsBeforeInTUCache.clear();
2139 return std::make_pair(false, false);
2140}
2141
Chris Lattner22eb9722006-06-18 05:43:12 +00002142void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002143 llvm::errs() << "\n*** Source Manager Stats:\n";
2144 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2145 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00002146 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002147 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00002148 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00002149 << NextLocalOffset << "B of Sloc address space used.\n";
2150 llvm::errs() << LoadedSLocEntryTable.size()
2151 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00002152 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00002153 << "B of Sloc address space used.\n";
2154
Chris Lattner22eb9722006-06-18 05:43:12 +00002155 unsigned NumLineNumsComputed = 0;
2156 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002157 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Craig Topperf1186c52014-05-08 06:41:40 +00002158 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattnerc8233df2009-02-03 07:30:45 +00002159 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00002160 }
Argyrios Kyrtzidis4bdd6aa2011-09-26 08:01:50 +00002161 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump11289f42009-09-09 15:08:12 +00002162
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002163 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002164 << NumLineNumsComputed << " files with line #'s computed, "
2165 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00002166 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2167 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00002168}
Douglas Gregor258ae542009-04-27 06:38:32 +00002169
Richard Smith03a06dd2015-08-13 00:45:11 +00002170LLVM_DUMP_METHOD void SourceManager::dump() const {
2171 llvm::raw_ostream &out = llvm::errs();
2172
2173 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2174 llvm::Optional<unsigned> NextStart) {
2175 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2176 << " <SourceLocation " << Entry.getOffset() << ":";
2177 if (NextStart)
2178 out << *NextStart << ">\n";
2179 else
2180 out << "???\?>\n";
2181 if (Entry.isFile()) {
2182 auto &FI = Entry.getFile();
2183 if (FI.NumCreatedFIDs)
2184 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2185 << ">\n";
2186 if (FI.getIncludeLoc().isValid())
2187 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2188 if (auto *CC = FI.getContentCache()) {
2189 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2190 << "\n";
2191 if (CC->BufferOverridden)
2192 out << " contents overridden\n";
2193 if (CC->ContentsEntry != CC->OrigEntry) {
2194 out << " contents from "
2195 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2196 << "\n";
2197 }
2198 }
2199 } else {
2200 auto &EI = Entry.getExpansion();
2201 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2202 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2203 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2204 << EI.getExpansionLocEnd().getOffset() << ">\n";
2205 }
2206 };
2207
2208 // Dump local SLocEntries.
2209 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2210 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2211 ID == NumIDs - 1 ? NextLocalOffset
2212 : LocalSLocEntryTable[ID + 1].getOffset());
2213 }
2214 // Dump loaded SLocEntries.
2215 llvm::Optional<unsigned> NextStart;
2216 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2217 int ID = -(int)Index - 2;
2218 if (SLocEntryLoaded[Index]) {
2219 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2220 NextStart = LoadedSLocEntryTable[Index].getOffset();
2221 } else {
2222 NextStart = None;
2223 }
2224 }
2225}
2226
Eugene Zelenko918e0ca2017-11-03 22:35:27 +00002227ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
Ted Kremenek8d587902011-04-28 20:36:42 +00002228
2229/// Return the amount of memory used by memory buffers, breaking down
2230/// by heap-backed versus mmap'ed memory.
2231SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2232 size_t malloc_bytes = 0;
2233 size_t mmap_bytes = 0;
2234
2235 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2236 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2237 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2238 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2239 mmap_bytes += sized_mapped;
2240 break;
2241 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2242 malloc_bytes += sized_mapped;
2243 break;
2244 }
2245
2246 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2247}
2248
Ted Kremenek120992a2011-07-26 23:46:06 +00002249size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002250 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00002251 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2252 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2253 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +00002254 + llvm::capacity_in_bytes(FileInfos);
2255
2256 if (OverriddenFilesInfo)
2257 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2258
2259 return size;
Ted Kremenek120992a2011-07-26 23:46:06 +00002260}