1e5dd7070Spatrick //===- SourceManager.cpp - Track and cache source files -------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file implements the SourceManager interface.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
14e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
15e5dd7070Spatrick #include "clang/Basic/FileManager.h"
16e5dd7070Spatrick #include "clang/Basic/LLVM.h"
17e5dd7070Spatrick #include "clang/Basic/SourceLocation.h"
18e5dd7070Spatrick #include "clang/Basic/SourceManagerInternals.h"
19e5dd7070Spatrick #include "llvm/ADT/DenseMap.h"
20*12c85518Srobert #include "llvm/ADT/MapVector.h"
21e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
22e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
23e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
24ec727ea7Spatrick #include "llvm/ADT/StringSwitch.h"
25e5dd7070Spatrick #include "llvm/Support/Allocator.h"
26e5dd7070Spatrick #include "llvm/Support/Capacity.h"
27e5dd7070Spatrick #include "llvm/Support/Compiler.h"
28a9ac8606Spatrick #include "llvm/Support/Endian.h"
29e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
30e5dd7070Spatrick #include "llvm/Support/FileSystem.h"
31e5dd7070Spatrick #include "llvm/Support/MathExtras.h"
32e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
33e5dd7070Spatrick #include "llvm/Support/Path.h"
34e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
35e5dd7070Spatrick #include <algorithm>
36e5dd7070Spatrick #include <cassert>
37e5dd7070Spatrick #include <cstddef>
38e5dd7070Spatrick #include <cstdint>
39e5dd7070Spatrick #include <memory>
40*12c85518Srobert #include <optional>
41e5dd7070Spatrick #include <tuple>
42e5dd7070Spatrick #include <utility>
43e5dd7070Spatrick #include <vector>
44e5dd7070Spatrick
45e5dd7070Spatrick using namespace clang;
46e5dd7070Spatrick using namespace SrcMgr;
47e5dd7070Spatrick using llvm::MemoryBuffer;
48e5dd7070Spatrick
49e5dd7070Spatrick //===----------------------------------------------------------------------===//
50e5dd7070Spatrick // SourceManager Helper Classes
51e5dd7070Spatrick //===----------------------------------------------------------------------===//
52e5dd7070Spatrick
53e5dd7070Spatrick /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
54e5dd7070Spatrick /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
getSizeBytesMapped() const55e5dd7070Spatrick unsigned ContentCache::getSizeBytesMapped() const {
56a9ac8606Spatrick return Buffer ? Buffer->getBufferSize() : 0;
57e5dd7070Spatrick }
58e5dd7070Spatrick
59e5dd7070Spatrick /// Returns the kind of memory used to back the memory buffer for
60e5dd7070Spatrick /// this content cache. This is used for performance analysis.
getMemoryBufferKind() const61e5dd7070Spatrick llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
62*12c85518Srobert if (Buffer == nullptr) {
63*12c85518Srobert assert(0 && "Buffer should never be null");
64e5dd7070Spatrick return llvm::MemoryBuffer::MemoryBuffer_Malloc;
65*12c85518Srobert }
66a9ac8606Spatrick return Buffer->getBufferKind();
67e5dd7070Spatrick }
68e5dd7070Spatrick
69e5dd7070Spatrick /// getSize - Returns the size of the content encapsulated by this ContentCache.
70e5dd7070Spatrick /// This can be the size of the source file or the size of an arbitrary
71e5dd7070Spatrick /// scratch buffer. If the ContentCache encapsulates a source file, that
72e5dd7070Spatrick /// file is not lazily brought in from disk to satisfy this query.
getSize() const73e5dd7070Spatrick unsigned ContentCache::getSize() const {
74a9ac8606Spatrick return Buffer ? (unsigned)Buffer->getBufferSize()
75e5dd7070Spatrick : (unsigned)ContentsEntry->getSize();
76e5dd7070Spatrick }
77e5dd7070Spatrick
getInvalidBOM(StringRef BufStr)78e5dd7070Spatrick const char *ContentCache::getInvalidBOM(StringRef BufStr) {
79e5dd7070Spatrick // If the buffer is valid, check to see if it has a UTF Byte Order Mark
80e5dd7070Spatrick // (BOM). We only support UTF-8 with and without a BOM right now. See
81e5dd7070Spatrick // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
82e5dd7070Spatrick const char *InvalidBOM =
83e5dd7070Spatrick llvm::StringSwitch<const char *>(BufStr)
84e5dd7070Spatrick .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
85e5dd7070Spatrick "UTF-32 (BE)")
86e5dd7070Spatrick .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
87e5dd7070Spatrick "UTF-32 (LE)")
88e5dd7070Spatrick .StartsWith("\xFE\xFF", "UTF-16 (BE)")
89e5dd7070Spatrick .StartsWith("\xFF\xFE", "UTF-16 (LE)")
90e5dd7070Spatrick .StartsWith("\x2B\x2F\x76", "UTF-7")
91e5dd7070Spatrick .StartsWith("\xF7\x64\x4C", "UTF-1")
92e5dd7070Spatrick .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
93e5dd7070Spatrick .StartsWith("\x0E\xFE\xFF", "SCSU")
94e5dd7070Spatrick .StartsWith("\xFB\xEE\x28", "BOCU-1")
95e5dd7070Spatrick .StartsWith("\x84\x31\x95\x33", "GB-18030")
96e5dd7070Spatrick .Default(nullptr);
97e5dd7070Spatrick
98e5dd7070Spatrick return InvalidBOM;
99e5dd7070Spatrick }
100e5dd7070Spatrick
101*12c85518Srobert std::optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine & Diag,FileManager & FM,SourceLocation Loc) const102a9ac8606Spatrick ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
103a9ac8606Spatrick SourceLocation Loc) const {
104e5dd7070Spatrick // Lazily create the Buffer for ContentCaches that wrap files. If we already
105e5dd7070Spatrick // computed it, just return what we have.
106a9ac8606Spatrick if (IsBufferInvalid)
107*12c85518Srobert return std::nullopt;
108a9ac8606Spatrick if (Buffer)
109a9ac8606Spatrick return Buffer->getMemBufferRef();
110a9ac8606Spatrick if (!ContentsEntry)
111*12c85518Srobert return std::nullopt;
112e5dd7070Spatrick
113a9ac8606Spatrick // Start with the assumption that the buffer is invalid to simplify early
114a9ac8606Spatrick // return paths.
115a9ac8606Spatrick IsBufferInvalid = true;
116e5dd7070Spatrick
117e5dd7070Spatrick auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
118e5dd7070Spatrick
119e5dd7070Spatrick // If we were unable to open the file, then we are in an inconsistent
120e5dd7070Spatrick // situation where the content cache referenced a file which no longer
121e5dd7070Spatrick // exists. Most likely, we were using a stat cache with an invalid entry but
122e5dd7070Spatrick // the file could also have been removed during processing. Since we can't
123e5dd7070Spatrick // really deal with this situation, just create an empty buffer.
124e5dd7070Spatrick if (!BufferOrError) {
125e5dd7070Spatrick if (Diag.isDiagnosticInFlight())
126e5dd7070Spatrick Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
127e5dd7070Spatrick ContentsEntry->getName(),
128e5dd7070Spatrick BufferOrError.getError().message());
129e5dd7070Spatrick else
130e5dd7070Spatrick Diag.Report(Loc, diag::err_cannot_open_file)
131e5dd7070Spatrick << ContentsEntry->getName() << BufferOrError.getError().message();
132e5dd7070Spatrick
133*12c85518Srobert return std::nullopt;
134e5dd7070Spatrick }
135e5dd7070Spatrick
136a9ac8606Spatrick Buffer = std::move(*BufferOrError);
137e5dd7070Spatrick
138a9ac8606Spatrick // Check that the file's size fits in an 'unsigned' (with room for a
139a9ac8606Spatrick // past-the-end value). This is deeply regrettable, but various parts of
140a9ac8606Spatrick // Clang (including elsewhere in this file!) use 'unsigned' to represent file
141a9ac8606Spatrick // offsets, line numbers, string literal lengths, and so on, and fail
142a9ac8606Spatrick // miserably on large source files.
143a9ac8606Spatrick //
144a9ac8606Spatrick // Note: ContentsEntry could be a named pipe, in which case
145a9ac8606Spatrick // ContentsEntry::getSize() could have the wrong size. Use
146a9ac8606Spatrick // MemoryBuffer::getBufferSize() instead.
147a9ac8606Spatrick if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
148a9ac8606Spatrick if (Diag.isDiagnosticInFlight())
149a9ac8606Spatrick Diag.SetDelayedDiagnostic(diag::err_file_too_large,
150a9ac8606Spatrick ContentsEntry->getName());
151a9ac8606Spatrick else
152a9ac8606Spatrick Diag.Report(Loc, diag::err_file_too_large)
153a9ac8606Spatrick << ContentsEntry->getName();
154a9ac8606Spatrick
155*12c85518Srobert return std::nullopt;
156a9ac8606Spatrick }
157a9ac8606Spatrick
158a9ac8606Spatrick // Unless this is a named pipe (in which case we can handle a mismatch),
159a9ac8606Spatrick // check that the file's size is the same as in the file entry (which may
160e5dd7070Spatrick // have come from a stat cache).
161a9ac8606Spatrick if (!ContentsEntry->isNamedPipe() &&
162a9ac8606Spatrick Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
163e5dd7070Spatrick if (Diag.isDiagnosticInFlight())
164e5dd7070Spatrick Diag.SetDelayedDiagnostic(diag::err_file_modified,
165e5dd7070Spatrick ContentsEntry->getName());
166e5dd7070Spatrick else
167e5dd7070Spatrick Diag.Report(Loc, diag::err_file_modified)
168e5dd7070Spatrick << ContentsEntry->getName();
169e5dd7070Spatrick
170*12c85518Srobert return std::nullopt;
171e5dd7070Spatrick }
172e5dd7070Spatrick
173e5dd7070Spatrick // If the buffer is valid, check to see if it has a UTF Byte Order Mark
174e5dd7070Spatrick // (BOM). We only support UTF-8 with and without a BOM right now. See
175e5dd7070Spatrick // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
176a9ac8606Spatrick StringRef BufStr = Buffer->getBuffer();
177e5dd7070Spatrick const char *InvalidBOM = getInvalidBOM(BufStr);
178e5dd7070Spatrick
179e5dd7070Spatrick if (InvalidBOM) {
180e5dd7070Spatrick Diag.Report(Loc, diag::err_unsupported_bom)
181e5dd7070Spatrick << InvalidBOM << ContentsEntry->getName();
182*12c85518Srobert return std::nullopt;
183e5dd7070Spatrick }
184e5dd7070Spatrick
185a9ac8606Spatrick // Buffer has been validated.
186a9ac8606Spatrick IsBufferInvalid = false;
187a9ac8606Spatrick return Buffer->getMemBufferRef();
188e5dd7070Spatrick }
189e5dd7070Spatrick
getLineTableFilenameID(StringRef Name)190e5dd7070Spatrick unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
191e5dd7070Spatrick auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
192e5dd7070Spatrick if (IterBool.second)
193e5dd7070Spatrick FilenamesByID.push_back(&*IterBool.first);
194e5dd7070Spatrick return IterBool.first->second;
195e5dd7070Spatrick }
196e5dd7070Spatrick
197e5dd7070Spatrick /// Add a line note to the line table that indicates that there is a \#line or
198e5dd7070Spatrick /// GNU line marker at the specified FID/Offset location which changes the
199e5dd7070Spatrick /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
200e5dd7070Spatrick /// change the presumed \#include stack. If it is 1, this is a file entry, if
201e5dd7070Spatrick /// it is 2 then this is a file exit. FileKind specifies whether this is a
202e5dd7070Spatrick /// system header or extern C system header.
AddLineNote(FileID FID,unsigned Offset,unsigned LineNo,int FilenameID,unsigned EntryExit,SrcMgr::CharacteristicKind FileKind)203e5dd7070Spatrick void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
204e5dd7070Spatrick int FilenameID, unsigned EntryExit,
205e5dd7070Spatrick SrcMgr::CharacteristicKind FileKind) {
206e5dd7070Spatrick std::vector<LineEntry> &Entries = LineEntries[FID];
207e5dd7070Spatrick
208e5dd7070Spatrick assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
209e5dd7070Spatrick "Adding line entries out of order!");
210e5dd7070Spatrick
211e5dd7070Spatrick unsigned IncludeOffset = 0;
212*12c85518Srobert if (EntryExit == 1) {
213*12c85518Srobert // Push #include
214e5dd7070Spatrick IncludeOffset = Offset-1;
215*12c85518Srobert } else {
216*12c85518Srobert const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
217*12c85518Srobert if (EntryExit == 2) {
218*12c85518Srobert // Pop #include
219*12c85518Srobert assert(PrevEntry && PrevEntry->IncludeOffset &&
220*12c85518Srobert "PPDirectives should have caught case when popping empty include "
221*12c85518Srobert "stack");
222*12c85518Srobert PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
223*12c85518Srobert }
224*12c85518Srobert if (PrevEntry) {
225e5dd7070Spatrick IncludeOffset = PrevEntry->IncludeOffset;
226*12c85518Srobert if (FilenameID == -1) {
227*12c85518Srobert // An unspecified FilenameID means use the previous (or containing)
228*12c85518Srobert // filename if available, or the main source file otherwise.
229*12c85518Srobert FilenameID = PrevEntry->FilenameID;
230*12c85518Srobert }
231*12c85518Srobert }
232e5dd7070Spatrick }
233e5dd7070Spatrick
234e5dd7070Spatrick Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
235e5dd7070Spatrick IncludeOffset));
236e5dd7070Spatrick }
237e5dd7070Spatrick
238e5dd7070Spatrick /// FindNearestLineEntry - Find the line entry nearest to FID that is before
239e5dd7070Spatrick /// it. If there is no line entry before Offset in FID, return null.
FindNearestLineEntry(FileID FID,unsigned Offset)240e5dd7070Spatrick const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
241e5dd7070Spatrick unsigned Offset) {
242e5dd7070Spatrick const std::vector<LineEntry> &Entries = LineEntries[FID];
243e5dd7070Spatrick assert(!Entries.empty() && "No #line entries for this FID after all!");
244e5dd7070Spatrick
245e5dd7070Spatrick // It is very common for the query to be after the last #line, check this
246e5dd7070Spatrick // first.
247e5dd7070Spatrick if (Entries.back().FileOffset <= Offset)
248e5dd7070Spatrick return &Entries.back();
249e5dd7070Spatrick
250e5dd7070Spatrick // Do a binary search to find the maximal element that is still before Offset.
251e5dd7070Spatrick std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
252e5dd7070Spatrick if (I == Entries.begin())
253e5dd7070Spatrick return nullptr;
254e5dd7070Spatrick return &*--I;
255e5dd7070Spatrick }
256e5dd7070Spatrick
257e5dd7070Spatrick /// Add a new line entry that has already been encoded into
258e5dd7070Spatrick /// the internal representation of the line table.
AddEntry(FileID FID,const std::vector<LineEntry> & Entries)259e5dd7070Spatrick void LineTableInfo::AddEntry(FileID FID,
260e5dd7070Spatrick const std::vector<LineEntry> &Entries) {
261e5dd7070Spatrick LineEntries[FID] = Entries;
262e5dd7070Spatrick }
263e5dd7070Spatrick
264e5dd7070Spatrick /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
getLineTableFilenameID(StringRef Name)265e5dd7070Spatrick unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
266e5dd7070Spatrick return getLineTable().getLineTableFilenameID(Name);
267e5dd7070Spatrick }
268e5dd7070Spatrick
269e5dd7070Spatrick /// AddLineNote - Add a line note to the line table for the FileID and offset
270e5dd7070Spatrick /// specified by Loc. If FilenameID is -1, it is considered to be
271e5dd7070Spatrick /// unspecified.
AddLineNote(SourceLocation Loc,unsigned LineNo,int FilenameID,bool IsFileEntry,bool IsFileExit,SrcMgr::CharacteristicKind FileKind)272e5dd7070Spatrick void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
273e5dd7070Spatrick int FilenameID, bool IsFileEntry,
274e5dd7070Spatrick bool IsFileExit,
275e5dd7070Spatrick SrcMgr::CharacteristicKind FileKind) {
276e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
277e5dd7070Spatrick
278e5dd7070Spatrick bool Invalid = false;
279e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
280e5dd7070Spatrick if (!Entry.isFile() || Invalid)
281e5dd7070Spatrick return;
282e5dd7070Spatrick
283e5dd7070Spatrick const SrcMgr::FileInfo &FileInfo = Entry.getFile();
284e5dd7070Spatrick
285e5dd7070Spatrick // Remember that this file has #line directives now if it doesn't already.
286e5dd7070Spatrick const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
287e5dd7070Spatrick
288e5dd7070Spatrick (void) getLineTable();
289e5dd7070Spatrick
290e5dd7070Spatrick unsigned EntryExit = 0;
291e5dd7070Spatrick if (IsFileEntry)
292e5dd7070Spatrick EntryExit = 1;
293e5dd7070Spatrick else if (IsFileExit)
294e5dd7070Spatrick EntryExit = 2;
295e5dd7070Spatrick
296e5dd7070Spatrick LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
297e5dd7070Spatrick EntryExit, FileKind);
298e5dd7070Spatrick }
299e5dd7070Spatrick
getLineTable()300e5dd7070Spatrick LineTableInfo &SourceManager::getLineTable() {
301e5dd7070Spatrick if (!LineTable)
302e5dd7070Spatrick LineTable.reset(new LineTableInfo());
303e5dd7070Spatrick return *LineTable;
304e5dd7070Spatrick }
305e5dd7070Spatrick
306e5dd7070Spatrick //===----------------------------------------------------------------------===//
307e5dd7070Spatrick // Private 'Create' methods.
308e5dd7070Spatrick //===----------------------------------------------------------------------===//
309e5dd7070Spatrick
SourceManager(DiagnosticsEngine & Diag,FileManager & FileMgr,bool UserFilesAreVolatile)310e5dd7070Spatrick SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
311e5dd7070Spatrick bool UserFilesAreVolatile)
312e5dd7070Spatrick : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
313e5dd7070Spatrick clearIDTables();
314e5dd7070Spatrick Diag.setSourceManager(this);
315e5dd7070Spatrick }
316e5dd7070Spatrick
~SourceManager()317e5dd7070Spatrick SourceManager::~SourceManager() {
318e5dd7070Spatrick // Delete FileEntry objects corresponding to content caches. Since the actual
319e5dd7070Spatrick // content cache objects are bump pointer allocated, we just have to run the
320e5dd7070Spatrick // dtors, but we call the deallocate method for completeness.
321e5dd7070Spatrick for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
322e5dd7070Spatrick if (MemBufferInfos[i]) {
323e5dd7070Spatrick MemBufferInfos[i]->~ContentCache();
324e5dd7070Spatrick ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
325e5dd7070Spatrick }
326e5dd7070Spatrick }
327e5dd7070Spatrick for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
328e5dd7070Spatrick I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
329e5dd7070Spatrick if (I->second) {
330e5dd7070Spatrick I->second->~ContentCache();
331e5dd7070Spatrick ContentCacheAlloc.Deallocate(I->second);
332e5dd7070Spatrick }
333e5dd7070Spatrick }
334e5dd7070Spatrick }
335e5dd7070Spatrick
clearIDTables()336e5dd7070Spatrick void SourceManager::clearIDTables() {
337e5dd7070Spatrick MainFileID = FileID();
338e5dd7070Spatrick LocalSLocEntryTable.clear();
339e5dd7070Spatrick LoadedSLocEntryTable.clear();
340e5dd7070Spatrick SLocEntryLoaded.clear();
341e5dd7070Spatrick LastLineNoFileIDQuery = FileID();
342e5dd7070Spatrick LastLineNoContentCache = nullptr;
343e5dd7070Spatrick LastFileIDLookup = FileID();
344e5dd7070Spatrick
345e5dd7070Spatrick if (LineTable)
346e5dd7070Spatrick LineTable->clear();
347e5dd7070Spatrick
348e5dd7070Spatrick // Use up FileID #0 as an invalid expansion.
349e5dd7070Spatrick NextLocalOffset = 0;
350e5dd7070Spatrick CurrentLoadedOffset = MaxLoadedOffset;
351e5dd7070Spatrick createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
352e5dd7070Spatrick }
353e5dd7070Spatrick
isMainFile(const FileEntry & SourceFile)354a9ac8606Spatrick bool SourceManager::isMainFile(const FileEntry &SourceFile) {
355ec727ea7Spatrick assert(MainFileID.isValid() && "expected initialized SourceManager");
356a9ac8606Spatrick if (auto *FE = getFileEntryForID(MainFileID))
357ec727ea7Spatrick return FE->getUID() == SourceFile.getUID();
358a9ac8606Spatrick return false;
359ec727ea7Spatrick }
360ec727ea7Spatrick
initializeForReplay(const SourceManager & Old)361e5dd7070Spatrick void SourceManager::initializeForReplay(const SourceManager &Old) {
362e5dd7070Spatrick assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
363e5dd7070Spatrick
364e5dd7070Spatrick auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
365e5dd7070Spatrick auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
366e5dd7070Spatrick Clone->OrigEntry = Cache->OrigEntry;
367e5dd7070Spatrick Clone->ContentsEntry = Cache->ContentsEntry;
368e5dd7070Spatrick Clone->BufferOverridden = Cache->BufferOverridden;
369e5dd7070Spatrick Clone->IsFileVolatile = Cache->IsFileVolatile;
370e5dd7070Spatrick Clone->IsTransient = Cache->IsTransient;
371a9ac8606Spatrick Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
372e5dd7070Spatrick return Clone;
373e5dd7070Spatrick };
374e5dd7070Spatrick
375e5dd7070Spatrick // Ensure all SLocEntries are loaded from the external source.
376e5dd7070Spatrick for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
377e5dd7070Spatrick if (!Old.SLocEntryLoaded[I])
378e5dd7070Spatrick Old.loadSLocEntry(I, nullptr);
379e5dd7070Spatrick
380e5dd7070Spatrick // Inherit any content cache data from the old source manager.
381e5dd7070Spatrick for (auto &FileInfo : Old.FileInfos) {
382e5dd7070Spatrick SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
383e5dd7070Spatrick if (Slot)
384e5dd7070Spatrick continue;
385e5dd7070Spatrick Slot = CloneContentCache(FileInfo.second);
386e5dd7070Spatrick }
387e5dd7070Spatrick }
388e5dd7070Spatrick
getOrCreateContentCache(FileEntryRef FileEnt,bool isSystemFile)389a9ac8606Spatrick ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
390e5dd7070Spatrick bool isSystemFile) {
391e5dd7070Spatrick // Do we already have information about this file?
392e5dd7070Spatrick ContentCache *&Entry = FileInfos[FileEnt];
393a9ac8606Spatrick if (Entry)
394a9ac8606Spatrick return *Entry;
395e5dd7070Spatrick
396e5dd7070Spatrick // Nope, create a new Cache entry.
397e5dd7070Spatrick Entry = ContentCacheAlloc.Allocate<ContentCache>();
398e5dd7070Spatrick
399e5dd7070Spatrick if (OverriddenFilesInfo) {
400e5dd7070Spatrick // If the file contents are overridden with contents from another file,
401e5dd7070Spatrick // pass that file to ContentCache.
402*12c85518Srobert auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
403e5dd7070Spatrick if (overI == OverriddenFilesInfo->OverriddenFiles.end())
404e5dd7070Spatrick new (Entry) ContentCache(FileEnt);
405e5dd7070Spatrick else
406e5dd7070Spatrick new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
407e5dd7070Spatrick : overI->second,
408e5dd7070Spatrick overI->second);
409e5dd7070Spatrick } else {
410e5dd7070Spatrick new (Entry) ContentCache(FileEnt);
411e5dd7070Spatrick }
412e5dd7070Spatrick
413e5dd7070Spatrick Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
414e5dd7070Spatrick Entry->IsTransient = FilesAreTransient;
415a9ac8606Spatrick Entry->BufferOverridden |= FileEnt.isNamedPipe();
416e5dd7070Spatrick
417a9ac8606Spatrick return *Entry;
418e5dd7070Spatrick }
419e5dd7070Spatrick
420e5dd7070Spatrick /// Create a new ContentCache for the specified memory buffer.
421e5dd7070Spatrick /// This does no caching.
createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buffer)422a9ac8606Spatrick ContentCache &SourceManager::createMemBufferContentCache(
423a9ac8606Spatrick std::unique_ptr<llvm::MemoryBuffer> Buffer) {
424e5dd7070Spatrick // Add a new ContentCache to the MemBufferInfos list and return it.
425e5dd7070Spatrick ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
426e5dd7070Spatrick new (Entry) ContentCache();
427e5dd7070Spatrick MemBufferInfos.push_back(Entry);
428a9ac8606Spatrick Entry->setBuffer(std::move(Buffer));
429a9ac8606Spatrick return *Entry;
430e5dd7070Spatrick }
431e5dd7070Spatrick
loadSLocEntry(unsigned Index,bool * Invalid) const432e5dd7070Spatrick const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
433e5dd7070Spatrick bool *Invalid) const {
434e5dd7070Spatrick assert(!SLocEntryLoaded[Index]);
435e5dd7070Spatrick if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
436e5dd7070Spatrick if (Invalid)
437e5dd7070Spatrick *Invalid = true;
438e5dd7070Spatrick // If the file of the SLocEntry changed we could still have loaded it.
439e5dd7070Spatrick if (!SLocEntryLoaded[Index]) {
440e5dd7070Spatrick // Try to recover; create a SLocEntry so the rest of clang can handle it.
441a9ac8606Spatrick if (!FakeSLocEntryForRecovery)
442a9ac8606Spatrick FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
443e5dd7070Spatrick 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
444a9ac8606Spatrick SrcMgr::C_User, "")));
445a9ac8606Spatrick return *FakeSLocEntryForRecovery;
446e5dd7070Spatrick }
447e5dd7070Spatrick }
448e5dd7070Spatrick
449e5dd7070Spatrick return LoadedSLocEntryTable[Index];
450e5dd7070Spatrick }
451e5dd7070Spatrick
452a9ac8606Spatrick std::pair<int, SourceLocation::UIntTy>
AllocateLoadedSLocEntries(unsigned NumSLocEntries,SourceLocation::UIntTy TotalSize)453e5dd7070Spatrick SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
454a9ac8606Spatrick SourceLocation::UIntTy TotalSize) {
455e5dd7070Spatrick assert(ExternalSLocEntries && "Don't have an external sloc source");
456e5dd7070Spatrick // Make sure we're not about to run out of source locations.
457*12c85518Srobert if (CurrentLoadedOffset < TotalSize ||
458*12c85518Srobert CurrentLoadedOffset - TotalSize < NextLocalOffset) {
459e5dd7070Spatrick return std::make_pair(0, 0);
460*12c85518Srobert }
461e5dd7070Spatrick LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
462e5dd7070Spatrick SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
463e5dd7070Spatrick CurrentLoadedOffset -= TotalSize;
464e5dd7070Spatrick int ID = LoadedSLocEntryTable.size();
465e5dd7070Spatrick return std::make_pair(-ID - 1, CurrentLoadedOffset);
466e5dd7070Spatrick }
467e5dd7070Spatrick
468e5dd7070Spatrick /// As part of recovering from missing or changed content, produce a
469e5dd7070Spatrick /// fake, non-empty buffer.
getFakeBufferForRecovery() const470a9ac8606Spatrick llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
471e5dd7070Spatrick if (!FakeBufferForRecovery)
472e5dd7070Spatrick FakeBufferForRecovery =
473e5dd7070Spatrick llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
474e5dd7070Spatrick
475a9ac8606Spatrick return *FakeBufferForRecovery;
476e5dd7070Spatrick }
477e5dd7070Spatrick
478e5dd7070Spatrick /// As part of recovering from missing or changed content, produce a
479e5dd7070Spatrick /// fake content cache.
getFakeContentCacheForRecovery() const480a9ac8606Spatrick SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
481e5dd7070Spatrick if (!FakeContentCacheForRecovery) {
482e5dd7070Spatrick FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
483a9ac8606Spatrick FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
484e5dd7070Spatrick }
485a9ac8606Spatrick return *FakeContentCacheForRecovery;
486e5dd7070Spatrick }
487e5dd7070Spatrick
488e5dd7070Spatrick /// Returns the previous in-order FileID or an invalid FileID if there
489e5dd7070Spatrick /// is no previous one.
getPreviousFileID(FileID FID) const490e5dd7070Spatrick FileID SourceManager::getPreviousFileID(FileID FID) const {
491e5dd7070Spatrick if (FID.isInvalid())
492e5dd7070Spatrick return FileID();
493e5dd7070Spatrick
494e5dd7070Spatrick int ID = FID.ID;
495e5dd7070Spatrick if (ID == -1)
496e5dd7070Spatrick return FileID();
497e5dd7070Spatrick
498e5dd7070Spatrick if (ID > 0) {
499e5dd7070Spatrick if (ID-1 == 0)
500e5dd7070Spatrick return FileID();
501e5dd7070Spatrick } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
502e5dd7070Spatrick return FileID();
503e5dd7070Spatrick }
504e5dd7070Spatrick
505e5dd7070Spatrick return FileID::get(ID-1);
506e5dd7070Spatrick }
507e5dd7070Spatrick
508e5dd7070Spatrick /// Returns the next in-order FileID or an invalid FileID if there is
509e5dd7070Spatrick /// no next one.
getNextFileID(FileID FID) const510e5dd7070Spatrick FileID SourceManager::getNextFileID(FileID FID) const {
511e5dd7070Spatrick if (FID.isInvalid())
512e5dd7070Spatrick return FileID();
513e5dd7070Spatrick
514e5dd7070Spatrick int ID = FID.ID;
515e5dd7070Spatrick if (ID > 0) {
516e5dd7070Spatrick if (unsigned(ID+1) >= local_sloc_entry_size())
517e5dd7070Spatrick return FileID();
518e5dd7070Spatrick } else if (ID+1 >= -1) {
519e5dd7070Spatrick return FileID();
520e5dd7070Spatrick }
521e5dd7070Spatrick
522e5dd7070Spatrick return FileID::get(ID+1);
523e5dd7070Spatrick }
524e5dd7070Spatrick
525e5dd7070Spatrick //===----------------------------------------------------------------------===//
526e5dd7070Spatrick // Methods to create new FileID's and macro expansions.
527e5dd7070Spatrick //===----------------------------------------------------------------------===//
528e5dd7070Spatrick
529ec727ea7Spatrick /// Create a new FileID that represents the specified file
530ec727ea7Spatrick /// being \#included from the specified IncludePosition.
531ec727ea7Spatrick ///
532ec727ea7Spatrick /// This translates NULL into standard input.
createFileID(const FileEntry * SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)533ec727ea7Spatrick FileID SourceManager::createFileID(const FileEntry *SourceFile,
534ec727ea7Spatrick SourceLocation IncludePos,
535ec727ea7Spatrick SrcMgr::CharacteristicKind FileCharacter,
536a9ac8606Spatrick int LoadedID,
537a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset) {
538a9ac8606Spatrick return createFileID(SourceFile->getLastRef(), IncludePos, FileCharacter,
539ec727ea7Spatrick LoadedID, LoadedOffset);
540ec727ea7Spatrick }
541ec727ea7Spatrick
createFileID(FileEntryRef SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)542ec727ea7Spatrick FileID SourceManager::createFileID(FileEntryRef SourceFile,
543ec727ea7Spatrick SourceLocation IncludePos,
544ec727ea7Spatrick SrcMgr::CharacteristicKind FileCharacter,
545a9ac8606Spatrick int LoadedID,
546a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset) {
547a9ac8606Spatrick SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
548a9ac8606Spatrick isSystem(FileCharacter));
549a9ac8606Spatrick
550a9ac8606Spatrick // If this is a named pipe, immediately load the buffer to ensure subsequent
551a9ac8606Spatrick // calls to ContentCache::getSize() are accurate.
552a9ac8606Spatrick if (IR.ContentsEntry->isNamedPipe())
553a9ac8606Spatrick (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
554a9ac8606Spatrick
555a9ac8606Spatrick return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
556ec727ea7Spatrick LoadedID, LoadedOffset);
557ec727ea7Spatrick }
558ec727ea7Spatrick
559ec727ea7Spatrick /// Create a new FileID that represents the specified memory buffer.
560ec727ea7Spatrick ///
561ec727ea7Spatrick /// This does no caching of the buffer and takes ownership of the
562ec727ea7Spatrick /// MemoryBuffer, so only pass a MemoryBuffer to this once.
createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset,SourceLocation IncludeLoc)563ec727ea7Spatrick FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
564ec727ea7Spatrick SrcMgr::CharacteristicKind FileCharacter,
565a9ac8606Spatrick int LoadedID,
566a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset,
567ec727ea7Spatrick SourceLocation IncludeLoc) {
568ec727ea7Spatrick StringRef Name = Buffer->getBufferIdentifier();
569a9ac8606Spatrick return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
570a9ac8606Spatrick IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
571ec727ea7Spatrick }
572ec727ea7Spatrick
573ec727ea7Spatrick /// Create a new FileID that represents the specified memory buffer.
574ec727ea7Spatrick ///
575ec727ea7Spatrick /// This does not take ownership of the MemoryBuffer. The memory buffer must
576ec727ea7Spatrick /// outlive the SourceManager.
createFileID(const llvm::MemoryBufferRef & Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset,SourceLocation IncludeLoc)577a9ac8606Spatrick FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
578ec727ea7Spatrick SrcMgr::CharacteristicKind FileCharacter,
579a9ac8606Spatrick int LoadedID,
580a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset,
581ec727ea7Spatrick SourceLocation IncludeLoc) {
582a9ac8606Spatrick return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
583a9ac8606Spatrick LoadedID, LoadedOffset, IncludeLoc);
584ec727ea7Spatrick }
585ec727ea7Spatrick
586ec727ea7Spatrick /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
587ec727ea7Spatrick /// new FileID for the \p SourceFile.
588ec727ea7Spatrick FileID
getOrCreateFileID(const FileEntry * SourceFile,SrcMgr::CharacteristicKind FileCharacter)589ec727ea7Spatrick SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
590ec727ea7Spatrick SrcMgr::CharacteristicKind FileCharacter) {
591ec727ea7Spatrick FileID ID = translateFile(SourceFile);
592ec727ea7Spatrick return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
593ec727ea7Spatrick FileCharacter);
594ec727ea7Spatrick }
595ec727ea7Spatrick
596e5dd7070Spatrick /// createFileID - Create a new FileID for the specified ContentCache and
597e5dd7070Spatrick /// include position. This works regardless of whether the ContentCache
598e5dd7070Spatrick /// corresponds to a file or some other input source.
createFileIDImpl(ContentCache & File,StringRef Filename,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)599a9ac8606Spatrick FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
600e5dd7070Spatrick SourceLocation IncludePos,
601e5dd7070Spatrick SrcMgr::CharacteristicKind FileCharacter,
602a9ac8606Spatrick int LoadedID,
603a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset) {
604e5dd7070Spatrick if (LoadedID < 0) {
605e5dd7070Spatrick assert(LoadedID != -1 && "Loading sentinel FileID");
606e5dd7070Spatrick unsigned Index = unsigned(-LoadedID) - 2;
607e5dd7070Spatrick assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
608e5dd7070Spatrick assert(!SLocEntryLoaded[Index] && "FileID already loaded");
609e5dd7070Spatrick LoadedSLocEntryTable[Index] = SLocEntry::get(
610e5dd7070Spatrick LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
611e5dd7070Spatrick SLocEntryLoaded[Index] = true;
612e5dd7070Spatrick return FileID::get(LoadedID);
613e5dd7070Spatrick }
614a9ac8606Spatrick unsigned FileSize = File.getSize();
615ec727ea7Spatrick if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
616ec727ea7Spatrick NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
617ec727ea7Spatrick Diag.Report(IncludePos, diag::err_include_too_large);
618*12c85518Srobert noteSLocAddressSpaceUsage(Diag);
619ec727ea7Spatrick return FileID();
620ec727ea7Spatrick }
621e5dd7070Spatrick LocalSLocEntryTable.push_back(
622e5dd7070Spatrick SLocEntry::get(NextLocalOffset,
623e5dd7070Spatrick FileInfo::get(IncludePos, File, FileCharacter, Filename)));
624e5dd7070Spatrick // We do a +1 here because we want a SourceLocation that means "the end of the
625e5dd7070Spatrick // file", e.g. for the "no newline at the end of the file" diagnostic.
626e5dd7070Spatrick NextLocalOffset += FileSize + 1;
627e5dd7070Spatrick
628e5dd7070Spatrick // Set LastFileIDLookup to the newly created file. The next getFileID call is
629e5dd7070Spatrick // almost guaranteed to be from that file.
630e5dd7070Spatrick FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
631e5dd7070Spatrick return LastFileIDLookup = FID;
632e5dd7070Spatrick }
633e5dd7070Spatrick
createMacroArgExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLoc,unsigned Length)634*12c85518Srobert SourceLocation SourceManager::createMacroArgExpansionLoc(
635*12c85518Srobert SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
636e5dd7070Spatrick ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
637e5dd7070Spatrick ExpansionLoc);
638*12c85518Srobert return createExpansionLocImpl(Info, Length);
639e5dd7070Spatrick }
640e5dd7070Spatrick
createExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned Length,bool ExpansionIsTokenRange,int LoadedID,SourceLocation::UIntTy LoadedOffset)641a9ac8606Spatrick SourceLocation SourceManager::createExpansionLoc(
642a9ac8606Spatrick SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
643*12c85518Srobert SourceLocation ExpansionLocEnd, unsigned Length,
644a9ac8606Spatrick bool ExpansionIsTokenRange, int LoadedID,
645a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset) {
646e5dd7070Spatrick ExpansionInfo Info = ExpansionInfo::create(
647e5dd7070Spatrick SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
648*12c85518Srobert return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
649e5dd7070Spatrick }
650e5dd7070Spatrick
createTokenSplitLoc(SourceLocation Spelling,SourceLocation TokenStart,SourceLocation TokenEnd)651e5dd7070Spatrick SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
652e5dd7070Spatrick SourceLocation TokenStart,
653e5dd7070Spatrick SourceLocation TokenEnd) {
654e5dd7070Spatrick assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
655e5dd7070Spatrick "token spans multiple files");
656e5dd7070Spatrick return createExpansionLocImpl(
657e5dd7070Spatrick ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
658e5dd7070Spatrick TokenEnd.getOffset() - TokenStart.getOffset());
659e5dd7070Spatrick }
660e5dd7070Spatrick
661e5dd7070Spatrick SourceLocation
createExpansionLocImpl(const ExpansionInfo & Info,unsigned Length,int LoadedID,SourceLocation::UIntTy LoadedOffset)662e5dd7070Spatrick SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
663*12c85518Srobert unsigned Length, int LoadedID,
664a9ac8606Spatrick SourceLocation::UIntTy LoadedOffset) {
665e5dd7070Spatrick if (LoadedID < 0) {
666e5dd7070Spatrick assert(LoadedID != -1 && "Loading sentinel FileID");
667e5dd7070Spatrick unsigned Index = unsigned(-LoadedID) - 2;
668e5dd7070Spatrick assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
669e5dd7070Spatrick assert(!SLocEntryLoaded[Index] && "FileID already loaded");
670e5dd7070Spatrick LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
671e5dd7070Spatrick SLocEntryLoaded[Index] = true;
672e5dd7070Spatrick return SourceLocation::getMacroLoc(LoadedOffset);
673e5dd7070Spatrick }
674e5dd7070Spatrick LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
675*12c85518Srobert // FIXME: Produce a proper diagnostic for this case.
676*12c85518Srobert assert(NextLocalOffset + Length + 1 > NextLocalOffset &&
677*12c85518Srobert NextLocalOffset + Length + 1 <= CurrentLoadedOffset &&
678e5dd7070Spatrick "Ran out of source locations!");
679e5dd7070Spatrick // See createFileID for that +1.
680*12c85518Srobert NextLocalOffset += Length + 1;
681*12c85518Srobert return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
682e5dd7070Spatrick }
683e5dd7070Spatrick
684*12c85518Srobert std::optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(const FileEntry * File)685a9ac8606Spatrick SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
686a9ac8606Spatrick SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef());
687a9ac8606Spatrick return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
688e5dd7070Spatrick }
689e5dd7070Spatrick
overrideFileContents(const FileEntry * SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)690a9ac8606Spatrick void SourceManager::overrideFileContents(
691a9ac8606Spatrick const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
692a9ac8606Spatrick SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile->getLastRef());
693e5dd7070Spatrick
694a9ac8606Spatrick IR.setBuffer(std::move(Buffer));
695a9ac8606Spatrick IR.BufferOverridden = true;
696e5dd7070Spatrick
697e5dd7070Spatrick getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
698e5dd7070Spatrick }
699e5dd7070Spatrick
overrideFileContents(const FileEntry * SourceFile,FileEntryRef NewFile)700e5dd7070Spatrick void SourceManager::overrideFileContents(const FileEntry *SourceFile,
701*12c85518Srobert FileEntryRef NewFile) {
702*12c85518Srobert assert(SourceFile->getSize() == NewFile.getSize() &&
703e5dd7070Spatrick "Different sizes, use the FileManager to create a virtual file with "
704e5dd7070Spatrick "the correct size");
705e5dd7070Spatrick assert(FileInfos.count(SourceFile) == 0 &&
706e5dd7070Spatrick "This function should be called at the initialization stage, before "
707e5dd7070Spatrick "any parsing occurs.");
708*12c85518Srobert // FileEntryRef is not default-constructible.
709*12c85518Srobert auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
710*12c85518Srobert std::make_pair(SourceFile, NewFile));
711*12c85518Srobert if (!Pair.second)
712*12c85518Srobert Pair.first->second = NewFile;
713e5dd7070Spatrick }
714e5dd7070Spatrick
715*12c85518Srobert OptionalFileEntryRef
bypassFileContentsOverride(FileEntryRef File)716a9ac8606Spatrick SourceManager::bypassFileContentsOverride(FileEntryRef File) {
717a9ac8606Spatrick assert(isFileOverridden(&File.getFileEntry()));
718*12c85518Srobert OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
719e5dd7070Spatrick
720e5dd7070Spatrick // If the file can't be found in the FS, give up.
721e5dd7070Spatrick if (!BypassFile)
722*12c85518Srobert return std::nullopt;
723e5dd7070Spatrick
724a9ac8606Spatrick (void)getOrCreateContentCache(*BypassFile);
725a9ac8606Spatrick return BypassFile;
726e5dd7070Spatrick }
727e5dd7070Spatrick
setFileIsTransient(const FileEntry * File)728e5dd7070Spatrick void SourceManager::setFileIsTransient(const FileEntry *File) {
729a9ac8606Spatrick getOrCreateContentCache(File->getLastRef()).IsTransient = true;
730e5dd7070Spatrick }
731e5dd7070Spatrick
732*12c85518Srobert std::optional<StringRef>
getNonBuiltinFilenameForID(FileID FID) const733a9ac8606Spatrick SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
734a9ac8606Spatrick if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
735a9ac8606Spatrick if (Entry->getFile().getContentCache().OrigEntry)
736a9ac8606Spatrick return Entry->getFile().getName();
737*12c85518Srobert return std::nullopt;
738ec727ea7Spatrick }
739ec727ea7Spatrick
getBufferData(FileID FID,bool * Invalid) const740e5dd7070Spatrick StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
741a9ac8606Spatrick auto B = getBufferDataOrNone(FID);
742e5dd7070Spatrick if (Invalid)
743a9ac8606Spatrick *Invalid = !B;
744a9ac8606Spatrick return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
745e5dd7070Spatrick }
746e5dd7070Spatrick
747*12c85518Srobert std::optional<StringRef>
getBufferDataIfLoaded(FileID FID) const748a9ac8606Spatrick SourceManager::getBufferDataIfLoaded(FileID FID) const {
749a9ac8606Spatrick if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
750a9ac8606Spatrick return Entry->getFile().getContentCache().getBufferDataIfLoaded();
751*12c85518Srobert return std::nullopt;
752a9ac8606Spatrick }
753e5dd7070Spatrick
getBufferDataOrNone(FileID FID) const754*12c85518Srobert std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
755a9ac8606Spatrick if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
756a9ac8606Spatrick if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
757a9ac8606Spatrick Diag, getFileManager(), SourceLocation()))
758a9ac8606Spatrick return B->getBuffer();
759*12c85518Srobert return std::nullopt;
760e5dd7070Spatrick }
761e5dd7070Spatrick
762e5dd7070Spatrick //===----------------------------------------------------------------------===//
763e5dd7070Spatrick // SourceLocation manipulation methods.
764e5dd7070Spatrick //===----------------------------------------------------------------------===//
765e5dd7070Spatrick
766e5dd7070Spatrick /// Return the FileID for a SourceLocation.
767e5dd7070Spatrick ///
768e5dd7070Spatrick /// This is the cache-miss path of getFileID. Not as hot as that function, but
769e5dd7070Spatrick /// still very important. It is responsible for finding the entry in the
770e5dd7070Spatrick /// SLocEntry tables that contains the specified location.
getFileIDSlow(SourceLocation::UIntTy SLocOffset) const771a9ac8606Spatrick FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
772e5dd7070Spatrick if (!SLocOffset)
773e5dd7070Spatrick return FileID::get(0);
774e5dd7070Spatrick
775e5dd7070Spatrick // Now it is time to search for the correct file. See where the SLocOffset
776e5dd7070Spatrick // sits in the global view and consult local or loaded buffers for it.
777e5dd7070Spatrick if (SLocOffset < NextLocalOffset)
778e5dd7070Spatrick return getFileIDLocal(SLocOffset);
779e5dd7070Spatrick return getFileIDLoaded(SLocOffset);
780e5dd7070Spatrick }
781e5dd7070Spatrick
782e5dd7070Spatrick /// Return the FileID for a SourceLocation with a low offset.
783e5dd7070Spatrick ///
784e5dd7070Spatrick /// This function knows that the SourceLocation is in a local buffer, not a
785e5dd7070Spatrick /// loaded one.
getFileIDLocal(SourceLocation::UIntTy SLocOffset) const786a9ac8606Spatrick FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
787e5dd7070Spatrick assert(SLocOffset < NextLocalOffset && "Bad function choice");
788e5dd7070Spatrick
789e5dd7070Spatrick // After the first and second level caches, I see two common sorts of
790e5dd7070Spatrick // behavior: 1) a lot of searched FileID's are "near" the cached file
791e5dd7070Spatrick // location or are "near" the cached expansion location. 2) others are just
792e5dd7070Spatrick // completely random and may be a very long way away.
793e5dd7070Spatrick //
794e5dd7070Spatrick // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
795e5dd7070Spatrick // then we fall back to a less cache efficient, but more scalable, binary
796e5dd7070Spatrick // search to find the location.
797e5dd7070Spatrick
798e5dd7070Spatrick // See if this is near the file point - worst case we start scanning from the
799e5dd7070Spatrick // most newly created FileID.
800e5dd7070Spatrick
801*12c85518Srobert // LessIndex - This is the lower bound of the range that we're searching.
802*12c85518Srobert // We know that the offset corresponding to the FileID is less than
803*12c85518Srobert // SLocOffset.
804*12c85518Srobert unsigned LessIndex = 0;
805*12c85518Srobert // upper bound of the search range.
806*12c85518Srobert unsigned GreaterIndex = LocalSLocEntryTable.size();
807*12c85518Srobert if (LastFileIDLookup.ID >= 0) {
808*12c85518Srobert // Use the LastFileIDLookup to prune the search space.
809*12c85518Srobert if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
810*12c85518Srobert LessIndex = LastFileIDLookup.ID;
811*12c85518Srobert else
812*12c85518Srobert GreaterIndex = LastFileIDLookup.ID;
813e5dd7070Spatrick }
814e5dd7070Spatrick
815*12c85518Srobert // Find the FileID that contains this.
816e5dd7070Spatrick unsigned NumProbes = 0;
817e5dd7070Spatrick while (true) {
818*12c85518Srobert --GreaterIndex;
819*12c85518Srobert assert(GreaterIndex < LocalSLocEntryTable.size());
820*12c85518Srobert if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
821*12c85518Srobert FileID Res = FileID::get(int(GreaterIndex));
822ec727ea7Spatrick // Remember it. We have good locality across FileID lookups.
823e5dd7070Spatrick LastFileIDLookup = Res;
824e5dd7070Spatrick NumLinearScans += NumProbes+1;
825e5dd7070Spatrick return Res;
826e5dd7070Spatrick }
827e5dd7070Spatrick if (++NumProbes == 8)
828e5dd7070Spatrick break;
829e5dd7070Spatrick }
830e5dd7070Spatrick
831e5dd7070Spatrick NumProbes = 0;
832e5dd7070Spatrick while (true) {
833e5dd7070Spatrick unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
834a9ac8606Spatrick SourceLocation::UIntTy MidOffset =
835a9ac8606Spatrick getLocalSLocEntry(MiddleIndex).getOffset();
836e5dd7070Spatrick
837e5dd7070Spatrick ++NumProbes;
838e5dd7070Spatrick
839e5dd7070Spatrick // If the offset of the midpoint is too large, chop the high side of the
840e5dd7070Spatrick // range to the midpoint.
841e5dd7070Spatrick if (MidOffset > SLocOffset) {
842e5dd7070Spatrick GreaterIndex = MiddleIndex;
843e5dd7070Spatrick continue;
844e5dd7070Spatrick }
845e5dd7070Spatrick
846e5dd7070Spatrick // If the middle index contains the value, succeed and return.
847ec727ea7Spatrick if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
848ec727ea7Spatrick SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
849e5dd7070Spatrick FileID Res = FileID::get(MiddleIndex);
850e5dd7070Spatrick
851ec727ea7Spatrick // Remember it. We have good locality across FileID lookups.
852e5dd7070Spatrick LastFileIDLookup = Res;
853e5dd7070Spatrick NumBinaryProbes += NumProbes;
854e5dd7070Spatrick return Res;
855e5dd7070Spatrick }
856e5dd7070Spatrick
857e5dd7070Spatrick // Otherwise, move the low-side up to the middle index.
858e5dd7070Spatrick LessIndex = MiddleIndex;
859e5dd7070Spatrick }
860e5dd7070Spatrick }
861e5dd7070Spatrick
862e5dd7070Spatrick /// Return the FileID for a SourceLocation with a high offset.
863e5dd7070Spatrick ///
864e5dd7070Spatrick /// This function knows that the SourceLocation is in a loaded buffer, not a
865e5dd7070Spatrick /// local one.
getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const866a9ac8606Spatrick FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
867e5dd7070Spatrick if (SLocOffset < CurrentLoadedOffset) {
868e5dd7070Spatrick assert(0 && "Invalid SLocOffset or bad function choice");
869e5dd7070Spatrick return FileID();
870e5dd7070Spatrick }
871e5dd7070Spatrick
872e5dd7070Spatrick // Essentially the same as the local case, but the loaded array is sorted
873*12c85518Srobert // in the other direction (decreasing order).
874*12c85518Srobert // GreaterIndex is the one where the offset is greater, which is actually a
875*12c85518Srobert // lower index!
876*12c85518Srobert unsigned GreaterIndex = 0;
877*12c85518Srobert unsigned LessIndex = LoadedSLocEntryTable.size();
878*12c85518Srobert if (LastFileIDLookup.ID < 0) {
879*12c85518Srobert // Prune the search space.
880*12c85518Srobert int LastID = LastFileIDLookup.ID;
881*12c85518Srobert if (getLoadedSLocEntryByID(LastID).getOffset() > SLocOffset)
882*12c85518Srobert GreaterIndex =
883*12c85518Srobert (-LastID - 2) + 1; // Exclude LastID, else we would have hit the cache
884*12c85518Srobert else
885*12c85518Srobert LessIndex = -LastID - 2;
886*12c85518Srobert }
887e5dd7070Spatrick
888e5dd7070Spatrick // First do a linear scan from the last lookup position, if possible.
889e5dd7070Spatrick unsigned NumProbes;
890*12c85518Srobert bool Invalid = false;
891*12c85518Srobert for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
892e5dd7070Spatrick // Make sure the entry is loaded!
893*12c85518Srobert const SrcMgr::SLocEntry &E = getLoadedSLocEntry(GreaterIndex, &Invalid);
894*12c85518Srobert if (Invalid)
895*12c85518Srobert return FileID(); // invalid entry.
896e5dd7070Spatrick if (E.getOffset() <= SLocOffset) {
897*12c85518Srobert FileID Res = FileID::get(-int(GreaterIndex) - 2);
898e5dd7070Spatrick LastFileIDLookup = Res;
899e5dd7070Spatrick NumLinearScans += NumProbes + 1;
900e5dd7070Spatrick return Res;
901e5dd7070Spatrick }
902e5dd7070Spatrick }
903e5dd7070Spatrick
904*12c85518Srobert // Linear scan failed. Do the binary search.
905e5dd7070Spatrick NumProbes = 0;
906e5dd7070Spatrick while (true) {
907e5dd7070Spatrick ++NumProbes;
908e5dd7070Spatrick unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
909*12c85518Srobert const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex, &Invalid);
910*12c85518Srobert if (Invalid)
911e5dd7070Spatrick return FileID(); // invalid entry.
912e5dd7070Spatrick
913e5dd7070Spatrick if (E.getOffset() > SLocOffset) {
914e5dd7070Spatrick if (GreaterIndex == MiddleIndex) {
915e5dd7070Spatrick assert(0 && "binary search missed the entry");
916e5dd7070Spatrick return FileID();
917e5dd7070Spatrick }
918e5dd7070Spatrick GreaterIndex = MiddleIndex;
919e5dd7070Spatrick continue;
920e5dd7070Spatrick }
921e5dd7070Spatrick
922e5dd7070Spatrick if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
923e5dd7070Spatrick FileID Res = FileID::get(-int(MiddleIndex) - 2);
924e5dd7070Spatrick LastFileIDLookup = Res;
925e5dd7070Spatrick NumBinaryProbes += NumProbes;
926e5dd7070Spatrick return Res;
927e5dd7070Spatrick }
928e5dd7070Spatrick
929e5dd7070Spatrick if (LessIndex == MiddleIndex) {
930e5dd7070Spatrick assert(0 && "binary search missed the entry");
931e5dd7070Spatrick return FileID();
932e5dd7070Spatrick }
933e5dd7070Spatrick LessIndex = MiddleIndex;
934e5dd7070Spatrick }
935e5dd7070Spatrick }
936e5dd7070Spatrick
937e5dd7070Spatrick SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const938e5dd7070Spatrick getExpansionLocSlowCase(SourceLocation Loc) const {
939e5dd7070Spatrick do {
940e5dd7070Spatrick // Note: If Loc indicates an offset into a token that came from a macro
941e5dd7070Spatrick // expansion (e.g. the 5th character of the token) we do not want to add
942e5dd7070Spatrick // this offset when going to the expansion location. The expansion
943e5dd7070Spatrick // location is the macro invocation, which the offset has nothing to do
944e5dd7070Spatrick // with. This is unlike when we get the spelling loc, because the offset
945e5dd7070Spatrick // directly correspond to the token whose spelling we're inspecting.
946e5dd7070Spatrick Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
947e5dd7070Spatrick } while (!Loc.isFileID());
948e5dd7070Spatrick
949e5dd7070Spatrick return Loc;
950e5dd7070Spatrick }
951e5dd7070Spatrick
getSpellingLocSlowCase(SourceLocation Loc) const952e5dd7070Spatrick SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
953e5dd7070Spatrick do {
954e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
955e5dd7070Spatrick Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
956e5dd7070Spatrick Loc = Loc.getLocWithOffset(LocInfo.second);
957e5dd7070Spatrick } while (!Loc.isFileID());
958e5dd7070Spatrick return Loc;
959e5dd7070Spatrick }
960e5dd7070Spatrick
getFileLocSlowCase(SourceLocation Loc) const961e5dd7070Spatrick SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
962e5dd7070Spatrick do {
963e5dd7070Spatrick if (isMacroArgExpansion(Loc))
964e5dd7070Spatrick Loc = getImmediateSpellingLoc(Loc);
965e5dd7070Spatrick else
966e5dd7070Spatrick Loc = getImmediateExpansionRange(Loc).getBegin();
967e5dd7070Spatrick } while (!Loc.isFileID());
968e5dd7070Spatrick return Loc;
969e5dd7070Spatrick }
970e5dd7070Spatrick
971e5dd7070Spatrick
972e5dd7070Spatrick std::pair<FileID, unsigned>
getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry * E) const973e5dd7070Spatrick SourceManager::getDecomposedExpansionLocSlowCase(
974e5dd7070Spatrick const SrcMgr::SLocEntry *E) const {
975e5dd7070Spatrick // If this is an expansion record, walk through all the expansion points.
976e5dd7070Spatrick FileID FID;
977e5dd7070Spatrick SourceLocation Loc;
978e5dd7070Spatrick unsigned Offset;
979e5dd7070Spatrick do {
980e5dd7070Spatrick Loc = E->getExpansion().getExpansionLocStart();
981e5dd7070Spatrick
982e5dd7070Spatrick FID = getFileID(Loc);
983e5dd7070Spatrick E = &getSLocEntry(FID);
984e5dd7070Spatrick Offset = Loc.getOffset()-E->getOffset();
985e5dd7070Spatrick } while (!Loc.isFileID());
986e5dd7070Spatrick
987e5dd7070Spatrick return std::make_pair(FID, Offset);
988e5dd7070Spatrick }
989e5dd7070Spatrick
990e5dd7070Spatrick std::pair<FileID, unsigned>
getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry * E,unsigned Offset) const991e5dd7070Spatrick SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
992e5dd7070Spatrick unsigned Offset) const {
993e5dd7070Spatrick // If this is an expansion record, walk through all the expansion points.
994e5dd7070Spatrick FileID FID;
995e5dd7070Spatrick SourceLocation Loc;
996e5dd7070Spatrick do {
997e5dd7070Spatrick Loc = E->getExpansion().getSpellingLoc();
998e5dd7070Spatrick Loc = Loc.getLocWithOffset(Offset);
999e5dd7070Spatrick
1000e5dd7070Spatrick FID = getFileID(Loc);
1001e5dd7070Spatrick E = &getSLocEntry(FID);
1002e5dd7070Spatrick Offset = Loc.getOffset()-E->getOffset();
1003e5dd7070Spatrick } while (!Loc.isFileID());
1004e5dd7070Spatrick
1005e5dd7070Spatrick return std::make_pair(FID, Offset);
1006e5dd7070Spatrick }
1007e5dd7070Spatrick
1008e5dd7070Spatrick /// getImmediateSpellingLoc - Given a SourceLocation object, return the
1009e5dd7070Spatrick /// spelling location referenced by the ID. This is the first level down
1010e5dd7070Spatrick /// towards the place where the characters that make up the lexed token can be
1011e5dd7070Spatrick /// found. This should not generally be used by clients.
getImmediateSpellingLoc(SourceLocation Loc) const1012e5dd7070Spatrick SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
1013e5dd7070Spatrick if (Loc.isFileID()) return Loc;
1014e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1015e5dd7070Spatrick Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1016e5dd7070Spatrick return Loc.getLocWithOffset(LocInfo.second);
1017e5dd7070Spatrick }
1018e5dd7070Spatrick
1019ec727ea7Spatrick /// Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc) const1020ec727ea7Spatrick StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1021ec727ea7Spatrick if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1022ec727ea7Spatrick return F->getName();
1023ec727ea7Spatrick return StringRef();
1024ec727ea7Spatrick }
1025ec727ea7Spatrick
1026e5dd7070Spatrick /// getImmediateExpansionRange - Loc is required to be an expansion location.
1027e5dd7070Spatrick /// Return the start/end of the expansion information.
1028e5dd7070Spatrick CharSourceRange
getImmediateExpansionRange(SourceLocation Loc) const1029e5dd7070Spatrick SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
1030e5dd7070Spatrick assert(Loc.isMacroID() && "Not a macro expansion loc!");
1031e5dd7070Spatrick const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1032e5dd7070Spatrick return Expansion.getExpansionLocRange();
1033e5dd7070Spatrick }
1034e5dd7070Spatrick
getTopMacroCallerLoc(SourceLocation Loc) const1035e5dd7070Spatrick SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1036e5dd7070Spatrick while (isMacroArgExpansion(Loc))
1037e5dd7070Spatrick Loc = getImmediateSpellingLoc(Loc);
1038e5dd7070Spatrick return Loc;
1039e5dd7070Spatrick }
1040e5dd7070Spatrick
1041e5dd7070Spatrick /// getExpansionRange - Given a SourceLocation object, return the range of
1042e5dd7070Spatrick /// tokens covered by the expansion in the ultimate file.
getExpansionRange(SourceLocation Loc) const1043e5dd7070Spatrick CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1044e5dd7070Spatrick if (Loc.isFileID())
1045e5dd7070Spatrick return CharSourceRange(SourceRange(Loc, Loc), true);
1046e5dd7070Spatrick
1047e5dd7070Spatrick CharSourceRange Res = getImmediateExpansionRange(Loc);
1048e5dd7070Spatrick
1049e5dd7070Spatrick // Fully resolve the start and end locations to their ultimate expansion
1050e5dd7070Spatrick // points.
1051e5dd7070Spatrick while (!Res.getBegin().isFileID())
1052e5dd7070Spatrick Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1053e5dd7070Spatrick while (!Res.getEnd().isFileID()) {
1054e5dd7070Spatrick CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1055e5dd7070Spatrick Res.setEnd(EndRange.getEnd());
1056e5dd7070Spatrick Res.setTokenRange(EndRange.isTokenRange());
1057e5dd7070Spatrick }
1058e5dd7070Spatrick return Res;
1059e5dd7070Spatrick }
1060e5dd7070Spatrick
isMacroArgExpansion(SourceLocation Loc,SourceLocation * StartLoc) const1061e5dd7070Spatrick bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1062e5dd7070Spatrick SourceLocation *StartLoc) const {
1063e5dd7070Spatrick if (!Loc.isMacroID()) return false;
1064e5dd7070Spatrick
1065e5dd7070Spatrick FileID FID = getFileID(Loc);
1066e5dd7070Spatrick const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1067e5dd7070Spatrick if (!Expansion.isMacroArgExpansion()) return false;
1068e5dd7070Spatrick
1069e5dd7070Spatrick if (StartLoc)
1070e5dd7070Spatrick *StartLoc = Expansion.getExpansionLocStart();
1071e5dd7070Spatrick return true;
1072e5dd7070Spatrick }
1073e5dd7070Spatrick
isMacroBodyExpansion(SourceLocation Loc) const1074e5dd7070Spatrick bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1075e5dd7070Spatrick if (!Loc.isMacroID()) return false;
1076e5dd7070Spatrick
1077e5dd7070Spatrick FileID FID = getFileID(Loc);
1078e5dd7070Spatrick const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1079e5dd7070Spatrick return Expansion.isMacroBodyExpansion();
1080e5dd7070Spatrick }
1081e5dd7070Spatrick
isAtStartOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroBegin) const1082e5dd7070Spatrick bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1083e5dd7070Spatrick SourceLocation *MacroBegin) const {
1084e5dd7070Spatrick assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1085e5dd7070Spatrick
1086e5dd7070Spatrick std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1087e5dd7070Spatrick if (DecompLoc.second > 0)
1088e5dd7070Spatrick return false; // Does not point at the start of expansion range.
1089e5dd7070Spatrick
1090e5dd7070Spatrick bool Invalid = false;
1091e5dd7070Spatrick const SrcMgr::ExpansionInfo &ExpInfo =
1092e5dd7070Spatrick getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1093e5dd7070Spatrick if (Invalid)
1094e5dd7070Spatrick return false;
1095e5dd7070Spatrick SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1096e5dd7070Spatrick
1097e5dd7070Spatrick if (ExpInfo.isMacroArgExpansion()) {
1098e5dd7070Spatrick // For macro argument expansions, check if the previous FileID is part of
1099e5dd7070Spatrick // the same argument expansion, in which case this Loc is not at the
1100e5dd7070Spatrick // beginning of the expansion.
1101e5dd7070Spatrick FileID PrevFID = getPreviousFileID(DecompLoc.first);
1102e5dd7070Spatrick if (!PrevFID.isInvalid()) {
1103e5dd7070Spatrick const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1104e5dd7070Spatrick if (Invalid)
1105e5dd7070Spatrick return false;
1106e5dd7070Spatrick if (PrevEntry.isExpansion() &&
1107e5dd7070Spatrick PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1108e5dd7070Spatrick return false;
1109e5dd7070Spatrick }
1110e5dd7070Spatrick }
1111e5dd7070Spatrick
1112e5dd7070Spatrick if (MacroBegin)
1113e5dd7070Spatrick *MacroBegin = ExpLoc;
1114e5dd7070Spatrick return true;
1115e5dd7070Spatrick }
1116e5dd7070Spatrick
isAtEndOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroEnd) const1117e5dd7070Spatrick bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1118e5dd7070Spatrick SourceLocation *MacroEnd) const {
1119e5dd7070Spatrick assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1120e5dd7070Spatrick
1121e5dd7070Spatrick FileID FID = getFileID(Loc);
1122e5dd7070Spatrick SourceLocation NextLoc = Loc.getLocWithOffset(1);
1123e5dd7070Spatrick if (isInFileID(NextLoc, FID))
1124e5dd7070Spatrick return false; // Does not point at the end of expansion range.
1125e5dd7070Spatrick
1126e5dd7070Spatrick bool Invalid = false;
1127e5dd7070Spatrick const SrcMgr::ExpansionInfo &ExpInfo =
1128e5dd7070Spatrick getSLocEntry(FID, &Invalid).getExpansion();
1129e5dd7070Spatrick if (Invalid)
1130e5dd7070Spatrick return false;
1131e5dd7070Spatrick
1132e5dd7070Spatrick if (ExpInfo.isMacroArgExpansion()) {
1133e5dd7070Spatrick // For macro argument expansions, check if the next FileID is part of the
1134e5dd7070Spatrick // same argument expansion, in which case this Loc is not at the end of the
1135e5dd7070Spatrick // expansion.
1136e5dd7070Spatrick FileID NextFID = getNextFileID(FID);
1137e5dd7070Spatrick if (!NextFID.isInvalid()) {
1138e5dd7070Spatrick const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1139e5dd7070Spatrick if (Invalid)
1140e5dd7070Spatrick return false;
1141e5dd7070Spatrick if (NextEntry.isExpansion() &&
1142e5dd7070Spatrick NextEntry.getExpansion().getExpansionLocStart() ==
1143e5dd7070Spatrick ExpInfo.getExpansionLocStart())
1144e5dd7070Spatrick return false;
1145e5dd7070Spatrick }
1146e5dd7070Spatrick }
1147e5dd7070Spatrick
1148e5dd7070Spatrick if (MacroEnd)
1149e5dd7070Spatrick *MacroEnd = ExpInfo.getExpansionLocEnd();
1150e5dd7070Spatrick return true;
1151e5dd7070Spatrick }
1152e5dd7070Spatrick
1153e5dd7070Spatrick //===----------------------------------------------------------------------===//
1154e5dd7070Spatrick // Queries about the code at a SourceLocation.
1155e5dd7070Spatrick //===----------------------------------------------------------------------===//
1156e5dd7070Spatrick
1157e5dd7070Spatrick /// getCharacterData - Return a pointer to the start of the specified location
1158e5dd7070Spatrick /// in the appropriate MemoryBuffer.
getCharacterData(SourceLocation SL,bool * Invalid) const1159e5dd7070Spatrick const char *SourceManager::getCharacterData(SourceLocation SL,
1160e5dd7070Spatrick bool *Invalid) const {
1161e5dd7070Spatrick // Note that this is a hot function in the getSpelling() path, which is
1162e5dd7070Spatrick // heavily used by -E mode.
1163e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1164e5dd7070Spatrick
1165e5dd7070Spatrick // Note that calling 'getBuffer()' may lazily page in a source file.
1166e5dd7070Spatrick bool CharDataInvalid = false;
1167e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1168e5dd7070Spatrick if (CharDataInvalid || !Entry.isFile()) {
1169e5dd7070Spatrick if (Invalid)
1170e5dd7070Spatrick *Invalid = true;
1171e5dd7070Spatrick
1172e5dd7070Spatrick return "<<<<INVALID BUFFER>>>>";
1173e5dd7070Spatrick }
1174*12c85518Srobert std::optional<llvm::MemoryBufferRef> Buffer =
1175a9ac8606Spatrick Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1176a9ac8606Spatrick SourceLocation());
1177e5dd7070Spatrick if (Invalid)
1178a9ac8606Spatrick *Invalid = !Buffer;
1179a9ac8606Spatrick return Buffer ? Buffer->getBufferStart() + LocInfo.second
1180a9ac8606Spatrick : "<<<<INVALID BUFFER>>>>";
1181e5dd7070Spatrick }
1182e5dd7070Spatrick
1183e5dd7070Spatrick /// getColumnNumber - Return the column # for the specified file position.
1184e5dd7070Spatrick /// this is significantly cheaper to compute than the line number.
getColumnNumber(FileID FID,unsigned FilePos,bool * Invalid) const1185e5dd7070Spatrick unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1186e5dd7070Spatrick bool *Invalid) const {
1187*12c85518Srobert std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
1188e5dd7070Spatrick if (Invalid)
1189a9ac8606Spatrick *Invalid = !MemBuf;
1190e5dd7070Spatrick
1191a9ac8606Spatrick if (!MemBuf)
1192e5dd7070Spatrick return 1;
1193e5dd7070Spatrick
1194e5dd7070Spatrick // It is okay to request a position just past the end of the buffer.
1195e5dd7070Spatrick if (FilePos > MemBuf->getBufferSize()) {
1196e5dd7070Spatrick if (Invalid)
1197e5dd7070Spatrick *Invalid = true;
1198e5dd7070Spatrick return 1;
1199e5dd7070Spatrick }
1200e5dd7070Spatrick
1201e5dd7070Spatrick const char *Buf = MemBuf->getBufferStart();
1202e5dd7070Spatrick // See if we just calculated the line number for this FilePos and can use
1203e5dd7070Spatrick // that to lookup the start of the line instead of searching for it.
1204a9ac8606Spatrick if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1205a9ac8606Spatrick LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1206a9ac8606Spatrick const unsigned *SourceLineCache =
1207a9ac8606Spatrick LastLineNoContentCache->SourceLineCache.begin();
1208e5dd7070Spatrick unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1209e5dd7070Spatrick unsigned LineEnd = SourceLineCache[LastLineNoResult];
1210e5dd7070Spatrick if (FilePos >= LineStart && FilePos < LineEnd) {
1211e5dd7070Spatrick // LineEnd is the LineStart of the next line.
1212e5dd7070Spatrick // A line ends with separator LF or CR+LF on Windows.
1213e5dd7070Spatrick // FilePos might point to the last separator,
1214e5dd7070Spatrick // but we need a column number at most 1 + the last column.
1215e5dd7070Spatrick if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1216e5dd7070Spatrick if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1217e5dd7070Spatrick --FilePos;
1218e5dd7070Spatrick }
1219e5dd7070Spatrick return FilePos - LineStart + 1;
1220e5dd7070Spatrick }
1221e5dd7070Spatrick }
1222e5dd7070Spatrick
1223e5dd7070Spatrick unsigned LineStart = FilePos;
1224e5dd7070Spatrick while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1225e5dd7070Spatrick --LineStart;
1226e5dd7070Spatrick return FilePos-LineStart+1;
1227e5dd7070Spatrick }
1228e5dd7070Spatrick
1229e5dd7070Spatrick // isInvalid - Return the result of calling loc.isInvalid(), and
1230e5dd7070Spatrick // if Invalid is not null, set its value to same.
1231e5dd7070Spatrick template<typename LocType>
isInvalid(LocType Loc,bool * Invalid)1232e5dd7070Spatrick static bool isInvalid(LocType Loc, bool *Invalid) {
1233e5dd7070Spatrick bool MyInvalid = Loc.isInvalid();
1234e5dd7070Spatrick if (Invalid)
1235e5dd7070Spatrick *Invalid = MyInvalid;
1236e5dd7070Spatrick return MyInvalid;
1237e5dd7070Spatrick }
1238e5dd7070Spatrick
getSpellingColumnNumber(SourceLocation Loc,bool * Invalid) const1239e5dd7070Spatrick unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1240e5dd7070Spatrick bool *Invalid) const {
1241e5dd7070Spatrick if (isInvalid(Loc, Invalid)) return 0;
1242e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1243e5dd7070Spatrick return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1244e5dd7070Spatrick }
1245e5dd7070Spatrick
getExpansionColumnNumber(SourceLocation Loc,bool * Invalid) const1246e5dd7070Spatrick unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1247e5dd7070Spatrick bool *Invalid) const {
1248e5dd7070Spatrick if (isInvalid(Loc, Invalid)) return 0;
1249e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1250e5dd7070Spatrick return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1251e5dd7070Spatrick }
1252e5dd7070Spatrick
getPresumedColumnNumber(SourceLocation Loc,bool * Invalid) const1253e5dd7070Spatrick unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1254e5dd7070Spatrick bool *Invalid) const {
1255e5dd7070Spatrick PresumedLoc PLoc = getPresumedLoc(Loc);
1256e5dd7070Spatrick if (isInvalid(PLoc, Invalid)) return 0;
1257e5dd7070Spatrick return PLoc.getColumn();
1258e5dd7070Spatrick }
1259e5dd7070Spatrick
1260a9ac8606Spatrick // Check if mutli-byte word x has bytes between m and n, included. This may also
1261a9ac8606Spatrick // catch bytes equal to n + 1.
1262a9ac8606Spatrick // The returned value holds a 0x80 at each byte position that holds a match.
1263a9ac8606Spatrick // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1264a9ac8606Spatrick template <class T>
likelyhasbetween(T x,unsigned char m,unsigned char n)1265a9ac8606Spatrick static constexpr inline T likelyhasbetween(T x, unsigned char m,
1266a9ac8606Spatrick unsigned char n) {
1267a9ac8606Spatrick return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1268a9ac8606Spatrick ((x & ~static_cast<T>(0) / 255 * 127) +
1269a9ac8606Spatrick (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1270a9ac8606Spatrick ~static_cast<T>(0) / 255 * 128;
1271a9ac8606Spatrick }
1272e5dd7070Spatrick
get(llvm::MemoryBufferRef Buffer,llvm::BumpPtrAllocator & Alloc)1273a9ac8606Spatrick LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1274a9ac8606Spatrick llvm::BumpPtrAllocator &Alloc) {
1275e5dd7070Spatrick
1276e5dd7070Spatrick // Find the file offsets of all of the *physical* source lines. This does
1277e5dd7070Spatrick // not look at trigraphs, escaped newlines, or anything else tricky.
1278e5dd7070Spatrick SmallVector<unsigned, 256> LineOffsets;
1279e5dd7070Spatrick
1280e5dd7070Spatrick // Line #1 starts at char 0.
1281e5dd7070Spatrick LineOffsets.push_back(0);
1282e5dd7070Spatrick
1283*12c85518Srobert const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();
1284a9ac8606Spatrick const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1285*12c85518Srobert const unsigned char *Buf = Start;
1286a9ac8606Spatrick
1287a9ac8606Spatrick uint64_t Word;
1288a9ac8606Spatrick
1289a9ac8606Spatrick // scan sizeof(Word) bytes at a time for new lines.
1290a9ac8606Spatrick // This is much faster than scanning each byte independently.
1291*12c85518Srobert if ((unsigned long)(End - Start) > sizeof(Word)) {
1292a9ac8606Spatrick do {
1293*12c85518Srobert Word = llvm::support::endian::read64(Buf, llvm::support::little);
1294a9ac8606Spatrick // no new line => jump over sizeof(Word) bytes.
1295a9ac8606Spatrick auto Mask = likelyhasbetween(Word, '\n', '\r');
1296a9ac8606Spatrick if (!Mask) {
1297*12c85518Srobert Buf += sizeof(Word);
1298a9ac8606Spatrick continue;
1299a9ac8606Spatrick }
1300a9ac8606Spatrick
1301a9ac8606Spatrick // At that point, Mask contains 0x80 set at each byte that holds a value
1302a9ac8606Spatrick // in [\n, \r + 1 [
1303a9ac8606Spatrick
1304a9ac8606Spatrick // Scan for the next newline - it's very likely there's one.
1305a9ac8606Spatrick unsigned N =
1306a9ac8606Spatrick llvm::countTrailingZeros(Mask) - 7; // -7 because 0x80 is the marker
1307a9ac8606Spatrick Word >>= N;
1308*12c85518Srobert Buf += N / 8 + 1;
1309a9ac8606Spatrick unsigned char Byte = Word;
1310*12c85518Srobert switch (Byte) {
1311*12c85518Srobert case '\r':
1312a9ac8606Spatrick // If this is \r\n, skip both characters.
1313*12c85518Srobert if (*Buf == '\n') {
1314*12c85518Srobert ++Buf;
1315a9ac8606Spatrick }
1316*12c85518Srobert LLVM_FALLTHROUGH;
1317*12c85518Srobert case '\n':
1318*12c85518Srobert LineOffsets.push_back(Buf - Start);
1319*12c85518Srobert };
1320*12c85518Srobert } while (Buf < End - sizeof(Word) - 1);
1321a9ac8606Spatrick }
1322a9ac8606Spatrick
1323a9ac8606Spatrick // Handle tail using a regular check.
1324*12c85518Srobert while (Buf < End) {
1325*12c85518Srobert if (*Buf == '\n') {
1326*12c85518Srobert LineOffsets.push_back(Buf - Start + 1);
1327*12c85518Srobert } else if (*Buf == '\r') {
1328e5dd7070Spatrick // If this is \r\n, skip both characters.
1329*12c85518Srobert if (Buf + 1 < End && Buf[1] == '\n') {
1330*12c85518Srobert ++Buf;
1331e5dd7070Spatrick }
1332*12c85518Srobert LineOffsets.push_back(Buf - Start + 1);
1333*12c85518Srobert }
1334*12c85518Srobert ++Buf;
1335e5dd7070Spatrick }
1336e5dd7070Spatrick
1337a9ac8606Spatrick return LineOffsetMapping(LineOffsets, Alloc);
1338a9ac8606Spatrick }
1339a9ac8606Spatrick
LineOffsetMapping(ArrayRef<unsigned> LineOffsets,llvm::BumpPtrAllocator & Alloc)1340a9ac8606Spatrick LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1341a9ac8606Spatrick llvm::BumpPtrAllocator &Alloc)
1342a9ac8606Spatrick : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1343a9ac8606Spatrick Storage[0] = LineOffsets.size();
1344a9ac8606Spatrick std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1345e5dd7070Spatrick }
1346e5dd7070Spatrick
1347e5dd7070Spatrick /// getLineNumber - Given a SourceLocation, return the spelling line number
1348e5dd7070Spatrick /// for the position indicated. This requires building and caching a table of
1349e5dd7070Spatrick /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1350e5dd7070Spatrick /// about to emit a diagnostic.
getLineNumber(FileID FID,unsigned FilePos,bool * Invalid) const1351e5dd7070Spatrick unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1352e5dd7070Spatrick bool *Invalid) const {
1353e5dd7070Spatrick if (FID.isInvalid()) {
1354e5dd7070Spatrick if (Invalid)
1355e5dd7070Spatrick *Invalid = true;
1356e5dd7070Spatrick return 1;
1357e5dd7070Spatrick }
1358e5dd7070Spatrick
1359a9ac8606Spatrick const ContentCache *Content;
1360e5dd7070Spatrick if (LastLineNoFileIDQuery == FID)
1361e5dd7070Spatrick Content = LastLineNoContentCache;
1362e5dd7070Spatrick else {
1363e5dd7070Spatrick bool MyInvalid = false;
1364e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1365e5dd7070Spatrick if (MyInvalid || !Entry.isFile()) {
1366e5dd7070Spatrick if (Invalid)
1367e5dd7070Spatrick *Invalid = true;
1368e5dd7070Spatrick return 1;
1369e5dd7070Spatrick }
1370e5dd7070Spatrick
1371a9ac8606Spatrick Content = &Entry.getFile().getContentCache();
1372e5dd7070Spatrick }
1373e5dd7070Spatrick
1374e5dd7070Spatrick // If this is the first use of line information for this buffer, compute the
1375e5dd7070Spatrick /// SourceLineCache for it on demand.
1376e5dd7070Spatrick if (!Content->SourceLineCache) {
1377*12c85518Srobert std::optional<llvm::MemoryBufferRef> Buffer =
1378a9ac8606Spatrick Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
1379e5dd7070Spatrick if (Invalid)
1380a9ac8606Spatrick *Invalid = !Buffer;
1381a9ac8606Spatrick if (!Buffer)
1382e5dd7070Spatrick return 1;
1383a9ac8606Spatrick
1384a9ac8606Spatrick Content->SourceLineCache =
1385a9ac8606Spatrick LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1386e5dd7070Spatrick } else if (Invalid)
1387e5dd7070Spatrick *Invalid = false;
1388e5dd7070Spatrick
1389e5dd7070Spatrick // Okay, we know we have a line number table. Do a binary search to find the
1390e5dd7070Spatrick // line number that this character position lands on.
1391a9ac8606Spatrick const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1392a9ac8606Spatrick const unsigned *SourceLineCacheStart = SourceLineCache;
1393a9ac8606Spatrick const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1394e5dd7070Spatrick
1395e5dd7070Spatrick unsigned QueriedFilePos = FilePos+1;
1396e5dd7070Spatrick
1397e5dd7070Spatrick // FIXME: I would like to be convinced that this code is worth being as
1398e5dd7070Spatrick // complicated as it is, binary search isn't that slow.
1399e5dd7070Spatrick //
1400e5dd7070Spatrick // If it is worth being optimized, then in my opinion it could be more
1401e5dd7070Spatrick // performant, simpler, and more obviously correct by just "galloping" outward
1402e5dd7070Spatrick // from the queried file position. In fact, this could be incorporated into a
1403e5dd7070Spatrick // generic algorithm such as lower_bound_with_hint.
1404e5dd7070Spatrick //
1405e5dd7070Spatrick // If someone gives me a test case where this matters, and I will do it! - DWD
1406e5dd7070Spatrick
1407e5dd7070Spatrick // If the previous query was to the same file, we know both the file pos from
1408e5dd7070Spatrick // that query and the line number returned. This allows us to narrow the
1409e5dd7070Spatrick // search space from the entire file to something near the match.
1410e5dd7070Spatrick if (LastLineNoFileIDQuery == FID) {
1411e5dd7070Spatrick if (QueriedFilePos >= LastLineNoFilePos) {
1412e5dd7070Spatrick // FIXME: Potential overflow?
1413e5dd7070Spatrick SourceLineCache = SourceLineCache+LastLineNoResult-1;
1414e5dd7070Spatrick
1415e5dd7070Spatrick // The query is likely to be nearby the previous one. Here we check to
1416e5dd7070Spatrick // see if it is within 5, 10 or 20 lines. It can be far away in cases
1417e5dd7070Spatrick // where big comment blocks and vertical whitespace eat up lines but
1418e5dd7070Spatrick // contribute no tokens.
1419e5dd7070Spatrick if (SourceLineCache+5 < SourceLineCacheEnd) {
1420e5dd7070Spatrick if (SourceLineCache[5] > QueriedFilePos)
1421e5dd7070Spatrick SourceLineCacheEnd = SourceLineCache+5;
1422e5dd7070Spatrick else if (SourceLineCache+10 < SourceLineCacheEnd) {
1423e5dd7070Spatrick if (SourceLineCache[10] > QueriedFilePos)
1424e5dd7070Spatrick SourceLineCacheEnd = SourceLineCache+10;
1425e5dd7070Spatrick else if (SourceLineCache+20 < SourceLineCacheEnd) {
1426e5dd7070Spatrick if (SourceLineCache[20] > QueriedFilePos)
1427e5dd7070Spatrick SourceLineCacheEnd = SourceLineCache+20;
1428e5dd7070Spatrick }
1429e5dd7070Spatrick }
1430e5dd7070Spatrick }
1431e5dd7070Spatrick } else {
1432a9ac8606Spatrick if (LastLineNoResult < Content->SourceLineCache.size())
1433e5dd7070Spatrick SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1434e5dd7070Spatrick }
1435e5dd7070Spatrick }
1436e5dd7070Spatrick
1437a9ac8606Spatrick const unsigned *Pos =
1438a9ac8606Spatrick std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1439e5dd7070Spatrick unsigned LineNo = Pos-SourceLineCacheStart;
1440e5dd7070Spatrick
1441e5dd7070Spatrick LastLineNoFileIDQuery = FID;
1442e5dd7070Spatrick LastLineNoContentCache = Content;
1443e5dd7070Spatrick LastLineNoFilePos = QueriedFilePos;
1444e5dd7070Spatrick LastLineNoResult = LineNo;
1445e5dd7070Spatrick return LineNo;
1446e5dd7070Spatrick }
1447e5dd7070Spatrick
getSpellingLineNumber(SourceLocation Loc,bool * Invalid) const1448e5dd7070Spatrick unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1449e5dd7070Spatrick bool *Invalid) const {
1450e5dd7070Spatrick if (isInvalid(Loc, Invalid)) return 0;
1451e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1452e5dd7070Spatrick return getLineNumber(LocInfo.first, LocInfo.second);
1453e5dd7070Spatrick }
getExpansionLineNumber(SourceLocation Loc,bool * Invalid) const1454e5dd7070Spatrick unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1455e5dd7070Spatrick bool *Invalid) const {
1456e5dd7070Spatrick if (isInvalid(Loc, Invalid)) return 0;
1457e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1458e5dd7070Spatrick return getLineNumber(LocInfo.first, LocInfo.second);
1459e5dd7070Spatrick }
getPresumedLineNumber(SourceLocation Loc,bool * Invalid) const1460e5dd7070Spatrick unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1461e5dd7070Spatrick bool *Invalid) const {
1462e5dd7070Spatrick PresumedLoc PLoc = getPresumedLoc(Loc);
1463e5dd7070Spatrick if (isInvalid(PLoc, Invalid)) return 0;
1464e5dd7070Spatrick return PLoc.getLine();
1465e5dd7070Spatrick }
1466e5dd7070Spatrick
1467e5dd7070Spatrick /// getFileCharacteristic - return the file characteristic of the specified
1468e5dd7070Spatrick /// source location, indicating whether this is a normal file, a system
1469e5dd7070Spatrick /// header, or an "implicit extern C" system header.
1470e5dd7070Spatrick ///
1471e5dd7070Spatrick /// This state can be modified with flags on GNU linemarker directives like:
1472e5dd7070Spatrick /// # 4 "foo.h" 3
1473e5dd7070Spatrick /// which changes all source locations in the current file after that to be
1474e5dd7070Spatrick /// considered to be from a system header.
1475e5dd7070Spatrick SrcMgr::CharacteristicKind
getFileCharacteristic(SourceLocation Loc) const1476e5dd7070Spatrick SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1477e5dd7070Spatrick assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1478e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1479a9ac8606Spatrick const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1480a9ac8606Spatrick if (!SEntry)
1481e5dd7070Spatrick return C_User;
1482e5dd7070Spatrick
1483a9ac8606Spatrick const SrcMgr::FileInfo &FI = SEntry->getFile();
1484e5dd7070Spatrick
1485e5dd7070Spatrick // If there are no #line directives in this file, just return the whole-file
1486e5dd7070Spatrick // state.
1487e5dd7070Spatrick if (!FI.hasLineDirectives())
1488e5dd7070Spatrick return FI.getFileCharacteristic();
1489e5dd7070Spatrick
1490e5dd7070Spatrick assert(LineTable && "Can't have linetable entries without a LineTable!");
1491e5dd7070Spatrick // See if there is a #line directive before the location.
1492e5dd7070Spatrick const LineEntry *Entry =
1493e5dd7070Spatrick LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1494e5dd7070Spatrick
1495e5dd7070Spatrick // If this is before the first line marker, use the file characteristic.
1496e5dd7070Spatrick if (!Entry)
1497e5dd7070Spatrick return FI.getFileCharacteristic();
1498e5dd7070Spatrick
1499e5dd7070Spatrick return Entry->FileKind;
1500e5dd7070Spatrick }
1501e5dd7070Spatrick
1502e5dd7070Spatrick /// Return the filename or buffer identifier of the buffer the location is in.
1503e5dd7070Spatrick /// Note that this name does not respect \#line directives. Use getPresumedLoc
1504e5dd7070Spatrick /// for normal clients.
getBufferName(SourceLocation Loc,bool * Invalid) const1505e5dd7070Spatrick StringRef SourceManager::getBufferName(SourceLocation Loc,
1506e5dd7070Spatrick bool *Invalid) const {
1507e5dd7070Spatrick if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1508e5dd7070Spatrick
1509a9ac8606Spatrick auto B = getBufferOrNone(getFileID(Loc));
1510a9ac8606Spatrick if (Invalid)
1511a9ac8606Spatrick *Invalid = !B;
1512a9ac8606Spatrick return B ? B->getBufferIdentifier() : "<invalid buffer>";
1513e5dd7070Spatrick }
1514e5dd7070Spatrick
1515e5dd7070Spatrick /// getPresumedLoc - This method returns the "presumed" location of a
1516e5dd7070Spatrick /// SourceLocation specifies. A "presumed location" can be modified by \#line
1517e5dd7070Spatrick /// or GNU line marker directives. This provides a view on the data that a
1518e5dd7070Spatrick /// user should see in diagnostics, for example.
1519e5dd7070Spatrick ///
1520e5dd7070Spatrick /// Note that a presumed location is always given as the expansion point of an
1521e5dd7070Spatrick /// expansion location, not at the spelling location.
getPresumedLoc(SourceLocation Loc,bool UseLineDirectives) const1522e5dd7070Spatrick PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1523e5dd7070Spatrick bool UseLineDirectives) const {
1524e5dd7070Spatrick if (Loc.isInvalid()) return PresumedLoc();
1525e5dd7070Spatrick
1526e5dd7070Spatrick // Presumed locations are always for expansion points.
1527e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1528e5dd7070Spatrick
1529e5dd7070Spatrick bool Invalid = false;
1530e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1531e5dd7070Spatrick if (Invalid || !Entry.isFile())
1532e5dd7070Spatrick return PresumedLoc();
1533e5dd7070Spatrick
1534e5dd7070Spatrick const SrcMgr::FileInfo &FI = Entry.getFile();
1535a9ac8606Spatrick const SrcMgr::ContentCache *C = &FI.getContentCache();
1536e5dd7070Spatrick
1537e5dd7070Spatrick // To get the source name, first consult the FileEntry (if one exists)
1538e5dd7070Spatrick // before the MemBuffer as this will avoid unnecessarily paging in the
1539e5dd7070Spatrick // MemBuffer.
1540e5dd7070Spatrick FileID FID = LocInfo.first;
1541e5dd7070Spatrick StringRef Filename;
1542e5dd7070Spatrick if (C->OrigEntry)
1543e5dd7070Spatrick Filename = C->OrigEntry->getName();
1544a9ac8606Spatrick else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1545a9ac8606Spatrick Filename = Buffer->getBufferIdentifier();
1546e5dd7070Spatrick
1547e5dd7070Spatrick unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1548e5dd7070Spatrick if (Invalid)
1549e5dd7070Spatrick return PresumedLoc();
1550e5dd7070Spatrick unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1551e5dd7070Spatrick if (Invalid)
1552e5dd7070Spatrick return PresumedLoc();
1553e5dd7070Spatrick
1554e5dd7070Spatrick SourceLocation IncludeLoc = FI.getIncludeLoc();
1555e5dd7070Spatrick
1556e5dd7070Spatrick // If we have #line directives in this file, update and overwrite the physical
1557e5dd7070Spatrick // location info if appropriate.
1558e5dd7070Spatrick if (UseLineDirectives && FI.hasLineDirectives()) {
1559e5dd7070Spatrick assert(LineTable && "Can't have linetable entries without a LineTable!");
1560e5dd7070Spatrick // See if there is a #line directive before this. If so, get it.
1561e5dd7070Spatrick if (const LineEntry *Entry =
1562e5dd7070Spatrick LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1563e5dd7070Spatrick // If the LineEntry indicates a filename, use it.
1564e5dd7070Spatrick if (Entry->FilenameID != -1) {
1565e5dd7070Spatrick Filename = LineTable->getFilename(Entry->FilenameID);
1566e5dd7070Spatrick // The contents of files referenced by #line are not in the
1567e5dd7070Spatrick // SourceManager
1568e5dd7070Spatrick FID = FileID::get(0);
1569e5dd7070Spatrick }
1570e5dd7070Spatrick
1571e5dd7070Spatrick // Use the line number specified by the LineEntry. This line number may
1572e5dd7070Spatrick // be multiple lines down from the line entry. Add the difference in
1573e5dd7070Spatrick // physical line numbers from the query point and the line marker to the
1574e5dd7070Spatrick // total.
1575e5dd7070Spatrick unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1576e5dd7070Spatrick LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1577e5dd7070Spatrick
1578e5dd7070Spatrick // Note that column numbers are not molested by line markers.
1579e5dd7070Spatrick
1580e5dd7070Spatrick // Handle virtual #include manipulation.
1581e5dd7070Spatrick if (Entry->IncludeOffset) {
1582e5dd7070Spatrick IncludeLoc = getLocForStartOfFile(LocInfo.first);
1583e5dd7070Spatrick IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1584e5dd7070Spatrick }
1585e5dd7070Spatrick }
1586e5dd7070Spatrick }
1587e5dd7070Spatrick
1588e5dd7070Spatrick return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1589e5dd7070Spatrick }
1590e5dd7070Spatrick
1591e5dd7070Spatrick /// Returns whether the PresumedLoc for a given SourceLocation is
1592e5dd7070Spatrick /// in the main file.
1593e5dd7070Spatrick ///
1594e5dd7070Spatrick /// This computes the "presumed" location for a SourceLocation, then checks
1595e5dd7070Spatrick /// whether it came from a file other than the main file. This is different
1596e5dd7070Spatrick /// from isWrittenInMainFile() because it takes line marker directives into
1597e5dd7070Spatrick /// account.
isInMainFile(SourceLocation Loc) const1598e5dd7070Spatrick bool SourceManager::isInMainFile(SourceLocation Loc) const {
1599e5dd7070Spatrick if (Loc.isInvalid()) return false;
1600e5dd7070Spatrick
1601e5dd7070Spatrick // Presumed locations are always for expansion points.
1602e5dd7070Spatrick std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1603e5dd7070Spatrick
1604a9ac8606Spatrick const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1605a9ac8606Spatrick if (!Entry)
1606e5dd7070Spatrick return false;
1607e5dd7070Spatrick
1608a9ac8606Spatrick const SrcMgr::FileInfo &FI = Entry->getFile();
1609e5dd7070Spatrick
1610e5dd7070Spatrick // Check if there is a line directive for this location.
1611e5dd7070Spatrick if (FI.hasLineDirectives())
1612e5dd7070Spatrick if (const LineEntry *Entry =
1613e5dd7070Spatrick LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1614e5dd7070Spatrick if (Entry->IncludeOffset)
1615e5dd7070Spatrick return false;
1616e5dd7070Spatrick
1617e5dd7070Spatrick return FI.getIncludeLoc().isInvalid();
1618e5dd7070Spatrick }
1619e5dd7070Spatrick
1620e5dd7070Spatrick /// The size of the SLocEntry that \p FID represents.
getFileIDSize(FileID FID) const1621e5dd7070Spatrick unsigned SourceManager::getFileIDSize(FileID FID) const {
1622e5dd7070Spatrick bool Invalid = false;
1623e5dd7070Spatrick const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1624e5dd7070Spatrick if (Invalid)
1625e5dd7070Spatrick return 0;
1626e5dd7070Spatrick
1627e5dd7070Spatrick int ID = FID.ID;
1628a9ac8606Spatrick SourceLocation::UIntTy NextOffset;
1629e5dd7070Spatrick if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1630e5dd7070Spatrick NextOffset = getNextLocalOffset();
1631e5dd7070Spatrick else if (ID+1 == -1)
1632e5dd7070Spatrick NextOffset = MaxLoadedOffset;
1633e5dd7070Spatrick else
1634e5dd7070Spatrick NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1635e5dd7070Spatrick
1636e5dd7070Spatrick return NextOffset - Entry.getOffset() - 1;
1637e5dd7070Spatrick }
1638e5dd7070Spatrick
1639e5dd7070Spatrick //===----------------------------------------------------------------------===//
1640e5dd7070Spatrick // Other miscellaneous methods.
1641e5dd7070Spatrick //===----------------------------------------------------------------------===//
1642e5dd7070Spatrick
1643e5dd7070Spatrick /// Get the source location for the given file:line:col triplet.
1644e5dd7070Spatrick ///
1645e5dd7070Spatrick /// If the source file is included multiple times, the source location will
1646e5dd7070Spatrick /// be based upon an arbitrary inclusion.
translateFileLineCol(const FileEntry * SourceFile,unsigned Line,unsigned Col) const1647e5dd7070Spatrick SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1648e5dd7070Spatrick unsigned Line,
1649e5dd7070Spatrick unsigned Col) const {
1650e5dd7070Spatrick assert(SourceFile && "Null source file!");
1651e5dd7070Spatrick assert(Line && Col && "Line and column should start from 1!");
1652e5dd7070Spatrick
1653e5dd7070Spatrick FileID FirstFID = translateFile(SourceFile);
1654e5dd7070Spatrick return translateLineCol(FirstFID, Line, Col);
1655e5dd7070Spatrick }
1656e5dd7070Spatrick
1657e5dd7070Spatrick /// Get the FileID for the given file.
1658e5dd7070Spatrick ///
1659e5dd7070Spatrick /// If the source file is included multiple times, the FileID will be the
1660e5dd7070Spatrick /// first inclusion.
translateFile(const FileEntry * SourceFile) const1661e5dd7070Spatrick FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1662e5dd7070Spatrick assert(SourceFile && "Null source file!");
1663e5dd7070Spatrick
1664e5dd7070Spatrick // First, check the main file ID, since it is common to look for a
1665e5dd7070Spatrick // location in the main file.
1666e5dd7070Spatrick if (MainFileID.isValid()) {
1667e5dd7070Spatrick bool Invalid = false;
1668e5dd7070Spatrick const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1669e5dd7070Spatrick if (Invalid)
1670e5dd7070Spatrick return FileID();
1671e5dd7070Spatrick
1672e5dd7070Spatrick if (MainSLoc.isFile()) {
1673a9ac8606Spatrick if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1674e5dd7070Spatrick return MainFileID;
1675e5dd7070Spatrick }
1676e5dd7070Spatrick }
1677e5dd7070Spatrick
1678e5dd7070Spatrick // The location we're looking for isn't in the main file; look
1679e5dd7070Spatrick // through all of the local source locations.
1680e5dd7070Spatrick for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1681ec727ea7Spatrick const SLocEntry &SLoc = getLocalSLocEntry(I);
1682a9ac8606Spatrick if (SLoc.isFile() &&
1683a9ac8606Spatrick SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1684e5dd7070Spatrick return FileID::get(I);
1685e5dd7070Spatrick }
1686e5dd7070Spatrick
1687e5dd7070Spatrick // If that still didn't help, try the modules.
1688e5dd7070Spatrick for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1689e5dd7070Spatrick const SLocEntry &SLoc = getLoadedSLocEntry(I);
1690a9ac8606Spatrick if (SLoc.isFile() &&
1691a9ac8606Spatrick SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1692e5dd7070Spatrick return FileID::get(-int(I) - 2);
1693e5dd7070Spatrick }
1694e5dd7070Spatrick
1695e5dd7070Spatrick return FileID();
1696e5dd7070Spatrick }
1697e5dd7070Spatrick
1698e5dd7070Spatrick /// Get the source location in \arg FID for the given line:col.
1699e5dd7070Spatrick /// Returns null location if \arg FID is not a file SLocEntry.
translateLineCol(FileID FID,unsigned Line,unsigned Col) const1700e5dd7070Spatrick SourceLocation SourceManager::translateLineCol(FileID FID,
1701e5dd7070Spatrick unsigned Line,
1702e5dd7070Spatrick unsigned Col) const {
1703e5dd7070Spatrick // Lines are used as a one-based index into a zero-based array. This assert
1704e5dd7070Spatrick // checks for possible buffer underruns.
1705e5dd7070Spatrick assert(Line && Col && "Line and column should start from 1!");
1706e5dd7070Spatrick
1707e5dd7070Spatrick if (FID.isInvalid())
1708e5dd7070Spatrick return SourceLocation();
1709e5dd7070Spatrick
1710e5dd7070Spatrick bool Invalid = false;
1711e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1712e5dd7070Spatrick if (Invalid)
1713e5dd7070Spatrick return SourceLocation();
1714e5dd7070Spatrick
1715e5dd7070Spatrick if (!Entry.isFile())
1716e5dd7070Spatrick return SourceLocation();
1717e5dd7070Spatrick
1718e5dd7070Spatrick SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1719e5dd7070Spatrick
1720e5dd7070Spatrick if (Line == 1 && Col == 1)
1721e5dd7070Spatrick return FileLoc;
1722e5dd7070Spatrick
1723a9ac8606Spatrick const ContentCache *Content = &Entry.getFile().getContentCache();
1724e5dd7070Spatrick
1725e5dd7070Spatrick // If this is the first use of line information for this buffer, compute the
1726e5dd7070Spatrick // SourceLineCache for it on demand.
1727*12c85518Srobert std::optional<llvm::MemoryBufferRef> Buffer =
1728a9ac8606Spatrick Content->getBufferOrNone(Diag, getFileManager());
1729a9ac8606Spatrick if (!Buffer)
1730e5dd7070Spatrick return SourceLocation();
1731a9ac8606Spatrick if (!Content->SourceLineCache)
1732a9ac8606Spatrick Content->SourceLineCache =
1733a9ac8606Spatrick LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1734e5dd7070Spatrick
1735a9ac8606Spatrick if (Line > Content->SourceLineCache.size()) {
1736a9ac8606Spatrick unsigned Size = Buffer->getBufferSize();
1737e5dd7070Spatrick if (Size > 0)
1738e5dd7070Spatrick --Size;
1739e5dd7070Spatrick return FileLoc.getLocWithOffset(Size);
1740e5dd7070Spatrick }
1741e5dd7070Spatrick
1742e5dd7070Spatrick unsigned FilePos = Content->SourceLineCache[Line - 1];
1743e5dd7070Spatrick const char *Buf = Buffer->getBufferStart() + FilePos;
1744e5dd7070Spatrick unsigned BufLength = Buffer->getBufferSize() - FilePos;
1745e5dd7070Spatrick if (BufLength == 0)
1746e5dd7070Spatrick return FileLoc.getLocWithOffset(FilePos);
1747e5dd7070Spatrick
1748e5dd7070Spatrick unsigned i = 0;
1749e5dd7070Spatrick
1750e5dd7070Spatrick // Check that the given column is valid.
1751e5dd7070Spatrick while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1752e5dd7070Spatrick ++i;
1753e5dd7070Spatrick return FileLoc.getLocWithOffset(FilePos + i);
1754e5dd7070Spatrick }
1755e5dd7070Spatrick
1756e5dd7070Spatrick /// Compute a map of macro argument chunks to their expanded source
1757e5dd7070Spatrick /// location. Chunks that are not part of a macro argument will map to an
1758e5dd7070Spatrick /// invalid source location. e.g. if a file contains one macro argument at
1759e5dd7070Spatrick /// offset 100 with length 10, this is how the map will be formed:
1760e5dd7070Spatrick /// 0 -> SourceLocation()
1761e5dd7070Spatrick /// 100 -> Expanded macro arg location
1762e5dd7070Spatrick /// 110 -> SourceLocation()
computeMacroArgsCache(MacroArgsMap & MacroArgsCache,FileID FID) const1763e5dd7070Spatrick void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1764e5dd7070Spatrick FileID FID) const {
1765e5dd7070Spatrick assert(FID.isValid());
1766e5dd7070Spatrick
1767e5dd7070Spatrick // Initially no macro argument chunk is present.
1768e5dd7070Spatrick MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1769e5dd7070Spatrick
1770e5dd7070Spatrick int ID = FID.ID;
1771e5dd7070Spatrick while (true) {
1772e5dd7070Spatrick ++ID;
1773e5dd7070Spatrick // Stop if there are no more FileIDs to check.
1774e5dd7070Spatrick if (ID > 0) {
1775e5dd7070Spatrick if (unsigned(ID) >= local_sloc_entry_size())
1776e5dd7070Spatrick return;
1777e5dd7070Spatrick } else if (ID == -1) {
1778e5dd7070Spatrick return;
1779e5dd7070Spatrick }
1780e5dd7070Spatrick
1781e5dd7070Spatrick bool Invalid = false;
1782e5dd7070Spatrick const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1783e5dd7070Spatrick if (Invalid)
1784e5dd7070Spatrick return;
1785e5dd7070Spatrick if (Entry.isFile()) {
1786a9ac8606Spatrick auto& File = Entry.getFile();
1787a9ac8606Spatrick if (File.getFileCharacteristic() == C_User_ModuleMap ||
1788a9ac8606Spatrick File.getFileCharacteristic() == C_System_ModuleMap)
1789a9ac8606Spatrick continue;
1790a9ac8606Spatrick
1791a9ac8606Spatrick SourceLocation IncludeLoc = File.getIncludeLoc();
1792ec727ea7Spatrick bool IncludedInFID =
1793ec727ea7Spatrick (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1794ec727ea7Spatrick // Predefined header doesn't have a valid include location in main
1795ec727ea7Spatrick // file, but any files created by it should still be skipped when
1796ec727ea7Spatrick // computing macro args expanded in the main file.
1797a9ac8606Spatrick (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1798ec727ea7Spatrick if (IncludedInFID) {
1799ec727ea7Spatrick // Skip the files/macros of the #include'd file, we only care about
1800ec727ea7Spatrick // macros that lexed macro arguments from our file.
1801e5dd7070Spatrick if (Entry.getFile().NumCreatedFIDs)
1802e5dd7070Spatrick ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1803e5dd7070Spatrick continue;
1804*12c85518Srobert }
1805ec727ea7Spatrick // If file was included but not from FID, there is no more files/macros
1806ec727ea7Spatrick // that may be "contained" in this file.
1807*12c85518Srobert if (IncludeLoc.isValid())
1808ec727ea7Spatrick return;
1809ec727ea7Spatrick continue;
1810e5dd7070Spatrick }
1811e5dd7070Spatrick
1812e5dd7070Spatrick const ExpansionInfo &ExpInfo = Entry.getExpansion();
1813e5dd7070Spatrick
1814e5dd7070Spatrick if (ExpInfo.getExpansionLocStart().isFileID()) {
1815e5dd7070Spatrick if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1816e5dd7070Spatrick return; // No more files/macros that may be "contained" in this file.
1817e5dd7070Spatrick }
1818e5dd7070Spatrick
1819e5dd7070Spatrick if (!ExpInfo.isMacroArgExpansion())
1820e5dd7070Spatrick continue;
1821e5dd7070Spatrick
1822e5dd7070Spatrick associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1823e5dd7070Spatrick ExpInfo.getSpellingLoc(),
1824e5dd7070Spatrick SourceLocation::getMacroLoc(Entry.getOffset()),
1825e5dd7070Spatrick getFileIDSize(FileID::get(ID)));
1826e5dd7070Spatrick }
1827e5dd7070Spatrick }
1828e5dd7070Spatrick
associateFileChunkWithMacroArgExp(MacroArgsMap & MacroArgsCache,FileID FID,SourceLocation SpellLoc,SourceLocation ExpansionLoc,unsigned ExpansionLength) const1829e5dd7070Spatrick void SourceManager::associateFileChunkWithMacroArgExp(
1830e5dd7070Spatrick MacroArgsMap &MacroArgsCache,
1831e5dd7070Spatrick FileID FID,
1832e5dd7070Spatrick SourceLocation SpellLoc,
1833e5dd7070Spatrick SourceLocation ExpansionLoc,
1834e5dd7070Spatrick unsigned ExpansionLength) const {
1835e5dd7070Spatrick if (!SpellLoc.isFileID()) {
1836a9ac8606Spatrick SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1837a9ac8606Spatrick SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
1838e5dd7070Spatrick
1839e5dd7070Spatrick // The spelling range for this macro argument expansion can span multiple
1840e5dd7070Spatrick // consecutive FileID entries. Go through each entry contained in the
1841e5dd7070Spatrick // spelling range and if one is itself a macro argument expansion, recurse
1842e5dd7070Spatrick // and associate the file chunk that it represents.
1843e5dd7070Spatrick
1844e5dd7070Spatrick FileID SpellFID; // Current FileID in the spelling range.
1845e5dd7070Spatrick unsigned SpellRelativeOffs;
1846e5dd7070Spatrick std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1847e5dd7070Spatrick while (true) {
1848e5dd7070Spatrick const SLocEntry &Entry = getSLocEntry(SpellFID);
1849a9ac8606Spatrick SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
1850e5dd7070Spatrick unsigned SpellFIDSize = getFileIDSize(SpellFID);
1851a9ac8606Spatrick SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1852e5dd7070Spatrick const ExpansionInfo &Info = Entry.getExpansion();
1853e5dd7070Spatrick if (Info.isMacroArgExpansion()) {
1854e5dd7070Spatrick unsigned CurrSpellLength;
1855e5dd7070Spatrick if (SpellFIDEndOffs < SpellEndOffs)
1856e5dd7070Spatrick CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1857e5dd7070Spatrick else
1858e5dd7070Spatrick CurrSpellLength = ExpansionLength;
1859e5dd7070Spatrick associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1860e5dd7070Spatrick Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1861e5dd7070Spatrick ExpansionLoc, CurrSpellLength);
1862e5dd7070Spatrick }
1863e5dd7070Spatrick
1864e5dd7070Spatrick if (SpellFIDEndOffs >= SpellEndOffs)
1865e5dd7070Spatrick return; // we covered all FileID entries in the spelling range.
1866e5dd7070Spatrick
1867e5dd7070Spatrick // Move to the next FileID entry in the spelling range.
1868e5dd7070Spatrick unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1869e5dd7070Spatrick ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1870e5dd7070Spatrick ExpansionLength -= advance;
1871e5dd7070Spatrick ++SpellFID.ID;
1872e5dd7070Spatrick SpellRelativeOffs = 0;
1873e5dd7070Spatrick }
1874e5dd7070Spatrick }
1875e5dd7070Spatrick
1876e5dd7070Spatrick assert(SpellLoc.isFileID());
1877e5dd7070Spatrick
1878e5dd7070Spatrick unsigned BeginOffs;
1879e5dd7070Spatrick if (!isInFileID(SpellLoc, FID, &BeginOffs))
1880e5dd7070Spatrick return;
1881e5dd7070Spatrick
1882e5dd7070Spatrick unsigned EndOffs = BeginOffs + ExpansionLength;
1883e5dd7070Spatrick
1884e5dd7070Spatrick // Add a new chunk for this macro argument. A previous macro argument chunk
1885e5dd7070Spatrick // may have been lexed again, so e.g. if the map is
1886e5dd7070Spatrick // 0 -> SourceLocation()
1887e5dd7070Spatrick // 100 -> Expanded loc #1
1888e5dd7070Spatrick // 110 -> SourceLocation()
1889e5dd7070Spatrick // and we found a new macro FileID that lexed from offset 105 with length 3,
1890e5dd7070Spatrick // the new map will be:
1891e5dd7070Spatrick // 0 -> SourceLocation()
1892e5dd7070Spatrick // 100 -> Expanded loc #1
1893e5dd7070Spatrick // 105 -> Expanded loc #2
1894e5dd7070Spatrick // 108 -> Expanded loc #1
1895e5dd7070Spatrick // 110 -> SourceLocation()
1896e5dd7070Spatrick //
1897e5dd7070Spatrick // Since re-lexed macro chunks will always be the same size or less of
1898e5dd7070Spatrick // previous chunks, we only need to find where the ending of the new macro
1899e5dd7070Spatrick // chunk is mapped to and update the map with new begin/end mappings.
1900e5dd7070Spatrick
1901e5dd7070Spatrick MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1902e5dd7070Spatrick --I;
1903e5dd7070Spatrick SourceLocation EndOffsMappedLoc = I->second;
1904e5dd7070Spatrick MacroArgsCache[BeginOffs] = ExpansionLoc;
1905e5dd7070Spatrick MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1906e5dd7070Spatrick }
1907e5dd7070Spatrick
1908e5dd7070Spatrick /// If \arg Loc points inside a function macro argument, the returned
1909e5dd7070Spatrick /// location will be the macro location in which the argument was expanded.
1910e5dd7070Spatrick /// If a macro argument is used multiple times, the expanded location will
1911e5dd7070Spatrick /// be at the first expansion of the argument.
1912e5dd7070Spatrick /// e.g.
1913e5dd7070Spatrick /// MY_MACRO(foo);
1914e5dd7070Spatrick /// ^
1915e5dd7070Spatrick /// Passing a file location pointing at 'foo', will yield a macro location
1916e5dd7070Spatrick /// where 'foo' was expanded into.
1917e5dd7070Spatrick SourceLocation
getMacroArgExpandedLocation(SourceLocation Loc) const1918e5dd7070Spatrick SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1919e5dd7070Spatrick if (Loc.isInvalid() || !Loc.isFileID())
1920e5dd7070Spatrick return Loc;
1921e5dd7070Spatrick
1922e5dd7070Spatrick FileID FID;
1923e5dd7070Spatrick unsigned Offset;
1924e5dd7070Spatrick std::tie(FID, Offset) = getDecomposedLoc(Loc);
1925e5dd7070Spatrick if (FID.isInvalid())
1926e5dd7070Spatrick return Loc;
1927e5dd7070Spatrick
1928e5dd7070Spatrick std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1929e5dd7070Spatrick if (!MacroArgsCache) {
1930e5dd7070Spatrick MacroArgsCache = std::make_unique<MacroArgsMap>();
1931e5dd7070Spatrick computeMacroArgsCache(*MacroArgsCache, FID);
1932e5dd7070Spatrick }
1933e5dd7070Spatrick
1934e5dd7070Spatrick assert(!MacroArgsCache->empty());
1935e5dd7070Spatrick MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1936a9ac8606Spatrick // In case every element in MacroArgsCache is greater than Offset we can't
1937a9ac8606Spatrick // decrement the iterator.
1938a9ac8606Spatrick if (I == MacroArgsCache->begin())
1939a9ac8606Spatrick return Loc;
1940a9ac8606Spatrick
1941e5dd7070Spatrick --I;
1942e5dd7070Spatrick
1943a9ac8606Spatrick SourceLocation::UIntTy MacroArgBeginOffs = I->first;
1944e5dd7070Spatrick SourceLocation MacroArgExpandedLoc = I->second;
1945e5dd7070Spatrick if (MacroArgExpandedLoc.isValid())
1946e5dd7070Spatrick return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1947e5dd7070Spatrick
1948e5dd7070Spatrick return Loc;
1949e5dd7070Spatrick }
1950e5dd7070Spatrick
1951e5dd7070Spatrick std::pair<FileID, unsigned>
getDecomposedIncludedLoc(FileID FID) const1952e5dd7070Spatrick SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1953e5dd7070Spatrick if (FID.isInvalid())
1954e5dd7070Spatrick return std::make_pair(FileID(), 0);
1955e5dd7070Spatrick
1956e5dd7070Spatrick // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1957e5dd7070Spatrick
1958e5dd7070Spatrick using DecompTy = std::pair<FileID, unsigned>;
1959e5dd7070Spatrick auto InsertOp = IncludedLocMap.try_emplace(FID);
1960e5dd7070Spatrick DecompTy &DecompLoc = InsertOp.first->second;
1961e5dd7070Spatrick if (!InsertOp.second)
1962e5dd7070Spatrick return DecompLoc; // already in map.
1963e5dd7070Spatrick
1964e5dd7070Spatrick SourceLocation UpperLoc;
1965e5dd7070Spatrick bool Invalid = false;
1966e5dd7070Spatrick const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1967e5dd7070Spatrick if (!Invalid) {
1968e5dd7070Spatrick if (Entry.isExpansion())
1969e5dd7070Spatrick UpperLoc = Entry.getExpansion().getExpansionLocStart();
1970e5dd7070Spatrick else
1971e5dd7070Spatrick UpperLoc = Entry.getFile().getIncludeLoc();
1972e5dd7070Spatrick }
1973e5dd7070Spatrick
1974e5dd7070Spatrick if (UpperLoc.isValid())
1975e5dd7070Spatrick DecompLoc = getDecomposedLoc(UpperLoc);
1976e5dd7070Spatrick
1977e5dd7070Spatrick return DecompLoc;
1978e5dd7070Spatrick }
1979e5dd7070Spatrick
1980e5dd7070Spatrick /// Given a decomposed source location, move it up the include/expansion stack
1981e5dd7070Spatrick /// to the parent source location. If this is possible, return the decomposed
1982e5dd7070Spatrick /// version of the parent in Loc and return false. If Loc is the top-level
1983e5dd7070Spatrick /// entry, return true and don't modify it.
MoveUpIncludeHierarchy(std::pair<FileID,unsigned> & Loc,const SourceManager & SM)1984e5dd7070Spatrick static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1985e5dd7070Spatrick const SourceManager &SM) {
1986e5dd7070Spatrick std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1987e5dd7070Spatrick if (UpperLoc.first.isInvalid())
1988e5dd7070Spatrick return true; // We reached the top.
1989e5dd7070Spatrick
1990e5dd7070Spatrick Loc = UpperLoc;
1991e5dd7070Spatrick return false;
1992e5dd7070Spatrick }
1993e5dd7070Spatrick
1994e5dd7070Spatrick /// Return the cache entry for comparing the given file IDs
1995e5dd7070Spatrick /// for isBeforeInTranslationUnit.
getInBeforeInTUCache(FileID LFID,FileID RFID) const1996e5dd7070Spatrick InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1997e5dd7070Spatrick FileID RFID) const {
1998e5dd7070Spatrick // This is a magic number for limiting the cache size. It was experimentally
1999e5dd7070Spatrick // derived from a small Objective-C project (where the cache filled
2000e5dd7070Spatrick // out to ~250 items). We can make it larger if necessary.
2001*12c85518Srobert // FIXME: this is almost certainly full these days. Use an LRU cache?
2002e5dd7070Spatrick enum { MagicCacheSize = 300 };
2003e5dd7070Spatrick IsBeforeInTUCacheKey Key(LFID, RFID);
2004e5dd7070Spatrick
2005e5dd7070Spatrick // If the cache size isn't too large, do a lookup and if necessary default
2006e5dd7070Spatrick // construct an entry. We can then return it to the caller for direct
2007e5dd7070Spatrick // use. When they update the value, the cache will get automatically
2008e5dd7070Spatrick // updated as well.
2009e5dd7070Spatrick if (IBTUCache.size() < MagicCacheSize)
2010*12c85518Srobert return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
2011e5dd7070Spatrick
2012e5dd7070Spatrick // Otherwise, do a lookup that will not construct a new value.
2013e5dd7070Spatrick InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2014e5dd7070Spatrick if (I != IBTUCache.end())
2015e5dd7070Spatrick return I->second;
2016e5dd7070Spatrick
2017e5dd7070Spatrick // Fall back to the overflow value.
2018*12c85518Srobert IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
2019e5dd7070Spatrick return IBTUCacheOverflow;
2020e5dd7070Spatrick }
2021e5dd7070Spatrick
2022e5dd7070Spatrick /// Determines the order of 2 source locations in the translation unit.
2023e5dd7070Spatrick ///
2024e5dd7070Spatrick /// \returns true if LHS source location comes before RHS, false otherwise.
isBeforeInTranslationUnit(SourceLocation LHS,SourceLocation RHS) const2025e5dd7070Spatrick bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2026e5dd7070Spatrick SourceLocation RHS) const {
2027e5dd7070Spatrick assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2028e5dd7070Spatrick if (LHS == RHS)
2029e5dd7070Spatrick return false;
2030e5dd7070Spatrick
2031e5dd7070Spatrick std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2032e5dd7070Spatrick std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2033e5dd7070Spatrick
2034e5dd7070Spatrick // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2035e5dd7070Spatrick // is a serialized one referring to a file that was removed after we loaded
2036e5dd7070Spatrick // the PCH.
2037e5dd7070Spatrick if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2038e5dd7070Spatrick return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2039e5dd7070Spatrick
2040e5dd7070Spatrick std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2041e5dd7070Spatrick if (InSameTU.first)
2042e5dd7070Spatrick return InSameTU.second;
2043e5dd7070Spatrick
2044e5dd7070Spatrick // If we arrived here, the location is either in a built-ins buffer or
2045e5dd7070Spatrick // associated with global inline asm. PR5662 and PR22576 are examples.
2046e5dd7070Spatrick
2047a9ac8606Spatrick StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2048a9ac8606Spatrick StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
2049e5dd7070Spatrick bool LIsBuiltins = LB == "<built-in>";
2050e5dd7070Spatrick bool RIsBuiltins = RB == "<built-in>";
2051e5dd7070Spatrick // Sort built-in before non-built-in.
2052e5dd7070Spatrick if (LIsBuiltins || RIsBuiltins) {
2053e5dd7070Spatrick if (LIsBuiltins != RIsBuiltins)
2054e5dd7070Spatrick return LIsBuiltins;
2055e5dd7070Spatrick // Both are in built-in buffers, but from different files. We just claim that
2056e5dd7070Spatrick // lower IDs come first.
2057e5dd7070Spatrick return LOffs.first < ROffs.first;
2058e5dd7070Spatrick }
2059e5dd7070Spatrick bool LIsAsm = LB == "<inline asm>";
2060e5dd7070Spatrick bool RIsAsm = RB == "<inline asm>";
2061e5dd7070Spatrick // Sort assembler after built-ins, but before the rest.
2062e5dd7070Spatrick if (LIsAsm || RIsAsm) {
2063e5dd7070Spatrick if (LIsAsm != RIsAsm)
2064e5dd7070Spatrick return RIsAsm;
2065e5dd7070Spatrick assert(LOffs.first == ROffs.first);
2066e5dd7070Spatrick return false;
2067e5dd7070Spatrick }
2068e5dd7070Spatrick bool LIsScratch = LB == "<scratch space>";
2069e5dd7070Spatrick bool RIsScratch = RB == "<scratch space>";
2070e5dd7070Spatrick // Sort scratch after inline asm, but before the rest.
2071e5dd7070Spatrick if (LIsScratch || RIsScratch) {
2072e5dd7070Spatrick if (LIsScratch != RIsScratch)
2073e5dd7070Spatrick return LIsScratch;
2074e5dd7070Spatrick return LOffs.second < ROffs.second;
2075e5dd7070Spatrick }
2076e5dd7070Spatrick llvm_unreachable("Unsortable locations found");
2077e5dd7070Spatrick }
2078e5dd7070Spatrick
isInTheSameTranslationUnit(std::pair<FileID,unsigned> & LOffs,std::pair<FileID,unsigned> & ROffs) const2079e5dd7070Spatrick std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2080e5dd7070Spatrick std::pair<FileID, unsigned> &LOffs,
2081e5dd7070Spatrick std::pair<FileID, unsigned> &ROffs) const {
2082e5dd7070Spatrick // If the source locations are in the same file, just compare offsets.
2083e5dd7070Spatrick if (LOffs.first == ROffs.first)
2084e5dd7070Spatrick return std::make_pair(true, LOffs.second < ROffs.second);
2085e5dd7070Spatrick
2086e5dd7070Spatrick // If we are comparing a source location with multiple locations in the same
2087e5dd7070Spatrick // file, we get a big win by caching the result.
2088e5dd7070Spatrick InBeforeInTUCacheEntry &IsBeforeInTUCache =
2089e5dd7070Spatrick getInBeforeInTUCache(LOffs.first, ROffs.first);
2090e5dd7070Spatrick
2091e5dd7070Spatrick // If we are comparing a source location with multiple locations in the same
2092e5dd7070Spatrick // file, we get a big win by caching the result.
2093*12c85518Srobert if (IsBeforeInTUCache.isCacheValid())
2094e5dd7070Spatrick return std::make_pair(
2095e5dd7070Spatrick true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2096e5dd7070Spatrick
2097*12c85518Srobert // Okay, we missed in the cache, we'll compute the answer and populate it.
2098e5dd7070Spatrick // We need to find the common ancestor. The only way of doing this is to
2099e5dd7070Spatrick // build the complete include chain for one and then walking up the chain
2100e5dd7070Spatrick // of the other looking for a match.
2101*12c85518Srobert
2102*12c85518Srobert // A location within a FileID on the path up from LOffs to the main file.
2103*12c85518Srobert struct Entry {
2104*12c85518Srobert unsigned Offset;
2105*12c85518Srobert FileID ParentFID; // Used for breaking ties.
2106*12c85518Srobert };
2107*12c85518Srobert llvm::SmallDenseMap<FileID, Entry, 16> LChain;
2108*12c85518Srobert
2109*12c85518Srobert FileID Parent;
2110e5dd7070Spatrick do {
2111*12c85518Srobert LChain.try_emplace(LOffs.first, Entry{LOffs.second, Parent});
2112e5dd7070Spatrick // We catch the case where LOffs is in a file included by ROffs and
2113e5dd7070Spatrick // quit early. The other way round unfortunately remains suboptimal.
2114*12c85518Srobert if (LOffs.first == ROffs.first)
2115*12c85518Srobert break;
2116*12c85518Srobert Parent = LOffs.first;
2117*12c85518Srobert } while (!MoveUpIncludeHierarchy(LOffs, *this));
2118e5dd7070Spatrick
2119*12c85518Srobert Parent = FileID();
2120*12c85518Srobert do {
2121*12c85518Srobert auto I = LChain.find(ROffs.first);
2122*12c85518Srobert if (I != LChain.end()) {
2123*12c85518Srobert // Compare the locations within the common file and cache them.
2124*12c85518Srobert LOffs.first = I->first;
2125*12c85518Srobert LOffs.second = I->second.Offset;
2126*12c85518Srobert // The relative order of LParent and RParent is a tiebreaker when
2127*12c85518Srobert // - locs expand to the same location (occurs in macro arg expansion)
2128*12c85518Srobert // - one loc is a parent of the other (we consider the parent as "first")
2129*12c85518Srobert // For the parent to be first, the invalid file ID must compare smaller.
2130*12c85518Srobert // However loaded FileIDs are <0, so we perform *unsigned* comparison!
2131*12c85518Srobert // This changes the relative order of local vs loaded FileIDs, but it
2132*12c85518Srobert // doesn't matter as these are never mixed in macro expansion.
2133*12c85518Srobert unsigned LParent = I->second.ParentFID.ID;
2134*12c85518Srobert unsigned RParent = Parent.ID;
2135*12c85518Srobert assert(((LOffs.second != ROffs.second) ||
2136*12c85518Srobert (LParent == 0 || RParent == 0) ||
2137*12c85518Srobert isInSameSLocAddrSpace(getComposedLoc(I->second.ParentFID, 0),
2138*12c85518Srobert getComposedLoc(Parent, 0), nullptr)) &&
2139*12c85518Srobert "Mixed local/loaded FileIDs with same include location?");
2140*12c85518Srobert IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
2141*12c85518Srobert LParent < RParent);
2142e5dd7070Spatrick return std::make_pair(
2143e5dd7070Spatrick true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2144e5dd7070Spatrick }
2145*12c85518Srobert Parent = ROffs.first;
2146*12c85518Srobert } while (!MoveUpIncludeHierarchy(ROffs, *this));
2147*12c85518Srobert
2148*12c85518Srobert // If we found no match, we're not in the same TU.
2149*12c85518Srobert // We don't cache this, but it is rare.
2150e5dd7070Spatrick return std::make_pair(false, false);
2151e5dd7070Spatrick }
2152e5dd7070Spatrick
PrintStats() const2153e5dd7070Spatrick void SourceManager::PrintStats() const {
2154e5dd7070Spatrick llvm::errs() << "\n*** Source Manager Stats:\n";
2155e5dd7070Spatrick llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2156e5dd7070Spatrick << " mem buffers mapped.\n";
2157e5dd7070Spatrick llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2158e5dd7070Spatrick << llvm::capacity_in_bytes(LocalSLocEntryTable)
2159e5dd7070Spatrick << " bytes of capacity), "
2160e5dd7070Spatrick << NextLocalOffset << "B of Sloc address space used.\n";
2161e5dd7070Spatrick llvm::errs() << LoadedSLocEntryTable.size()
2162e5dd7070Spatrick << " loaded SLocEntries allocated, "
2163e5dd7070Spatrick << MaxLoadedOffset - CurrentLoadedOffset
2164e5dd7070Spatrick << "B of Sloc address space used.\n";
2165e5dd7070Spatrick
2166e5dd7070Spatrick unsigned NumLineNumsComputed = 0;
2167e5dd7070Spatrick unsigned NumFileBytesMapped = 0;
2168e5dd7070Spatrick for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2169a9ac8606Spatrick NumLineNumsComputed += bool(I->second->SourceLineCache);
2170e5dd7070Spatrick NumFileBytesMapped += I->second->getSizeBytesMapped();
2171e5dd7070Spatrick }
2172e5dd7070Spatrick unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2173e5dd7070Spatrick
2174e5dd7070Spatrick llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2175e5dd7070Spatrick << NumLineNumsComputed << " files with line #'s computed, "
2176e5dd7070Spatrick << NumMacroArgsComputed << " files with macro args computed.\n";
2177e5dd7070Spatrick llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2178e5dd7070Spatrick << NumBinaryProbes << " binary.\n";
2179e5dd7070Spatrick }
2180e5dd7070Spatrick
dump() const2181e5dd7070Spatrick LLVM_DUMP_METHOD void SourceManager::dump() const {
2182e5dd7070Spatrick llvm::raw_ostream &out = llvm::errs();
2183e5dd7070Spatrick
2184e5dd7070Spatrick auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2185*12c85518Srobert std::optional<SourceLocation::UIntTy> NextStart) {
2186e5dd7070Spatrick out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2187e5dd7070Spatrick << " <SourceLocation " << Entry.getOffset() << ":";
2188e5dd7070Spatrick if (NextStart)
2189e5dd7070Spatrick out << *NextStart << ">\n";
2190e5dd7070Spatrick else
2191e5dd7070Spatrick out << "???\?>\n";
2192e5dd7070Spatrick if (Entry.isFile()) {
2193e5dd7070Spatrick auto &FI = Entry.getFile();
2194e5dd7070Spatrick if (FI.NumCreatedFIDs)
2195e5dd7070Spatrick out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2196e5dd7070Spatrick << ">\n";
2197e5dd7070Spatrick if (FI.getIncludeLoc().isValid())
2198e5dd7070Spatrick out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2199a9ac8606Spatrick auto &CC = FI.getContentCache();
2200a9ac8606Spatrick out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
2201e5dd7070Spatrick << "\n";
2202a9ac8606Spatrick if (CC.BufferOverridden)
2203e5dd7070Spatrick out << " contents overridden\n";
2204a9ac8606Spatrick if (CC.ContentsEntry != CC.OrigEntry) {
2205e5dd7070Spatrick out << " contents from "
2206a9ac8606Spatrick << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
2207e5dd7070Spatrick << "\n";
2208e5dd7070Spatrick }
2209e5dd7070Spatrick } else {
2210e5dd7070Spatrick auto &EI = Entry.getExpansion();
2211e5dd7070Spatrick out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2212e5dd7070Spatrick out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2213e5dd7070Spatrick << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2214e5dd7070Spatrick << EI.getExpansionLocEnd().getOffset() << ">\n";
2215e5dd7070Spatrick }
2216e5dd7070Spatrick };
2217e5dd7070Spatrick
2218e5dd7070Spatrick // Dump local SLocEntries.
2219e5dd7070Spatrick for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2220e5dd7070Spatrick DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2221e5dd7070Spatrick ID == NumIDs - 1 ? NextLocalOffset
2222e5dd7070Spatrick : LocalSLocEntryTable[ID + 1].getOffset());
2223e5dd7070Spatrick }
2224e5dd7070Spatrick // Dump loaded SLocEntries.
2225*12c85518Srobert std::optional<SourceLocation::UIntTy> NextStart;
2226e5dd7070Spatrick for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2227e5dd7070Spatrick int ID = -(int)Index - 2;
2228e5dd7070Spatrick if (SLocEntryLoaded[Index]) {
2229e5dd7070Spatrick DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2230e5dd7070Spatrick NextStart = LoadedSLocEntryTable[Index].getOffset();
2231e5dd7070Spatrick } else {
2232*12c85518Srobert NextStart = std::nullopt;
2233e5dd7070Spatrick }
2234e5dd7070Spatrick }
2235e5dd7070Spatrick }
2236e5dd7070Spatrick
noteSLocAddressSpaceUsage(DiagnosticsEngine & Diag,std::optional<unsigned> MaxNotes) const2237*12c85518Srobert void SourceManager::noteSLocAddressSpaceUsage(
2238*12c85518Srobert DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {
2239*12c85518Srobert struct Info {
2240*12c85518Srobert // A location where this file was entered.
2241*12c85518Srobert SourceLocation Loc;
2242*12c85518Srobert // Number of times this FileEntry was entered.
2243*12c85518Srobert unsigned Inclusions = 0;
2244*12c85518Srobert // Size usage from the file itself.
2245*12c85518Srobert uint64_t DirectSize = 0;
2246*12c85518Srobert // Total size usage from the file and its macro expansions.
2247*12c85518Srobert uint64_t TotalSize = 0;
2248*12c85518Srobert };
2249*12c85518Srobert using UsageMap = llvm::MapVector<const FileEntry*, Info>;
2250*12c85518Srobert
2251*12c85518Srobert UsageMap Usage;
2252*12c85518Srobert uint64_t CountedSize = 0;
2253*12c85518Srobert
2254*12c85518Srobert auto AddUsageForFileID = [&](FileID ID) {
2255*12c85518Srobert // The +1 here is because getFileIDSize doesn't include the extra byte for
2256*12c85518Srobert // the one-past-the-end location.
2257*12c85518Srobert unsigned Size = getFileIDSize(ID) + 1;
2258*12c85518Srobert
2259*12c85518Srobert // Find the file that used this address space, either directly or by
2260*12c85518Srobert // macro expansion.
2261*12c85518Srobert SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));
2262*12c85518Srobert FileID FileLocID = getFileID(FileStart);
2263*12c85518Srobert const FileEntry *Entry = getFileEntryForID(FileLocID);
2264*12c85518Srobert
2265*12c85518Srobert Info &EntryInfo = Usage[Entry];
2266*12c85518Srobert if (EntryInfo.Loc.isInvalid())
2267*12c85518Srobert EntryInfo.Loc = FileStart;
2268*12c85518Srobert if (ID == FileLocID) {
2269*12c85518Srobert ++EntryInfo.Inclusions;
2270*12c85518Srobert EntryInfo.DirectSize += Size;
2271*12c85518Srobert }
2272*12c85518Srobert EntryInfo.TotalSize += Size;
2273*12c85518Srobert CountedSize += Size;
2274*12c85518Srobert };
2275*12c85518Srobert
2276*12c85518Srobert // Loaded SLocEntries have indexes counting downwards from -2.
2277*12c85518Srobert for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2278*12c85518Srobert AddUsageForFileID(FileID::get(-2 - Index));
2279*12c85518Srobert }
2280*12c85518Srobert // Local SLocEntries have indexes counting upwards from 0.
2281*12c85518Srobert for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
2282*12c85518Srobert AddUsageForFileID(FileID::get(Index));
2283*12c85518Srobert }
2284*12c85518Srobert
2285*12c85518Srobert // Sort the usage by size from largest to smallest. Break ties by raw source
2286*12c85518Srobert // location.
2287*12c85518Srobert auto SortedUsage = Usage.takeVector();
2288*12c85518Srobert auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {
2289*12c85518Srobert return A.second.TotalSize > B.second.TotalSize ||
2290*12c85518Srobert (A.second.TotalSize == B.second.TotalSize &&
2291*12c85518Srobert A.second.Loc < B.second.Loc);
2292*12c85518Srobert };
2293*12c85518Srobert auto SortedEnd = SortedUsage.end();
2294*12c85518Srobert if (MaxNotes && SortedUsage.size() > *MaxNotes) {
2295*12c85518Srobert SortedEnd = SortedUsage.begin() + *MaxNotes;
2296*12c85518Srobert std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);
2297*12c85518Srobert }
2298*12c85518Srobert std::sort(SortedUsage.begin(), SortedEnd, Cmp);
2299*12c85518Srobert
2300*12c85518Srobert // Produce note on sloc address space usage total.
2301*12c85518Srobert uint64_t LocalUsage = NextLocalOffset;
2302*12c85518Srobert uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
2303*12c85518Srobert int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /
2304*12c85518Srobert MaxLoadedOffset);
2305*12c85518Srobert Diag.Report(SourceLocation(), diag::note_total_sloc_usage)
2306*12c85518Srobert << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;
2307*12c85518Srobert
2308*12c85518Srobert // Produce notes on sloc address space usage for each file with a high usage.
2309*12c85518Srobert uint64_t ReportedSize = 0;
2310*12c85518Srobert for (auto &[Entry, FileInfo] :
2311*12c85518Srobert llvm::make_range(SortedUsage.begin(), SortedEnd)) {
2312*12c85518Srobert Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)
2313*12c85518Srobert << FileInfo.Inclusions << FileInfo.DirectSize
2314*12c85518Srobert << (FileInfo.TotalSize - FileInfo.DirectSize);
2315*12c85518Srobert ReportedSize += FileInfo.TotalSize;
2316*12c85518Srobert }
2317*12c85518Srobert
2318*12c85518Srobert // Describe any remaining usage not reported in the per-file usage.
2319*12c85518Srobert if (ReportedSize != CountedSize) {
2320*12c85518Srobert Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)
2321*12c85518Srobert << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
2322*12c85518Srobert }
2323*12c85518Srobert }
2324*12c85518Srobert
2325e5dd7070Spatrick ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2326e5dd7070Spatrick
2327e5dd7070Spatrick /// Return the amount of memory used by memory buffers, breaking down
2328e5dd7070Spatrick /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes() const2329e5dd7070Spatrick SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2330e5dd7070Spatrick size_t malloc_bytes = 0;
2331e5dd7070Spatrick size_t mmap_bytes = 0;
2332e5dd7070Spatrick
2333e5dd7070Spatrick for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2334e5dd7070Spatrick if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2335e5dd7070Spatrick switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2336e5dd7070Spatrick case llvm::MemoryBuffer::MemoryBuffer_MMap:
2337e5dd7070Spatrick mmap_bytes += sized_mapped;
2338e5dd7070Spatrick break;
2339e5dd7070Spatrick case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2340e5dd7070Spatrick malloc_bytes += sized_mapped;
2341e5dd7070Spatrick break;
2342e5dd7070Spatrick }
2343e5dd7070Spatrick
2344e5dd7070Spatrick return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2345e5dd7070Spatrick }
2346e5dd7070Spatrick
getDataStructureSizes() const2347e5dd7070Spatrick size_t SourceManager::getDataStructureSizes() const {
2348e5dd7070Spatrick size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2349e5dd7070Spatrick + llvm::capacity_in_bytes(LocalSLocEntryTable)
2350e5dd7070Spatrick + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2351e5dd7070Spatrick + llvm::capacity_in_bytes(SLocEntryLoaded)
2352e5dd7070Spatrick + llvm::capacity_in_bytes(FileInfos);
2353e5dd7070Spatrick
2354e5dd7070Spatrick if (OverriddenFilesInfo)
2355e5dd7070Spatrick size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2356e5dd7070Spatrick
2357e5dd7070Spatrick return size;
2358e5dd7070Spatrick }
2359e5dd7070Spatrick
SourceManagerForFile(StringRef FileName,StringRef Content)2360e5dd7070Spatrick SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2361e5dd7070Spatrick StringRef Content) {
2362e5dd7070Spatrick // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2363e5dd7070Spatrick // is deleted.
2364e5dd7070Spatrick IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2365e5dd7070Spatrick new llvm::vfs::InMemoryFileSystem);
2366e5dd7070Spatrick InMemoryFileSystem->addFile(
2367e5dd7070Spatrick FileName, 0,
2368e5dd7070Spatrick llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2369e5dd7070Spatrick /*RequiresNullTerminator=*/false));
2370e5dd7070Spatrick // This is passed to `SM` as reference, so the pointer has to be referenced
2371e5dd7070Spatrick // in `Environment` so that `FileMgr` can out-live this function scope.
2372e5dd7070Spatrick FileMgr =
2373e5dd7070Spatrick std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2374e5dd7070Spatrick // This is passed to `SM` as reference, so the pointer has to be referenced
2375e5dd7070Spatrick // by `Environment` due to the same reason above.
2376e5dd7070Spatrick Diagnostics = std::make_unique<DiagnosticsEngine>(
2377e5dd7070Spatrick IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2378e5dd7070Spatrick new DiagnosticOptions);
2379e5dd7070Spatrick SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2380e5dd7070Spatrick FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2381e5dd7070Spatrick SourceLocation(), clang::SrcMgr::C_User);
2382e5dd7070Spatrick assert(ID.isValid());
2383e5dd7070Spatrick SourceMgr->setMainFileID(ID);
2384e5dd7070Spatrick }
2385