1461a67faSDimitry Andric //===- SourceManager.cpp - Track and cache source files -------------------===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten // This file implements the SourceManager interface.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten
13ec2b103cSEd Schouten #include "clang/Basic/SourceManager.h"
144a37f65fSRoman Divacky #include "clang/Basic/Diagnostic.h"
15ec2b103cSEd Schouten #include "clang/Basic/FileManager.h"
16461a67faSDimitry Andric #include "clang/Basic/LLVM.h"
17461a67faSDimitry Andric #include "clang/Basic/SourceLocation.h"
18809500fcSDimitry Andric #include "clang/Basic/SourceManagerInternals.h"
19461a67faSDimitry Andric #include "llvm/ADT/DenseMap.h"
20e3b55780SDimitry Andric #include "llvm/ADT/MapVector.h"
2136981b17SDimitry Andric #include "llvm/ADT/STLExtras.h"
22461a67faSDimitry Andric #include "llvm/ADT/SmallVector.h"
23ac9a064cSDimitry Andric #include "llvm/ADT/Statistic.h"
24461a67faSDimitry Andric #include "llvm/ADT/StringRef.h"
25cfca06d7SDimitry Andric #include "llvm/ADT/StringSwitch.h"
26461a67faSDimitry Andric #include "llvm/Support/Allocator.h"
27809500fcSDimitry Andric #include "llvm/Support/Capacity.h"
28ec2b103cSEd Schouten #include "llvm/Support/Compiler.h"
29344a3780SDimitry Andric #include "llvm/Support/Endian.h"
30461a67faSDimitry Andric #include "llvm/Support/ErrorHandling.h"
31461a67faSDimitry Andric #include "llvm/Support/FileSystem.h"
32461a67faSDimitry Andric #include "llvm/Support/MathExtras.h"
33ec2b103cSEd Schouten #include "llvm/Support/MemoryBuffer.h"
34bca07a45SDimitry Andric #include "llvm/Support/Path.h"
35809500fcSDimitry Andric #include "llvm/Support/raw_ostream.h"
36ec2b103cSEd Schouten #include <algorithm>
37461a67faSDimitry Andric #include <cassert>
38461a67faSDimitry Andric #include <cstddef>
39461a67faSDimitry Andric #include <cstdint>
40461a67faSDimitry Andric #include <memory>
41e3b55780SDimitry Andric #include <optional>
42461a67faSDimitry Andric #include <tuple>
43461a67faSDimitry Andric #include <utility>
44461a67faSDimitry Andric #include <vector>
454a37f65fSRoman Divacky
46ec2b103cSEd Schouten using namespace clang;
47ec2b103cSEd Schouten using namespace SrcMgr;
48ec2b103cSEd Schouten using llvm::MemoryBuffer;
49ec2b103cSEd Schouten
50ac9a064cSDimitry Andric #define DEBUG_TYPE "source-manager"
51ac9a064cSDimitry Andric
52ac9a064cSDimitry Andric // Reaching a limit of 2^31 results in a hard error. This metric allows to track
53ac9a064cSDimitry Andric // if particular invocation of the compiler is close to it.
54ac9a064cSDimitry Andric STATISTIC(MaxUsedSLocBytes, "Maximum number of bytes used by source locations "
55ac9a064cSDimitry Andric "(both loaded and local).");
56ac9a064cSDimitry Andric
57ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
58ec2b103cSEd Schouten // SourceManager Helper Classes
59ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
60ec2b103cSEd Schouten
6136981b17SDimitry Andric /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
6236981b17SDimitry Andric /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
getSizeBytesMapped() const63ec2b103cSEd Schouten unsigned ContentCache::getSizeBytesMapped() const {
64b60736ecSDimitry Andric return Buffer ? Buffer->getBufferSize() : 0;
65ec2b103cSEd Schouten }
66ec2b103cSEd Schouten
6701af97d3SDimitry Andric /// Returns the kind of memory used to back the memory buffer for
6801af97d3SDimitry Andric /// this content cache. This is used for performance analysis.
getMemoryBufferKind() const6901af97d3SDimitry Andric llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
70846a2208SDimitry Andric if (Buffer == nullptr) {
71846a2208SDimitry Andric assert(0 && "Buffer should never be null");
7201af97d3SDimitry Andric return llvm::MemoryBuffer::MemoryBuffer_Malloc;
73846a2208SDimitry Andric }
74b60736ecSDimitry Andric return Buffer->getBufferKind();
7501af97d3SDimitry Andric }
7601af97d3SDimitry Andric
77ec2b103cSEd Schouten /// getSize - Returns the size of the content encapsulated by this ContentCache.
78ec2b103cSEd Schouten /// This can be the size of the source file or the size of an arbitrary
79ec2b103cSEd Schouten /// scratch buffer. If the ContentCache encapsulates a source file, that
8034d02d0bSRoman Divacky /// file is not lazily brought in from disk to satisfy this query.
getSize() const81ec2b103cSEd Schouten unsigned ContentCache::getSize() const {
82b60736ecSDimitry Andric return Buffer ? (unsigned)Buffer->getBufferSize()
8301af97d3SDimitry Andric : (unsigned)ContentsEntry->getSize();
84ec2b103cSEd Schouten }
85ec2b103cSEd Schouten
getInvalidBOM(StringRef BufStr)86706b4fc4SDimitry Andric const char *ContentCache::getInvalidBOM(StringRef BufStr) {
87706b4fc4SDimitry Andric // If the buffer is valid, check to see if it has a UTF Byte Order Mark
88706b4fc4SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See
89706b4fc4SDimitry Andric // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
90706b4fc4SDimitry Andric const char *InvalidBOM =
91706b4fc4SDimitry Andric llvm::StringSwitch<const char *>(BufStr)
92706b4fc4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
93706b4fc4SDimitry Andric "UTF-32 (BE)")
94706b4fc4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
95706b4fc4SDimitry Andric "UTF-32 (LE)")
96706b4fc4SDimitry Andric .StartsWith("\xFE\xFF", "UTF-16 (BE)")
97706b4fc4SDimitry Andric .StartsWith("\xFF\xFE", "UTF-16 (LE)")
98706b4fc4SDimitry Andric .StartsWith("\x2B\x2F\x76", "UTF-7")
99706b4fc4SDimitry Andric .StartsWith("\xF7\x64\x4C", "UTF-1")
100706b4fc4SDimitry Andric .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
101706b4fc4SDimitry Andric .StartsWith("\x0E\xFE\xFF", "SCSU")
102706b4fc4SDimitry Andric .StartsWith("\xFB\xEE\x28", "BOCU-1")
103706b4fc4SDimitry Andric .StartsWith("\x84\x31\x95\x33", "GB-18030")
104706b4fc4SDimitry Andric .Default(nullptr);
105706b4fc4SDimitry Andric
106706b4fc4SDimitry Andric return InvalidBOM;
107706b4fc4SDimitry Andric }
108706b4fc4SDimitry Andric
109e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine & Diag,FileManager & FM,SourceLocation Loc) const110b60736ecSDimitry Andric ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
111b60736ecSDimitry Andric SourceLocation Loc) const {
112bca07a45SDimitry Andric // Lazily create the Buffer for ContentCaches that wrap files. If we already
11301af97d3SDimitry Andric // computed it, just return what we have.
114b60736ecSDimitry Andric if (IsBufferInvalid)
115e3b55780SDimitry Andric return std::nullopt;
116b60736ecSDimitry Andric if (Buffer)
117b60736ecSDimitry Andric return Buffer->getMemBufferRef();
118b60736ecSDimitry Andric if (!ContentsEntry)
119e3b55780SDimitry Andric return std::nullopt;
1204a37f65fSRoman Divacky
121b60736ecSDimitry Andric // Start with the assumption that the buffer is invalid to simplify early
122b60736ecSDimitry Andric // return paths.
123b60736ecSDimitry Andric IsBufferInvalid = true;
12422989816SDimitry Andric
125b1c73532SDimitry Andric auto BufferOrError = FM.getBufferForFile(*ContentsEntry, IsFileVolatile);
12634d02d0bSRoman Divacky
12734d02d0bSRoman Divacky // If we were unable to open the file, then we are in an inconsistent
12834d02d0bSRoman Divacky // situation where the content cache referenced a file which no longer
12934d02d0bSRoman Divacky // exists. Most likely, we were using a stat cache with an invalid entry but
13034d02d0bSRoman Divacky // the file could also have been removed during processing. Since we can't
13134d02d0bSRoman Divacky // really deal with this situation, just create an empty buffer.
13206d4ba38SDimitry Andric if (!BufferOrError) {
13311d2b2d2SRoman Divacky if (Diag.isDiagnosticInFlight())
13411d2b2d2SRoman Divacky Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
13506d4ba38SDimitry Andric ContentsEntry->getName(),
13606d4ba38SDimitry Andric BufferOrError.getError().message());
13711d2b2d2SRoman Divacky else
138bca07a45SDimitry Andric Diag.Report(Loc, diag::err_cannot_open_file)
13906d4ba38SDimitry Andric << ContentsEntry->getName() << BufferOrError.getError().message();
14011d2b2d2SRoman Divacky
141e3b55780SDimitry Andric return std::nullopt;
142bca07a45SDimitry Andric }
143bca07a45SDimitry Andric
144b60736ecSDimitry Andric Buffer = std::move(*BufferOrError);
14506d4ba38SDimitry Andric
146b60736ecSDimitry Andric // Check that the file's size fits in an 'unsigned' (with room for a
147b60736ecSDimitry Andric // past-the-end value). This is deeply regrettable, but various parts of
148b60736ecSDimitry Andric // Clang (including elsewhere in this file!) use 'unsigned' to represent file
149b60736ecSDimitry Andric // offsets, line numbers, string literal lengths, and so on, and fail
150b60736ecSDimitry Andric // miserably on large source files.
151b60736ecSDimitry Andric //
152b60736ecSDimitry Andric // Note: ContentsEntry could be a named pipe, in which case
153b60736ecSDimitry Andric // ContentsEntry::getSize() could have the wrong size. Use
154b60736ecSDimitry Andric // MemoryBuffer::getBufferSize() instead.
155b60736ecSDimitry Andric if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
156b60736ecSDimitry Andric if (Diag.isDiagnosticInFlight())
157b60736ecSDimitry Andric Diag.SetDelayedDiagnostic(diag::err_file_too_large,
158b60736ecSDimitry Andric ContentsEntry->getName());
159b60736ecSDimitry Andric else
160b60736ecSDimitry Andric Diag.Report(Loc, diag::err_file_too_large)
161b60736ecSDimitry Andric << ContentsEntry->getName();
162b60736ecSDimitry Andric
163e3b55780SDimitry Andric return std::nullopt;
164b60736ecSDimitry Andric }
165b60736ecSDimitry Andric
166b60736ecSDimitry Andric // Unless this is a named pipe (in which case we can handle a mismatch),
167b60736ecSDimitry Andric // check that the file's size is the same as in the file entry (which may
168bca07a45SDimitry Andric // have come from a stat cache).
169b60736ecSDimitry Andric if (!ContentsEntry->isNamedPipe() &&
170b60736ecSDimitry Andric Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
17111d2b2d2SRoman Divacky if (Diag.isDiagnosticInFlight())
17211d2b2d2SRoman Divacky Diag.SetDelayedDiagnostic(diag::err_file_modified,
17301af97d3SDimitry Andric ContentsEntry->getName());
17411d2b2d2SRoman Divacky else
175bca07a45SDimitry Andric Diag.Report(Loc, diag::err_file_modified)
17601af97d3SDimitry Andric << ContentsEntry->getName();
17711d2b2d2SRoman Divacky
178e3b55780SDimitry Andric return std::nullopt;
1790883ccd9SRoman Divacky }
1800883ccd9SRoman Divacky
1810883ccd9SRoman Divacky // If the buffer is valid, check to see if it has a UTF Byte Order Mark
18201af97d3SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See
1830883ccd9SRoman Divacky // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
184b60736ecSDimitry Andric StringRef BufStr = Buffer->getBuffer();
185706b4fc4SDimitry Andric const char *InvalidBOM = getInvalidBOM(BufStr);
1860883ccd9SRoman Divacky
18701af97d3SDimitry Andric if (InvalidBOM) {
188bca07a45SDimitry Andric Diag.Report(Loc, diag::err_unsupported_bom)
18901af97d3SDimitry Andric << InvalidBOM << ContentsEntry->getName();
190e3b55780SDimitry Andric return std::nullopt;
1914a37f65fSRoman Divacky }
1924a37f65fSRoman Divacky
193b60736ecSDimitry Andric // Buffer has been validated.
194b60736ecSDimitry Andric IsBufferInvalid = false;
195b60736ecSDimitry Andric return Buffer->getMemBufferRef();
196ec2b103cSEd Schouten }
197ec2b103cSEd Schouten
getLineTableFilenameID(StringRef Name)19836981b17SDimitry Andric unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
199676fbe81SDimitry Andric auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
20006d4ba38SDimitry Andric if (IterBool.second)
20106d4ba38SDimitry Andric FilenamesByID.push_back(&*IterBool.first);
20206d4ba38SDimitry Andric return IterBool.first->second;
203ec2b103cSEd Schouten }
204ec2b103cSEd Schouten
205b5aee35cSDimitry Andric /// Add a line note to the line table that indicates that there is a \#line or
206b5aee35cSDimitry Andric /// GNU line marker at the specified FID/Offset location which changes the
207b5aee35cSDimitry Andric /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
208b5aee35cSDimitry Andric /// change the presumed \#include stack. If it is 1, this is a file entry, if
209b5aee35cSDimitry Andric /// it is 2 then this is a file exit. FileKind specifies whether this is a
210b5aee35cSDimitry Andric /// system header or extern C system header.
AddLineNote(FileID FID,unsigned Offset,unsigned LineNo,int FilenameID,unsigned EntryExit,SrcMgr::CharacteristicKind FileKind)211b5aee35cSDimitry Andric void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
212b5aee35cSDimitry Andric int FilenameID, unsigned EntryExit,
213ec2b103cSEd Schouten SrcMgr::CharacteristicKind FileKind) {
214ec2b103cSEd Schouten std::vector<LineEntry> &Entries = LineEntries[FID];
215ec2b103cSEd Schouten
216ec2b103cSEd Schouten assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
217ec2b103cSEd Schouten "Adding line entries out of order!");
218ec2b103cSEd Schouten
219ec2b103cSEd Schouten unsigned IncludeOffset = 0;
220c0981da4SDimitry Andric if (EntryExit == 1) {
221c0981da4SDimitry Andric // Push #include
222ec2b103cSEd Schouten IncludeOffset = Offset-1;
223c0981da4SDimitry Andric } else {
224c0981da4SDimitry Andric const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
225c0981da4SDimitry Andric if (EntryExit == 2) {
226c0981da4SDimitry Andric // Pop #include
227c0981da4SDimitry Andric assert(PrevEntry && PrevEntry->IncludeOffset &&
228c0981da4SDimitry Andric "PPDirectives should have caught case when popping empty include "
229c0981da4SDimitry Andric "stack");
230c0981da4SDimitry Andric PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
231c0981da4SDimitry Andric }
232c0981da4SDimitry Andric if (PrevEntry) {
233ec2b103cSEd Schouten IncludeOffset = PrevEntry->IncludeOffset;
234c0981da4SDimitry Andric if (FilenameID == -1) {
235c0981da4SDimitry Andric // An unspecified FilenameID means use the previous (or containing)
236c0981da4SDimitry Andric // filename if available, or the main source file otherwise.
237c0981da4SDimitry Andric FilenameID = PrevEntry->FilenameID;
238c0981da4SDimitry Andric }
239c0981da4SDimitry Andric }
240ec2b103cSEd Schouten }
241ec2b103cSEd Schouten
242ec2b103cSEd Schouten Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
243ec2b103cSEd Schouten IncludeOffset));
244ec2b103cSEd Schouten }
245ec2b103cSEd Schouten
246ec2b103cSEd Schouten /// FindNearestLineEntry - Find the line entry nearest to FID that is before
247ec2b103cSEd Schouten /// it. If there is no line entry before Offset in FID, return null.
FindNearestLineEntry(FileID FID,unsigned Offset)24856d91b49SDimitry Andric const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
249ec2b103cSEd Schouten unsigned Offset) {
250ec2b103cSEd Schouten const std::vector<LineEntry> &Entries = LineEntries[FID];
251ec2b103cSEd Schouten assert(!Entries.empty() && "No #line entries for this FID after all!");
252ec2b103cSEd Schouten
253ec2b103cSEd Schouten // It is very common for the query to be after the last #line, check this
254ec2b103cSEd Schouten // first.
255ec2b103cSEd Schouten if (Entries.back().FileOffset <= Offset)
256ec2b103cSEd Schouten return &Entries.back();
257ec2b103cSEd Schouten
258ec2b103cSEd Schouten // Do a binary search to find the maximal element that is still before Offset.
25922989816SDimitry Andric std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
26022989816SDimitry Andric if (I == Entries.begin())
26122989816SDimitry Andric return nullptr;
262ec2b103cSEd Schouten return &*--I;
263ec2b103cSEd Schouten }
264ec2b103cSEd Schouten
26548675466SDimitry Andric /// Add a new line entry that has already been encoded into
266ec2b103cSEd Schouten /// the internal representation of the line table.
AddEntry(FileID FID,const std::vector<LineEntry> & Entries)26756d91b49SDimitry Andric void LineTableInfo::AddEntry(FileID FID,
268ec2b103cSEd Schouten const std::vector<LineEntry> &Entries) {
269ec2b103cSEd Schouten LineEntries[FID] = Entries;
270ec2b103cSEd Schouten }
271ec2b103cSEd Schouten
272ec2b103cSEd Schouten /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
getLineTableFilenameID(StringRef Name)27336981b17SDimitry Andric unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
27445b53394SDimitry Andric return getLineTable().getLineTableFilenameID(Name);
275ec2b103cSEd Schouten }
276ec2b103cSEd Schouten
277ec2b103cSEd Schouten /// AddLineNote - Add a line note to the line table for the FileID and offset
278ec2b103cSEd Schouten /// specified by Loc. If FilenameID is -1, it is considered to be
279ec2b103cSEd Schouten /// unspecified.
AddLineNote(SourceLocation Loc,unsigned LineNo,int FilenameID,bool IsFileEntry,bool IsFileExit,SrcMgr::CharacteristicKind FileKind)280ec2b103cSEd Schouten void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
281ec2b103cSEd Schouten int FilenameID, bool IsFileEntry,
282b5aee35cSDimitry Andric bool IsFileExit,
283b5aee35cSDimitry Andric SrcMgr::CharacteristicKind FileKind) {
28436981b17SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
28501af97d3SDimitry Andric
28601af97d3SDimitry Andric bool Invalid = false;
287ac9a064cSDimitry Andric SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
28801af97d3SDimitry Andric if (!Entry.isFile() || Invalid)
28901af97d3SDimitry Andric return;
29001af97d3SDimitry Andric
291ac9a064cSDimitry Andric SrcMgr::FileInfo &FileInfo = Entry.getFile();
292ec2b103cSEd Schouten
293ec2b103cSEd Schouten // Remember that this file has #line directives now if it doesn't already.
294ac9a064cSDimitry Andric FileInfo.setHasLineDirectives();
295ec2b103cSEd Schouten
29645b53394SDimitry Andric (void) getLineTable();
297ec2b103cSEd Schouten
298ec2b103cSEd Schouten unsigned EntryExit = 0;
299ec2b103cSEd Schouten if (IsFileEntry)
300ec2b103cSEd Schouten EntryExit = 1;
301ec2b103cSEd Schouten else if (IsFileExit)
302ec2b103cSEd Schouten EntryExit = 2;
303ec2b103cSEd Schouten
30456d91b49SDimitry Andric LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
305ec2b103cSEd Schouten EntryExit, FileKind);
306ec2b103cSEd Schouten }
307ec2b103cSEd Schouten
getLineTable()308ec2b103cSEd Schouten LineTableInfo &SourceManager::getLineTable() {
3099f4dbff6SDimitry Andric if (!LineTable)
31022989816SDimitry Andric LineTable.reset(new LineTableInfo());
311ec2b103cSEd Schouten return *LineTable;
312ec2b103cSEd Schouten }
313ec2b103cSEd Schouten
314ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
315ec2b103cSEd Schouten // Private 'Create' methods.
316ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
317ec2b103cSEd Schouten
SourceManager(DiagnosticsEngine & Diag,FileManager & FileMgr,bool UserFilesAreVolatile)31856d91b49SDimitry Andric SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
31956d91b49SDimitry Andric bool UserFilesAreVolatile)
320461a67faSDimitry Andric : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
321bca07a45SDimitry Andric clearIDTables();
322bca07a45SDimitry Andric Diag.setSourceManager(this);
323bca07a45SDimitry Andric }
324bca07a45SDimitry Andric
~SourceManager()325ec2b103cSEd Schouten SourceManager::~SourceManager() {
326ec2b103cSEd Schouten // Delete FileEntry objects corresponding to content caches. Since the actual
327ec2b103cSEd Schouten // content cache objects are bump pointer allocated, we just have to run the
328ec2b103cSEd Schouten // dtors, but we call the deallocate method for completeness.
329ec2b103cSEd Schouten for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
330dbe13110SDimitry Andric if (MemBufferInfos[i]) {
331ec2b103cSEd Schouten MemBufferInfos[i]->~ContentCache();
332ec2b103cSEd Schouten ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
333ec2b103cSEd Schouten }
334dbe13110SDimitry Andric }
335b1c73532SDimitry Andric for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
336dbe13110SDimitry Andric if (I->second) {
337ec2b103cSEd Schouten I->second->~ContentCache();
338ec2b103cSEd Schouten ContentCacheAlloc.Deallocate(I->second);
339ec2b103cSEd Schouten }
340dbe13110SDimitry Andric }
341ec2b103cSEd Schouten }
342ec2b103cSEd Schouten
clearIDTables()343ec2b103cSEd Schouten void SourceManager::clearIDTables() {
344ec2b103cSEd Schouten MainFileID = FileID();
34536981b17SDimitry Andric LocalSLocEntryTable.clear();
34636981b17SDimitry Andric LoadedSLocEntryTable.clear();
34736981b17SDimitry Andric SLocEntryLoaded.clear();
348b1c73532SDimitry Andric SLocEntryOffsetLoaded.clear();
349ec2b103cSEd Schouten LastLineNoFileIDQuery = FileID();
3509f4dbff6SDimitry Andric LastLineNoContentCache = nullptr;
351ec2b103cSEd Schouten LastFileIDLookup = FileID();
352ec2b103cSEd Schouten
353ec2b103cSEd Schouten if (LineTable)
354ec2b103cSEd Schouten LineTable->clear();
355ec2b103cSEd Schouten
35636981b17SDimitry Andric // Use up FileID #0 as an invalid expansion.
35736981b17SDimitry Andric NextLocalOffset = 0;
35836981b17SDimitry Andric CurrentLoadedOffset = MaxLoadedOffset;
35936981b17SDimitry Andric createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
360ec2b103cSEd Schouten }
361ec2b103cSEd Schouten
isMainFile(const FileEntry & SourceFile)362b60736ecSDimitry Andric bool SourceManager::isMainFile(const FileEntry &SourceFile) {
363cfca06d7SDimitry Andric assert(MainFileID.isValid() && "expected initialized SourceManager");
364b60736ecSDimitry Andric if (auto *FE = getFileEntryForID(MainFileID))
365cfca06d7SDimitry Andric return FE->getUID() == SourceFile.getUID();
366b60736ecSDimitry Andric return false;
367cfca06d7SDimitry Andric }
368cfca06d7SDimitry Andric
initializeForReplay(const SourceManager & Old)3691b08b196SDimitry Andric void SourceManager::initializeForReplay(const SourceManager &Old) {
3701b08b196SDimitry Andric assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
3711b08b196SDimitry Andric
3721b08b196SDimitry Andric auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
3731b08b196SDimitry Andric auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
3741b08b196SDimitry Andric Clone->OrigEntry = Cache->OrigEntry;
3751b08b196SDimitry Andric Clone->ContentsEntry = Cache->ContentsEntry;
3761b08b196SDimitry Andric Clone->BufferOverridden = Cache->BufferOverridden;
377519fc96cSDimitry Andric Clone->IsFileVolatile = Cache->IsFileVolatile;
3781b08b196SDimitry Andric Clone->IsTransient = Cache->IsTransient;
379b60736ecSDimitry Andric Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
3801b08b196SDimitry Andric return Clone;
3811b08b196SDimitry Andric };
3821b08b196SDimitry Andric
3831b08b196SDimitry Andric // Ensure all SLocEntries are loaded from the external source.
3841b08b196SDimitry Andric for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
3851b08b196SDimitry Andric if (!Old.SLocEntryLoaded[I])
3861b08b196SDimitry Andric Old.loadSLocEntry(I, nullptr);
3871b08b196SDimitry Andric
3881b08b196SDimitry Andric // Inherit any content cache data from the old source manager.
3891b08b196SDimitry Andric for (auto &FileInfo : Old.FileInfos) {
3901b08b196SDimitry Andric SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
3911b08b196SDimitry Andric if (Slot)
3921b08b196SDimitry Andric continue;
3931b08b196SDimitry Andric Slot = CloneContentCache(FileInfo.second);
3941b08b196SDimitry Andric }
3951b08b196SDimitry Andric }
3961b08b196SDimitry Andric
getOrCreateContentCache(FileEntryRef FileEnt,bool isSystemFile)397b60736ecSDimitry Andric ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
39856d91b49SDimitry Andric bool isSystemFile) {
399ec2b103cSEd Schouten // Do we already have information about this file?
400ec2b103cSEd Schouten ContentCache *&Entry = FileInfos[FileEnt];
401b60736ecSDimitry Andric if (Entry)
402b60736ecSDimitry Andric return *Entry;
403ec2b103cSEd Schouten
4049f4dbff6SDimitry Andric // Nope, create a new Cache entry.
4059f4dbff6SDimitry Andric Entry = ContentCacheAlloc.Allocate<ContentCache>();
40601af97d3SDimitry Andric
40756d91b49SDimitry Andric if (OverriddenFilesInfo) {
40801af97d3SDimitry Andric // If the file contents are overridden with contents from another file,
40901af97d3SDimitry Andric // pass that file to ContentCache.
410e3b55780SDimitry Andric auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
41156d91b49SDimitry Andric if (overI == OverriddenFilesInfo->OverriddenFiles.end())
412ec2b103cSEd Schouten new (Entry) ContentCache(FileEnt);
41301af97d3SDimitry Andric else
41401af97d3SDimitry Andric new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
41501af97d3SDimitry Andric : overI->second,
41601af97d3SDimitry Andric overI->second);
41756d91b49SDimitry Andric } else {
41856d91b49SDimitry Andric new (Entry) ContentCache(FileEnt);
41956d91b49SDimitry Andric }
42056d91b49SDimitry Andric
421519fc96cSDimitry Andric Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
42245b53394SDimitry Andric Entry->IsTransient = FilesAreTransient;
423b60736ecSDimitry Andric Entry->BufferOverridden |= FileEnt.isNamedPipe();
42401af97d3SDimitry Andric
425b60736ecSDimitry Andric return *Entry;
426ec2b103cSEd Schouten }
427ec2b103cSEd Schouten
428461a67faSDimitry Andric /// Create a new ContentCache for the specified memory buffer.
429461a67faSDimitry Andric /// This does no caching.
createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buffer)430b60736ecSDimitry Andric ContentCache &SourceManager::createMemBufferContentCache(
431b60736ecSDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer) {
4329f4dbff6SDimitry Andric // Add a new ContentCache to the MemBufferInfos list and return it.
4339f4dbff6SDimitry Andric ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
434ec2b103cSEd Schouten new (Entry) ContentCache();
435ec2b103cSEd Schouten MemBufferInfos.push_back(Entry);
436b60736ecSDimitry Andric Entry->setBuffer(std::move(Buffer));
437b60736ecSDimitry Andric return *Entry;
438ec2b103cSEd Schouten }
439ec2b103cSEd Schouten
loadSLocEntry(unsigned Index,bool * Invalid) const440dbe13110SDimitry Andric const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
441dbe13110SDimitry Andric bool *Invalid) const {
442ac9a064cSDimitry Andric return const_cast<SourceManager *>(this)->loadSLocEntry(Index, Invalid);
443ac9a064cSDimitry Andric }
444ac9a064cSDimitry Andric
loadSLocEntry(unsigned Index,bool * Invalid)445ac9a064cSDimitry Andric SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, bool *Invalid) {
446dbe13110SDimitry Andric assert(!SLocEntryLoaded[Index]);
447dbe13110SDimitry Andric if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
448dbe13110SDimitry Andric if (Invalid)
449dbe13110SDimitry Andric *Invalid = true;
450dbe13110SDimitry Andric // If the file of the SLocEntry changed we could still have loaded it.
451dbe13110SDimitry Andric if (!SLocEntryLoaded[Index]) {
452dbe13110SDimitry Andric // Try to recover; create a SLocEntry so the rest of clang can handle it.
453b60736ecSDimitry Andric if (!FakeSLocEntryForRecovery)
454b60736ecSDimitry Andric FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
455519fc96cSDimitry Andric 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
456b60736ecSDimitry Andric SrcMgr::C_User, "")));
457b60736ecSDimitry Andric return *FakeSLocEntryForRecovery;
458dbe13110SDimitry Andric }
459dbe13110SDimitry Andric }
460dbe13110SDimitry Andric
461dbe13110SDimitry Andric return LoadedSLocEntryTable[Index];
462dbe13110SDimitry Andric }
463dbe13110SDimitry Andric
464344a3780SDimitry Andric std::pair<int, SourceLocation::UIntTy>
AllocateLoadedSLocEntries(unsigned NumSLocEntries,SourceLocation::UIntTy TotalSize)46536981b17SDimitry Andric SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
466344a3780SDimitry Andric SourceLocation::UIntTy TotalSize) {
46736981b17SDimitry Andric assert(ExternalSLocEntries && "Don't have an external sloc source");
46845b53394SDimitry Andric // Make sure we're not about to run out of source locations.
469e3b55780SDimitry Andric if (CurrentLoadedOffset < TotalSize ||
470e3b55780SDimitry Andric CurrentLoadedOffset - TotalSize < NextLocalOffset) {
47145b53394SDimitry Andric return std::make_pair(0, 0);
472e3b55780SDimitry Andric }
47336981b17SDimitry Andric LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
47436981b17SDimitry Andric SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
475b1c73532SDimitry Andric SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());
47636981b17SDimitry Andric CurrentLoadedOffset -= TotalSize;
477ac9a064cSDimitry Andric updateSlocUsageStats();
478b1c73532SDimitry Andric int BaseID = -int(LoadedSLocEntryTable.size()) - 1;
479b1c73532SDimitry Andric LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));
480b1c73532SDimitry Andric return std::make_pair(BaseID, CurrentLoadedOffset);
481ec2b103cSEd Schouten }
482ec2b103cSEd Schouten
48348675466SDimitry Andric /// As part of recovering from missing or changed content, produce a
48401af97d3SDimitry Andric /// fake, non-empty buffer.
getFakeBufferForRecovery() const485b60736ecSDimitry Andric llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
48601af97d3SDimitry Andric if (!FakeBufferForRecovery)
48706d4ba38SDimitry Andric FakeBufferForRecovery =
48806d4ba38SDimitry Andric llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
48901af97d3SDimitry Andric
490b60736ecSDimitry Andric return *FakeBufferForRecovery;
49101af97d3SDimitry Andric }
492ec2b103cSEd Schouten
49348675466SDimitry Andric /// As part of recovering from missing or changed content, produce a
494dbe13110SDimitry Andric /// fake content cache.
getFakeContentCacheForRecovery() const495b60736ecSDimitry Andric SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
496dbe13110SDimitry Andric if (!FakeContentCacheForRecovery) {
497519fc96cSDimitry Andric FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
498b60736ecSDimitry Andric FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
499dbe13110SDimitry Andric }
500b60736ecSDimitry Andric return *FakeContentCacheForRecovery;
501dbe13110SDimitry Andric }
502dbe13110SDimitry Andric
50348675466SDimitry Andric /// Returns the previous in-order FileID or an invalid FileID if there
504bfef3995SDimitry Andric /// is no previous one.
getPreviousFileID(FileID FID) const505bfef3995SDimitry Andric FileID SourceManager::getPreviousFileID(FileID FID) const {
506bfef3995SDimitry Andric if (FID.isInvalid())
507bfef3995SDimitry Andric return FileID();
508bfef3995SDimitry Andric
509bfef3995SDimitry Andric int ID = FID.ID;
510bfef3995SDimitry Andric if (ID == -1)
511bfef3995SDimitry Andric return FileID();
512bfef3995SDimitry Andric
513bfef3995SDimitry Andric if (ID > 0) {
514bfef3995SDimitry Andric if (ID-1 == 0)
515bfef3995SDimitry Andric return FileID();
516bfef3995SDimitry Andric } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
517bfef3995SDimitry Andric return FileID();
518bfef3995SDimitry Andric }
519bfef3995SDimitry Andric
520bfef3995SDimitry Andric return FileID::get(ID-1);
521bfef3995SDimitry Andric }
522bfef3995SDimitry Andric
52348675466SDimitry Andric /// Returns the next in-order FileID or an invalid FileID if there is
524bfef3995SDimitry Andric /// no next one.
getNextFileID(FileID FID) const525bfef3995SDimitry Andric FileID SourceManager::getNextFileID(FileID FID) const {
526bfef3995SDimitry Andric if (FID.isInvalid())
527bfef3995SDimitry Andric return FileID();
528bfef3995SDimitry Andric
529bfef3995SDimitry Andric int ID = FID.ID;
530bfef3995SDimitry Andric if (ID > 0) {
531bfef3995SDimitry Andric if (unsigned(ID+1) >= local_sloc_entry_size())
532bfef3995SDimitry Andric return FileID();
533bfef3995SDimitry Andric } else if (ID+1 >= -1) {
534bfef3995SDimitry Andric return FileID();
535bfef3995SDimitry Andric }
536bfef3995SDimitry Andric
537bfef3995SDimitry Andric return FileID::get(ID+1);
538bfef3995SDimitry Andric }
539bfef3995SDimitry Andric
540ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
54136981b17SDimitry Andric // Methods to create new FileID's and macro expansions.
542ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
543ec2b103cSEd Schouten
544cfca06d7SDimitry Andric /// Create a new FileID that represents the specified file
545cfca06d7SDimitry Andric /// being \#included from the specified IncludePosition.
createFileID(FileEntryRef SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)546cfca06d7SDimitry Andric FileID SourceManager::createFileID(FileEntryRef SourceFile,
547cfca06d7SDimitry Andric SourceLocation IncludePos,
548cfca06d7SDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
549344a3780SDimitry Andric int LoadedID,
550344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
551b60736ecSDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
552b60736ecSDimitry Andric isSystem(FileCharacter));
553b60736ecSDimitry Andric
554b60736ecSDimitry Andric // If this is a named pipe, immediately load the buffer to ensure subsequent
555b60736ecSDimitry Andric // calls to ContentCache::getSize() are accurate.
556b60736ecSDimitry Andric if (IR.ContentsEntry->isNamedPipe())
557b60736ecSDimitry Andric (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
558b60736ecSDimitry Andric
559b60736ecSDimitry Andric return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
560cfca06d7SDimitry Andric LoadedID, LoadedOffset);
561cfca06d7SDimitry Andric }
562cfca06d7SDimitry Andric
563cfca06d7SDimitry Andric /// Create a new FileID that represents the specified memory buffer.
564cfca06d7SDimitry Andric ///
565cfca06d7SDimitry Andric /// This does no caching of the buffer and takes ownership of the
566cfca06d7SDimitry Andric /// 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)567cfca06d7SDimitry Andric FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
568cfca06d7SDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
569344a3780SDimitry Andric int LoadedID,
570344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset,
571cfca06d7SDimitry Andric SourceLocation IncludeLoc) {
572cfca06d7SDimitry Andric StringRef Name = Buffer->getBufferIdentifier();
573b60736ecSDimitry Andric return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
574b60736ecSDimitry Andric IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
575cfca06d7SDimitry Andric }
576cfca06d7SDimitry Andric
577cfca06d7SDimitry Andric /// Create a new FileID that represents the specified memory buffer.
578cfca06d7SDimitry Andric ///
579cfca06d7SDimitry Andric /// This does not take ownership of the MemoryBuffer. The memory buffer must
580cfca06d7SDimitry Andric /// outlive the SourceManager.
createFileID(const llvm::MemoryBufferRef & Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset,SourceLocation IncludeLoc)581b60736ecSDimitry Andric FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
582cfca06d7SDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
583344a3780SDimitry Andric int LoadedID,
584344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset,
585cfca06d7SDimitry Andric SourceLocation IncludeLoc) {
586b60736ecSDimitry Andric return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
587b60736ecSDimitry Andric LoadedID, LoadedOffset, IncludeLoc);
588cfca06d7SDimitry Andric }
589cfca06d7SDimitry Andric
590cfca06d7SDimitry Andric /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
591cfca06d7SDimitry Andric /// new FileID for the \p SourceFile.
592cfca06d7SDimitry Andric FileID
getOrCreateFileID(FileEntryRef SourceFile,SrcMgr::CharacteristicKind FileCharacter)593b1c73532SDimitry Andric SourceManager::getOrCreateFileID(FileEntryRef SourceFile,
594cfca06d7SDimitry Andric SrcMgr::CharacteristicKind FileCharacter) {
595cfca06d7SDimitry Andric FileID ID = translateFile(SourceFile);
596cfca06d7SDimitry Andric return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
597cfca06d7SDimitry Andric FileCharacter);
598cfca06d7SDimitry Andric }
599cfca06d7SDimitry Andric
6003d1dcd9bSDimitry Andric /// createFileID - Create a new FileID for the specified ContentCache and
601ec2b103cSEd Schouten /// include position. This works regardless of whether the ContentCache
602ec2b103cSEd Schouten /// corresponds to a file or some other input source.
createFileIDImpl(ContentCache & File,StringRef Filename,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)603b60736ecSDimitry Andric FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
604ec2b103cSEd Schouten SourceLocation IncludePos,
605ec2b103cSEd Schouten SrcMgr::CharacteristicKind FileCharacter,
606344a3780SDimitry Andric int LoadedID,
607344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
60836981b17SDimitry Andric if (LoadedID < 0) {
60936981b17SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID");
61036981b17SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2;
61136981b17SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
61236981b17SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded");
613519fc96cSDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get(
614519fc96cSDimitry Andric LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
615b1c73532SDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
61636981b17SDimitry Andric return FileID::get(LoadedID);
617ec2b103cSEd Schouten }
618b60736ecSDimitry Andric unsigned FileSize = File.getSize();
619cfca06d7SDimitry Andric if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
620cfca06d7SDimitry Andric NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
621b1c73532SDimitry Andric Diag.Report(IncludePos, diag::err_sloc_space_too_large);
622e3b55780SDimitry Andric noteSLocAddressSpaceUsage(Diag);
623cfca06d7SDimitry Andric return FileID();
624cfca06d7SDimitry Andric }
625519fc96cSDimitry Andric LocalSLocEntryTable.push_back(
626519fc96cSDimitry Andric SLocEntry::get(NextLocalOffset,
627519fc96cSDimitry Andric FileInfo::get(IncludePos, File, FileCharacter, Filename)));
62836981b17SDimitry Andric // We do a +1 here because we want a SourceLocation that means "the end of the
62936981b17SDimitry Andric // file", e.g. for the "no newline at the end of the file" diagnostic.
63036981b17SDimitry Andric NextLocalOffset += FileSize + 1;
631ac9a064cSDimitry Andric updateSlocUsageStats();
632ec2b103cSEd Schouten
633ec2b103cSEd Schouten // Set LastFileIDLookup to the newly created file. The next getFileID call is
634ec2b103cSEd Schouten // almost guaranteed to be from that file.
63536981b17SDimitry Andric FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
636d6aff018SEd Schouten return LastFileIDLookup = FID;
637ec2b103cSEd Schouten }
638ec2b103cSEd Schouten
createMacroArgExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLoc,unsigned Length)639145449b1SDimitry Andric SourceLocation SourceManager::createMacroArgExpansionLoc(
640145449b1SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
64136981b17SDimitry Andric ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
64236981b17SDimitry Andric ExpansionLoc);
643145449b1SDimitry Andric return createExpansionLocImpl(Info, Length);
644180abc3dSDimitry Andric }
645180abc3dSDimitry Andric
createExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned Length,bool ExpansionIsTokenRange,int LoadedID,SourceLocation::UIntTy LoadedOffset)646344a3780SDimitry Andric SourceLocation SourceManager::createExpansionLoc(
647344a3780SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
648145449b1SDimitry Andric SourceLocation ExpansionLocEnd, unsigned Length,
649344a3780SDimitry Andric bool ExpansionIsTokenRange, int LoadedID,
650344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
65148675466SDimitry Andric ExpansionInfo Info = ExpansionInfo::create(
65248675466SDimitry Andric SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
653145449b1SDimitry Andric return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
654ec2b103cSEd Schouten }
65536981b17SDimitry Andric
createTokenSplitLoc(SourceLocation Spelling,SourceLocation TokenStart,SourceLocation TokenEnd)65648675466SDimitry Andric SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
65748675466SDimitry Andric SourceLocation TokenStart,
65848675466SDimitry Andric SourceLocation TokenEnd) {
65948675466SDimitry Andric assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
66048675466SDimitry Andric "token spans multiple files");
66148675466SDimitry Andric return createExpansionLocImpl(
66248675466SDimitry Andric ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
66348675466SDimitry Andric TokenEnd.getOffset() - TokenStart.getOffset());
66448675466SDimitry Andric }
66548675466SDimitry Andric
66636981b17SDimitry Andric SourceLocation
createExpansionLocImpl(const ExpansionInfo & Info,unsigned Length,int LoadedID,SourceLocation::UIntTy LoadedOffset)66736981b17SDimitry Andric SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
668145449b1SDimitry Andric unsigned Length, int LoadedID,
669344a3780SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
67036981b17SDimitry Andric if (LoadedID < 0) {
67136981b17SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID");
67236981b17SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2;
67336981b17SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
67436981b17SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded");
67536981b17SDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
676b1c73532SDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
67736981b17SDimitry Andric return SourceLocation::getMacroLoc(LoadedOffset);
67836981b17SDimitry Andric }
67936981b17SDimitry Andric LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
680b1c73532SDimitry Andric if (NextLocalOffset + Length + 1 <= NextLocalOffset ||
681b1c73532SDimitry Andric NextLocalOffset + Length + 1 > CurrentLoadedOffset) {
682b1c73532SDimitry Andric Diag.Report(SourceLocation(), diag::err_sloc_space_too_large);
683b1c73532SDimitry Andric // FIXME: call `noteSLocAddressSpaceUsage` to report details to users and
684b1c73532SDimitry Andric // use a source location from `Info` to point at an error.
685b1c73532SDimitry Andric // Currently, both cause Clang to run indefinitely, this needs to be fixed.
686b1c73532SDimitry Andric // FIXME: return an error instead of crashing. Returning invalid source
687b1c73532SDimitry Andric // locations causes compiler to run indefinitely.
688b1c73532SDimitry Andric llvm::report_fatal_error("ran out of source locations");
689b1c73532SDimitry Andric }
69036981b17SDimitry Andric // See createFileID for that +1.
691145449b1SDimitry Andric NextLocalOffset += Length + 1;
692ac9a064cSDimitry Andric updateSlocUsageStats();
693145449b1SDimitry Andric return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
694ec2b103cSEd Schouten }
695ec2b103cSEd Schouten
696e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(FileEntryRef File)697b1c73532SDimitry Andric SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) {
698b1c73532SDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(File);
699b60736ecSDimitry Andric return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
70034d02d0bSRoman Divacky }
70134d02d0bSRoman Divacky
overrideFileContents(FileEntryRef SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)702b60736ecSDimitry Andric void SourceManager::overrideFileContents(
703b1c73532SDimitry Andric FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
704b1c73532SDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);
70534d02d0bSRoman Divacky
706b60736ecSDimitry Andric IR.setBuffer(std::move(Buffer));
707b60736ecSDimitry Andric IR.BufferOverridden = true;
70856d91b49SDimitry Andric
70956d91b49SDimitry Andric getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
71034d02d0bSRoman Divacky }
71134d02d0bSRoman Divacky
overrideFileContents(const FileEntry * SourceFile,FileEntryRef NewFile)71201af97d3SDimitry Andric void SourceManager::overrideFileContents(const FileEntry *SourceFile,
713e3b55780SDimitry Andric FileEntryRef NewFile) {
714e3b55780SDimitry Andric assert(SourceFile->getSize() == NewFile.getSize() &&
71501af97d3SDimitry Andric "Different sizes, use the FileManager to create a virtual file with "
71601af97d3SDimitry Andric "the correct size");
717b1c73532SDimitry Andric assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&
71801af97d3SDimitry Andric "This function should be called at the initialization stage, before "
71901af97d3SDimitry Andric "any parsing occurs.");
720e3b55780SDimitry Andric // FileEntryRef is not default-constructible.
721e3b55780SDimitry Andric auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
722e3b55780SDimitry Andric std::make_pair(SourceFile, NewFile));
723e3b55780SDimitry Andric if (!Pair.second)
724e3b55780SDimitry Andric Pair.first->second = NewFile;
72556d91b49SDimitry Andric }
72656d91b49SDimitry Andric
727e3b55780SDimitry Andric OptionalFileEntryRef
bypassFileContentsOverride(FileEntryRef File)728b60736ecSDimitry Andric SourceManager::bypassFileContentsOverride(FileEntryRef File) {
729b60736ecSDimitry Andric assert(isFileOverridden(&File.getFileEntry()));
730e3b55780SDimitry Andric OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
73156d91b49SDimitry Andric
732519fc96cSDimitry Andric // If the file can't be found in the FS, give up.
733519fc96cSDimitry Andric if (!BypassFile)
734e3b55780SDimitry Andric return std::nullopt;
73556d91b49SDimitry Andric
736b60736ecSDimitry Andric (void)getOrCreateContentCache(*BypassFile);
737b60736ecSDimitry Andric return BypassFile;
73801af97d3SDimitry Andric }
73901af97d3SDimitry Andric
setFileIsTransient(FileEntryRef File)740b1c73532SDimitry Andric void SourceManager::setFileIsTransient(FileEntryRef File) {
741b1c73532SDimitry Andric getOrCreateContentCache(File).IsTransient = true;
74245b53394SDimitry Andric }
74345b53394SDimitry Andric
744e3b55780SDimitry Andric std::optional<StringRef>
getNonBuiltinFilenameForID(FileID FID) const745b60736ecSDimitry Andric SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
746b60736ecSDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
747b60736ecSDimitry Andric if (Entry->getFile().getContentCache().OrigEntry)
748b60736ecSDimitry Andric return Entry->getFile().getName();
749e3b55780SDimitry Andric return std::nullopt;
750cfca06d7SDimitry Andric }
751cfca06d7SDimitry Andric
getBufferData(FileID FID,bool * Invalid) const75236981b17SDimitry Andric StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
753b60736ecSDimitry Andric auto B = getBufferDataOrNone(FID);
754bca07a45SDimitry Andric if (Invalid)
755b60736ecSDimitry Andric *Invalid = !B;
756b60736ecSDimitry Andric return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
757bca07a45SDimitry Andric }
758bca07a45SDimitry Andric
759e3b55780SDimitry Andric std::optional<StringRef>
getBufferDataIfLoaded(FileID FID) const760b60736ecSDimitry Andric SourceManager::getBufferDataIfLoaded(FileID FID) const {
761b60736ecSDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
762b60736ecSDimitry Andric return Entry->getFile().getContentCache().getBufferDataIfLoaded();
763e3b55780SDimitry Andric return std::nullopt;
764b60736ecSDimitry Andric }
765ec2b103cSEd Schouten
getBufferDataOrNone(FileID FID) const766e3b55780SDimitry Andric std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
767b60736ecSDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
768b60736ecSDimitry Andric if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
769b60736ecSDimitry Andric Diag, getFileManager(), SourceLocation()))
770b60736ecSDimitry Andric return B->getBuffer();
771e3b55780SDimitry Andric return std::nullopt;
7724a37f65fSRoman Divacky }
773ec2b103cSEd Schouten
774ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
775ec2b103cSEd Schouten // SourceLocation manipulation methods.
776ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
777ec2b103cSEd Schouten
77848675466SDimitry Andric /// Return the FileID for a SourceLocation.
779ec2b103cSEd Schouten ///
78036981b17SDimitry Andric /// This is the cache-miss path of getFileID. Not as hot as that function, but
78136981b17SDimitry Andric /// still very important. It is responsible for finding the entry in the
78236981b17SDimitry Andric /// SLocEntry tables that contains the specified location.
getFileIDSlow(SourceLocation::UIntTy SLocOffset) const783344a3780SDimitry Andric FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
78401af97d3SDimitry Andric if (!SLocOffset)
78501af97d3SDimitry Andric return FileID::get(0);
786ec2b103cSEd Schouten
78736981b17SDimitry Andric // Now it is time to search for the correct file. See where the SLocOffset
78836981b17SDimitry Andric // sits in the global view and consult local or loaded buffers for it.
78936981b17SDimitry Andric if (SLocOffset < NextLocalOffset)
79036981b17SDimitry Andric return getFileIDLocal(SLocOffset);
79136981b17SDimitry Andric return getFileIDLoaded(SLocOffset);
79236981b17SDimitry Andric }
79336981b17SDimitry Andric
79448675466SDimitry Andric /// Return the FileID for a SourceLocation with a low offset.
79536981b17SDimitry Andric ///
79636981b17SDimitry Andric /// This function knows that the SourceLocation is in a local buffer, not a
79736981b17SDimitry Andric /// loaded one.
getFileIDLocal(SourceLocation::UIntTy SLocOffset) const798344a3780SDimitry Andric FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
79936981b17SDimitry Andric assert(SLocOffset < NextLocalOffset && "Bad function choice");
80036981b17SDimitry Andric
801ec2b103cSEd Schouten // After the first and second level caches, I see two common sorts of
80236981b17SDimitry Andric // behavior: 1) a lot of searched FileID's are "near" the cached file
80336981b17SDimitry Andric // location or are "near" the cached expansion location. 2) others are just
804ec2b103cSEd Schouten // completely random and may be a very long way away.
805ec2b103cSEd Schouten //
806ec2b103cSEd Schouten // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
807ec2b103cSEd Schouten // then we fall back to a less cache efficient, but more scalable, binary
808ec2b103cSEd Schouten // search to find the location.
809ec2b103cSEd Schouten
810ec2b103cSEd Schouten // See if this is near the file point - worst case we start scanning from the
811ec2b103cSEd Schouten // most newly created FileID.
812ec2b103cSEd Schouten
813e3b55780SDimitry Andric // LessIndex - This is the lower bound of the range that we're searching.
814e3b55780SDimitry Andric // We know that the offset corresponding to the FileID is less than
815e3b55780SDimitry Andric // SLocOffset.
816e3b55780SDimitry Andric unsigned LessIndex = 0;
817e3b55780SDimitry Andric // upper bound of the search range.
818e3b55780SDimitry Andric unsigned GreaterIndex = LocalSLocEntryTable.size();
819e3b55780SDimitry Andric if (LastFileIDLookup.ID >= 0) {
820e3b55780SDimitry Andric // Use the LastFileIDLookup to prune the search space.
821e3b55780SDimitry Andric if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
822e3b55780SDimitry Andric LessIndex = LastFileIDLookup.ID;
823e3b55780SDimitry Andric else
824e3b55780SDimitry Andric GreaterIndex = LastFileIDLookup.ID;
825ec2b103cSEd Schouten }
826ec2b103cSEd Schouten
827e3b55780SDimitry Andric // Find the FileID that contains this.
828ec2b103cSEd Schouten unsigned NumProbes = 0;
829461a67faSDimitry Andric while (true) {
830e3b55780SDimitry Andric --GreaterIndex;
831e3b55780SDimitry Andric assert(GreaterIndex < LocalSLocEntryTable.size());
832e3b55780SDimitry Andric if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
833e3b55780SDimitry Andric FileID Res = FileID::get(int(GreaterIndex));
834cfca06d7SDimitry Andric // Remember it. We have good locality across FileID lookups.
835ec2b103cSEd Schouten LastFileIDLookup = Res;
836ec2b103cSEd Schouten NumLinearScans += NumProbes+1;
837ec2b103cSEd Schouten return Res;
838ec2b103cSEd Schouten }
839ec2b103cSEd Schouten if (++NumProbes == 8)
840ec2b103cSEd Schouten break;
841ec2b103cSEd Schouten }
842ec2b103cSEd Schouten
843ec2b103cSEd Schouten NumProbes = 0;
844461a67faSDimitry Andric while (true) {
845ec2b103cSEd Schouten unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
846344a3780SDimitry Andric SourceLocation::UIntTy MidOffset =
847344a3780SDimitry Andric getLocalSLocEntry(MiddleIndex).getOffset();
848ec2b103cSEd Schouten
849ec2b103cSEd Schouten ++NumProbes;
850ec2b103cSEd Schouten
851ec2b103cSEd Schouten // If the offset of the midpoint is too large, chop the high side of the
852ec2b103cSEd Schouten // range to the midpoint.
853ec2b103cSEd Schouten if (MidOffset > SLocOffset) {
854ec2b103cSEd Schouten GreaterIndex = MiddleIndex;
855ec2b103cSEd Schouten continue;
856ec2b103cSEd Schouten }
857ec2b103cSEd Schouten
858ec2b103cSEd Schouten // If the middle index contains the value, succeed and return.
859cfca06d7SDimitry Andric if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
860cfca06d7SDimitry Andric SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
861ec2b103cSEd Schouten FileID Res = FileID::get(MiddleIndex);
862ec2b103cSEd Schouten
863cfca06d7SDimitry Andric // Remember it. We have good locality across FileID lookups.
864ec2b103cSEd Schouten LastFileIDLookup = Res;
865ec2b103cSEd Schouten NumBinaryProbes += NumProbes;
866ec2b103cSEd Schouten return Res;
867ec2b103cSEd Schouten }
868ec2b103cSEd Schouten
869ec2b103cSEd Schouten // Otherwise, move the low-side up to the middle index.
870ec2b103cSEd Schouten LessIndex = MiddleIndex;
871ec2b103cSEd Schouten }
872ec2b103cSEd Schouten }
873ec2b103cSEd Schouten
87448675466SDimitry Andric /// Return the FileID for a SourceLocation with a high offset.
87536981b17SDimitry Andric ///
87636981b17SDimitry Andric /// This function knows that the SourceLocation is in a loaded buffer, not a
87736981b17SDimitry Andric /// local one.
getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const878344a3780SDimitry Andric FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
879dbe13110SDimitry Andric if (SLocOffset < CurrentLoadedOffset) {
880dbe13110SDimitry Andric assert(0 && "Invalid SLocOffset or bad function choice");
88136981b17SDimitry Andric return FileID();
882dbe13110SDimitry Andric }
88336981b17SDimitry Andric
884b1c73532SDimitry Andric return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));
88536981b17SDimitry Andric }
88636981b17SDimitry Andric
887ec2b103cSEd Schouten SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const88836981b17SDimitry Andric getExpansionLocSlowCase(SourceLocation Loc) const {
889ec2b103cSEd Schouten do {
890ecb7e5c8SRoman Divacky // Note: If Loc indicates an offset into a token that came from a macro
891ecb7e5c8SRoman Divacky // expansion (e.g. the 5th character of the token) we do not want to add
89236981b17SDimitry Andric // this offset when going to the expansion location. The expansion
893ecb7e5c8SRoman Divacky // location is the macro invocation, which the offset has nothing to do
894ecb7e5c8SRoman Divacky // with. This is unlike when we get the spelling loc, because the offset
895ecb7e5c8SRoman Divacky // directly correspond to the token whose spelling we're inspecting.
89636981b17SDimitry Andric Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
897ec2b103cSEd Schouten } while (!Loc.isFileID());
898ec2b103cSEd Schouten
899ec2b103cSEd Schouten return Loc;
900ec2b103cSEd Schouten }
901ec2b103cSEd Schouten
getSpellingLocSlowCase(SourceLocation Loc) const902ec2b103cSEd Schouten SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
903ec2b103cSEd Schouten do {
904ec2b103cSEd Schouten std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
90536981b17SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
90636981b17SDimitry Andric Loc = Loc.getLocWithOffset(LocInfo.second);
90736981b17SDimitry Andric } while (!Loc.isFileID());
90836981b17SDimitry Andric return Loc;
90936981b17SDimitry Andric }
91036981b17SDimitry Andric
getFileLocSlowCase(SourceLocation Loc) const91136981b17SDimitry Andric SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
91236981b17SDimitry Andric do {
91336981b17SDimitry Andric if (isMacroArgExpansion(Loc))
91436981b17SDimitry Andric Loc = getImmediateSpellingLoc(Loc);
91536981b17SDimitry Andric else
91648675466SDimitry Andric Loc = getImmediateExpansionRange(Loc).getBegin();
917ec2b103cSEd Schouten } while (!Loc.isFileID());
918ec2b103cSEd Schouten return Loc;
919ec2b103cSEd Schouten }
920ec2b103cSEd Schouten
921ec2b103cSEd Schouten
922ec2b103cSEd Schouten std::pair<FileID, unsigned>
getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry * E) const92336981b17SDimitry Andric SourceManager::getDecomposedExpansionLocSlowCase(
924180abc3dSDimitry Andric const SrcMgr::SLocEntry *E) const {
92536981b17SDimitry Andric // If this is an expansion record, walk through all the expansion points.
926ec2b103cSEd Schouten FileID FID;
927ec2b103cSEd Schouten SourceLocation Loc;
928180abc3dSDimitry Andric unsigned Offset;
929ec2b103cSEd Schouten do {
93036981b17SDimitry Andric Loc = E->getExpansion().getExpansionLocStart();
931ec2b103cSEd Schouten
932ec2b103cSEd Schouten FID = getFileID(Loc);
933ec2b103cSEd Schouten E = &getSLocEntry(FID);
934180abc3dSDimitry Andric Offset = Loc.getOffset()-E->getOffset();
935ec2b103cSEd Schouten } while (!Loc.isFileID());
936ec2b103cSEd Schouten
937ec2b103cSEd Schouten return std::make_pair(FID, Offset);
938ec2b103cSEd Schouten }
939ec2b103cSEd Schouten
940ec2b103cSEd Schouten std::pair<FileID, unsigned>
getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry * E,unsigned Offset) const941ec2b103cSEd Schouten SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
942ec2b103cSEd Schouten unsigned Offset) const {
94336981b17SDimitry Andric // If this is an expansion record, walk through all the expansion points.
944ec2b103cSEd Schouten FileID FID;
945ec2b103cSEd Schouten SourceLocation Loc;
946ec2b103cSEd Schouten do {
94736981b17SDimitry Andric Loc = E->getExpansion().getSpellingLoc();
94836981b17SDimitry Andric Loc = Loc.getLocWithOffset(Offset);
949ec2b103cSEd Schouten
950ec2b103cSEd Schouten FID = getFileID(Loc);
951ec2b103cSEd Schouten E = &getSLocEntry(FID);
95236981b17SDimitry Andric Offset = Loc.getOffset()-E->getOffset();
953ec2b103cSEd Schouten } while (!Loc.isFileID());
954ec2b103cSEd Schouten
955ec2b103cSEd Schouten return std::make_pair(FID, Offset);
956ec2b103cSEd Schouten }
957ec2b103cSEd Schouten
958ec2b103cSEd Schouten /// getImmediateSpellingLoc - Given a SourceLocation object, return the
959ec2b103cSEd Schouten /// spelling location referenced by the ID. This is the first level down
960ec2b103cSEd Schouten /// towards the place where the characters that make up the lexed token can be
961ec2b103cSEd Schouten /// found. This should not generally be used by clients.
getImmediateSpellingLoc(SourceLocation Loc) const962ec2b103cSEd Schouten SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
963ec2b103cSEd Schouten if (Loc.isFileID()) return Loc;
964ec2b103cSEd Schouten std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
96536981b17SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
96636981b17SDimitry Andric return Loc.getLocWithOffset(LocInfo.second);
967ec2b103cSEd Schouten }
968ec2b103cSEd Schouten
969cfca06d7SDimitry Andric /// Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc) const970cfca06d7SDimitry Andric StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
971b1c73532SDimitry Andric if (OptionalFileEntryRef F = getFileEntryRefForID(getFileID(SpellingLoc)))
972cfca06d7SDimitry Andric return F->getName();
973cfca06d7SDimitry Andric return StringRef();
974cfca06d7SDimitry Andric }
975cfca06d7SDimitry Andric
97636981b17SDimitry Andric /// getImmediateExpansionRange - Loc is required to be an expansion location.
97736981b17SDimitry Andric /// Return the start/end of the expansion information.
97848675466SDimitry Andric CharSourceRange
getImmediateExpansionRange(SourceLocation Loc) const97936981b17SDimitry Andric SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
98036981b17SDimitry Andric assert(Loc.isMacroID() && "Not a macro expansion loc!");
98136981b17SDimitry Andric const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
98236981b17SDimitry Andric return Expansion.getExpansionLocRange();
983ec2b103cSEd Schouten }
984ec2b103cSEd Schouten
getTopMacroCallerLoc(SourceLocation Loc) const98548675466SDimitry Andric SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
98648675466SDimitry Andric while (isMacroArgExpansion(Loc))
98748675466SDimitry Andric Loc = getImmediateSpellingLoc(Loc);
98848675466SDimitry Andric return Loc;
98948675466SDimitry Andric }
99048675466SDimitry Andric
99136981b17SDimitry Andric /// getExpansionRange - Given a SourceLocation object, return the range of
99236981b17SDimitry Andric /// tokens covered by the expansion in the ultimate file.
getExpansionRange(SourceLocation Loc) const99348675466SDimitry Andric CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
99448675466SDimitry Andric if (Loc.isFileID())
99548675466SDimitry Andric return CharSourceRange(SourceRange(Loc, Loc), true);
996ec2b103cSEd Schouten
99748675466SDimitry Andric CharSourceRange Res = getImmediateExpansionRange(Loc);
998ec2b103cSEd Schouten
99936981b17SDimitry Andric // Fully resolve the start and end locations to their ultimate expansion
1000ec2b103cSEd Schouten // points.
100148675466SDimitry Andric while (!Res.getBegin().isFileID())
100248675466SDimitry Andric Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
100348675466SDimitry Andric while (!Res.getEnd().isFileID()) {
100448675466SDimitry Andric CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
100548675466SDimitry Andric Res.setEnd(EndRange.getEnd());
100648675466SDimitry Andric Res.setTokenRange(EndRange.isTokenRange());
100748675466SDimitry Andric }
1008ec2b103cSEd Schouten return Res;
1009ec2b103cSEd Schouten }
1010ec2b103cSEd Schouten
isMacroArgExpansion(SourceLocation Loc,SourceLocation * StartLoc) const101145b53394SDimitry Andric bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
101245b53394SDimitry Andric SourceLocation *StartLoc) const {
1013180abc3dSDimitry Andric if (!Loc.isMacroID()) return false;
1014180abc3dSDimitry Andric
1015180abc3dSDimitry Andric FileID FID = getFileID(Loc);
1016809500fcSDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
101745b53394SDimitry Andric if (!Expansion.isMacroArgExpansion()) return false;
101845b53394SDimitry Andric
101945b53394SDimitry Andric if (StartLoc)
102045b53394SDimitry Andric *StartLoc = Expansion.getExpansionLocStart();
102145b53394SDimitry Andric return true;
1022180abc3dSDimitry Andric }
1023ec2b103cSEd Schouten
isMacroBodyExpansion(SourceLocation Loc) const1024809500fcSDimitry Andric bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1025809500fcSDimitry Andric if (!Loc.isMacroID()) return false;
1026809500fcSDimitry Andric
1027809500fcSDimitry Andric FileID FID = getFileID(Loc);
1028809500fcSDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1029809500fcSDimitry Andric return Expansion.isMacroBodyExpansion();
1030809500fcSDimitry Andric }
1031809500fcSDimitry Andric
isAtStartOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroBegin) const1032bfef3995SDimitry Andric bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1033bfef3995SDimitry Andric SourceLocation *MacroBegin) const {
1034bfef3995SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1035bfef3995SDimitry Andric
1036bfef3995SDimitry Andric std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1037bfef3995SDimitry Andric if (DecompLoc.second > 0)
1038bfef3995SDimitry Andric return false; // Does not point at the start of expansion range.
1039bfef3995SDimitry Andric
1040bfef3995SDimitry Andric bool Invalid = false;
1041bfef3995SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo =
1042bfef3995SDimitry Andric getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1043bfef3995SDimitry Andric if (Invalid)
1044bfef3995SDimitry Andric return false;
1045bfef3995SDimitry Andric SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1046bfef3995SDimitry Andric
1047bfef3995SDimitry Andric if (ExpInfo.isMacroArgExpansion()) {
1048bfef3995SDimitry Andric // For macro argument expansions, check if the previous FileID is part of
1049bfef3995SDimitry Andric // the same argument expansion, in which case this Loc is not at the
1050bfef3995SDimitry Andric // beginning of the expansion.
1051bfef3995SDimitry Andric FileID PrevFID = getPreviousFileID(DecompLoc.first);
1052bfef3995SDimitry Andric if (!PrevFID.isInvalid()) {
1053bfef3995SDimitry Andric const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1054bfef3995SDimitry Andric if (Invalid)
1055bfef3995SDimitry Andric return false;
1056bfef3995SDimitry Andric if (PrevEntry.isExpansion() &&
1057bfef3995SDimitry Andric PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1058bfef3995SDimitry Andric return false;
1059bfef3995SDimitry Andric }
1060bfef3995SDimitry Andric }
1061bfef3995SDimitry Andric
1062bfef3995SDimitry Andric if (MacroBegin)
1063bfef3995SDimitry Andric *MacroBegin = ExpLoc;
1064bfef3995SDimitry Andric return true;
1065bfef3995SDimitry Andric }
1066bfef3995SDimitry Andric
isAtEndOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroEnd) const1067bfef3995SDimitry Andric bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1068bfef3995SDimitry Andric SourceLocation *MacroEnd) const {
1069bfef3995SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1070bfef3995SDimitry Andric
1071bfef3995SDimitry Andric FileID FID = getFileID(Loc);
1072bfef3995SDimitry Andric SourceLocation NextLoc = Loc.getLocWithOffset(1);
1073bfef3995SDimitry Andric if (isInFileID(NextLoc, FID))
1074bfef3995SDimitry Andric return false; // Does not point at the end of expansion range.
1075bfef3995SDimitry Andric
1076bfef3995SDimitry Andric bool Invalid = false;
1077bfef3995SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo =
1078bfef3995SDimitry Andric getSLocEntry(FID, &Invalid).getExpansion();
1079bfef3995SDimitry Andric if (Invalid)
1080bfef3995SDimitry Andric return false;
1081bfef3995SDimitry Andric
1082bfef3995SDimitry Andric if (ExpInfo.isMacroArgExpansion()) {
1083bfef3995SDimitry Andric // For macro argument expansions, check if the next FileID is part of the
1084bfef3995SDimitry Andric // same argument expansion, in which case this Loc is not at the end of the
1085bfef3995SDimitry Andric // expansion.
1086bfef3995SDimitry Andric FileID NextFID = getNextFileID(FID);
1087bfef3995SDimitry Andric if (!NextFID.isInvalid()) {
1088bfef3995SDimitry Andric const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1089bfef3995SDimitry Andric if (Invalid)
1090bfef3995SDimitry Andric return false;
1091bfef3995SDimitry Andric if (NextEntry.isExpansion() &&
1092bfef3995SDimitry Andric NextEntry.getExpansion().getExpansionLocStart() ==
1093bfef3995SDimitry Andric ExpInfo.getExpansionLocStart())
1094bfef3995SDimitry Andric return false;
1095bfef3995SDimitry Andric }
1096bfef3995SDimitry Andric }
1097bfef3995SDimitry Andric
1098bfef3995SDimitry Andric if (MacroEnd)
1099bfef3995SDimitry Andric *MacroEnd = ExpInfo.getExpansionLocEnd();
1100bfef3995SDimitry Andric return true;
1101bfef3995SDimitry Andric }
1102bfef3995SDimitry Andric
1103ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1104ec2b103cSEd Schouten // Queries about the code at a SourceLocation.
1105ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1106ec2b103cSEd Schouten
1107ec2b103cSEd Schouten /// getCharacterData - Return a pointer to the start of the specified location
1108ec2b103cSEd Schouten /// in the appropriate MemoryBuffer.
getCharacterData(SourceLocation SL,bool * Invalid) const11094a37f65fSRoman Divacky const char *SourceManager::getCharacterData(SourceLocation SL,
11104a37f65fSRoman Divacky bool *Invalid) const {
1111ec2b103cSEd Schouten // Note that this is a hot function in the getSpelling() path, which is
1112ec2b103cSEd Schouten // heavily used by -E mode.
1113ec2b103cSEd Schouten std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1114ec2b103cSEd Schouten
1115ec2b103cSEd Schouten // Note that calling 'getBuffer()' may lazily page in a source file.
11164a37f65fSRoman Divacky bool CharDataInvalid = false;
111701af97d3SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
111801af97d3SDimitry Andric if (CharDataInvalid || !Entry.isFile()) {
111901af97d3SDimitry Andric if (Invalid)
112001af97d3SDimitry Andric *Invalid = true;
112101af97d3SDimitry Andric
112201af97d3SDimitry Andric return "<<<<INVALID BUFFER>>>>";
112301af97d3SDimitry Andric }
1124e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1125b60736ecSDimitry Andric Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1126b60736ecSDimitry Andric SourceLocation());
11274a37f65fSRoman Divacky if (Invalid)
1128b60736ecSDimitry Andric *Invalid = !Buffer;
1129b60736ecSDimitry Andric return Buffer ? Buffer->getBufferStart() + LocInfo.second
1130b60736ecSDimitry Andric : "<<<<INVALID BUFFER>>>>";
1131ec2b103cSEd Schouten }
1132ec2b103cSEd Schouten
1133ec2b103cSEd Schouten /// getColumnNumber - Return the column # for the specified file position.
1134ec2b103cSEd Schouten /// this is significantly cheaper to compute than the line number.
getColumnNumber(FileID FID,unsigned FilePos,bool * Invalid) const11354a37f65fSRoman Divacky unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
11364a37f65fSRoman Divacky bool *Invalid) const {
1137e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
11384a37f65fSRoman Divacky if (Invalid)
1139b60736ecSDimitry Andric *Invalid = !MemBuf;
11404a37f65fSRoman Divacky
1141b60736ecSDimitry Andric if (!MemBuf)
11424a37f65fSRoman Divacky return 1;
1143ec2b103cSEd Schouten
114456d91b49SDimitry Andric // It is okay to request a position just past the end of the buffer.
114556d91b49SDimitry Andric if (FilePos > MemBuf->getBufferSize()) {
1146dbe13110SDimitry Andric if (Invalid)
114756d91b49SDimitry Andric *Invalid = true;
1148dbe13110SDimitry Andric return 1;
1149dbe13110SDimitry Andric }
1150dbe13110SDimitry Andric
11517442d6faSDimitry Andric const char *Buf = MemBuf->getBufferStart();
115213cc256eSDimitry Andric // See if we just calculated the line number for this FilePos and can use
115313cc256eSDimitry Andric // that to lookup the start of the line instead of searching for it.
1154b60736ecSDimitry Andric if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1155b60736ecSDimitry Andric LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1156b60736ecSDimitry Andric const unsigned *SourceLineCache =
1157b60736ecSDimitry Andric LastLineNoContentCache->SourceLineCache.begin();
115813cc256eSDimitry Andric unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
115913cc256eSDimitry Andric unsigned LineEnd = SourceLineCache[LastLineNoResult];
11607442d6faSDimitry Andric if (FilePos >= LineStart && FilePos < LineEnd) {
11617442d6faSDimitry Andric // LineEnd is the LineStart of the next line.
11627442d6faSDimitry Andric // A line ends with separator LF or CR+LF on Windows.
11637442d6faSDimitry Andric // FilePos might point to the last separator,
11647442d6faSDimitry Andric // but we need a column number at most 1 + the last column.
11657442d6faSDimitry Andric if (FilePos + 1 == LineEnd && FilePos > LineStart) {
11667442d6faSDimitry Andric if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
11677442d6faSDimitry Andric --FilePos;
11687442d6faSDimitry Andric }
116913cc256eSDimitry Andric return FilePos - LineStart + 1;
117013cc256eSDimitry Andric }
11717442d6faSDimitry Andric }
117213cc256eSDimitry Andric
1173ec2b103cSEd Schouten unsigned LineStart = FilePos;
1174ec2b103cSEd Schouten while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1175ec2b103cSEd Schouten --LineStart;
1176ec2b103cSEd Schouten return FilePos-LineStart+1;
1177ec2b103cSEd Schouten }
1178ec2b103cSEd Schouten
1179bca07a45SDimitry Andric // isInvalid - Return the result of calling loc.isInvalid(), and
1180bca07a45SDimitry Andric // if Invalid is not null, set its value to same.
11812b6b257fSDimitry Andric template<typename LocType>
isInvalid(LocType Loc,bool * Invalid)11822b6b257fSDimitry Andric static bool isInvalid(LocType Loc, bool *Invalid) {
1183bca07a45SDimitry Andric bool MyInvalid = Loc.isInvalid();
1184bca07a45SDimitry Andric if (Invalid)
1185bca07a45SDimitry Andric *Invalid = MyInvalid;
1186bca07a45SDimitry Andric return MyInvalid;
1187bca07a45SDimitry Andric }
1188bca07a45SDimitry Andric
getSpellingColumnNumber(SourceLocation Loc,bool * Invalid) const11894a37f65fSRoman Divacky unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
11904a37f65fSRoman Divacky bool *Invalid) const {
1191bca07a45SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
1192ec2b103cSEd Schouten std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
11934a37f65fSRoman Divacky return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1194ec2b103cSEd Schouten }
1195ec2b103cSEd Schouten
getExpansionColumnNumber(SourceLocation Loc,bool * Invalid) const119636981b17SDimitry Andric unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
11974a37f65fSRoman Divacky bool *Invalid) const {
1198bca07a45SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
119936981b17SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
12004a37f65fSRoman Divacky return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1201ec2b103cSEd Schouten }
1202ec2b103cSEd Schouten
getPresumedColumnNumber(SourceLocation Loc,bool * Invalid) const1203c3b054d2SDimitry Andric unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1204c3b054d2SDimitry Andric bool *Invalid) const {
12052b6b257fSDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc);
12062b6b257fSDimitry Andric if (isInvalid(PLoc, Invalid)) return 0;
12072b6b257fSDimitry Andric return PLoc.getColumn();
1208c3b054d2SDimitry Andric }
1209c3b054d2SDimitry Andric
1210344a3780SDimitry Andric // Check if mutli-byte word x has bytes between m and n, included. This may also
1211344a3780SDimitry Andric // catch bytes equal to n + 1.
1212344a3780SDimitry Andric // The returned value holds a 0x80 at each byte position that holds a match.
1213344a3780SDimitry Andric // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1214344a3780SDimitry Andric template <class T>
likelyhasbetween(T x,unsigned char m,unsigned char n)1215344a3780SDimitry Andric static constexpr inline T likelyhasbetween(T x, unsigned char m,
1216344a3780SDimitry Andric unsigned char n) {
1217344a3780SDimitry Andric return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1218344a3780SDimitry Andric ((x & ~static_cast<T>(0) / 255 * 127) +
1219344a3780SDimitry Andric (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1220344a3780SDimitry Andric ~static_cast<T>(0) / 255 * 128;
1221344a3780SDimitry Andric }
1222dbe13110SDimitry Andric
get(llvm::MemoryBufferRef Buffer,llvm::BumpPtrAllocator & Alloc)1223b60736ecSDimitry Andric LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1224b60736ecSDimitry Andric llvm::BumpPtrAllocator &Alloc) {
1225344a3780SDimitry Andric
1226ec2b103cSEd Schouten // Find the file offsets of all of the *physical* source lines. This does
1227ec2b103cSEd Schouten // not look at trigraphs, escaped newlines, or anything else tricky.
122836981b17SDimitry Andric SmallVector<unsigned, 256> LineOffsets;
1229ec2b103cSEd Schouten
1230ec2b103cSEd Schouten // Line #1 starts at char 0.
1231ec2b103cSEd Schouten LineOffsets.push_back(0);
1232ec2b103cSEd Schouten
1233e3b55780SDimitry Andric const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();
1234b60736ecSDimitry Andric const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1235e3b55780SDimitry Andric const unsigned char *Buf = Start;
1236344a3780SDimitry Andric
1237344a3780SDimitry Andric uint64_t Word;
1238344a3780SDimitry Andric
1239344a3780SDimitry Andric // scan sizeof(Word) bytes at a time for new lines.
1240344a3780SDimitry Andric // This is much faster than scanning each byte independently.
1241e3b55780SDimitry Andric if ((unsigned long)(End - Start) > sizeof(Word)) {
1242344a3780SDimitry Andric do {
1243b1c73532SDimitry Andric Word = llvm::support::endian::read64(Buf, llvm::endianness::little);
1244344a3780SDimitry Andric // no new line => jump over sizeof(Word) bytes.
1245344a3780SDimitry Andric auto Mask = likelyhasbetween(Word, '\n', '\r');
1246344a3780SDimitry Andric if (!Mask) {
1247e3b55780SDimitry Andric Buf += sizeof(Word);
1248344a3780SDimitry Andric continue;
1249344a3780SDimitry Andric }
1250344a3780SDimitry Andric
1251344a3780SDimitry Andric // At that point, Mask contains 0x80 set at each byte that holds a value
1252344a3780SDimitry Andric // in [\n, \r + 1 [
1253344a3780SDimitry Andric
1254344a3780SDimitry Andric // Scan for the next newline - it's very likely there's one.
12557fa27ce4SDimitry Andric unsigned N = llvm::countr_zero(Mask) - 7; // -7 because 0x80 is the marker
1256344a3780SDimitry Andric Word >>= N;
1257e3b55780SDimitry Andric Buf += N / 8 + 1;
1258344a3780SDimitry Andric unsigned char Byte = Word;
1259e3b55780SDimitry Andric switch (Byte) {
1260e3b55780SDimitry Andric case '\r':
1261344a3780SDimitry Andric // If this is \r\n, skip both characters.
1262e3b55780SDimitry Andric if (*Buf == '\n') {
1263e3b55780SDimitry Andric ++Buf;
1264344a3780SDimitry Andric }
12657fa27ce4SDimitry Andric [[fallthrough]];
1266e3b55780SDimitry Andric case '\n':
1267e3b55780SDimitry Andric LineOffsets.push_back(Buf - Start);
1268e3b55780SDimitry Andric };
1269e3b55780SDimitry Andric } while (Buf < End - sizeof(Word) - 1);
1270344a3780SDimitry Andric }
1271344a3780SDimitry Andric
1272344a3780SDimitry Andric // Handle tail using a regular check.
1273e3b55780SDimitry Andric while (Buf < End) {
1274e3b55780SDimitry Andric if (*Buf == '\n') {
1275e3b55780SDimitry Andric LineOffsets.push_back(Buf - Start + 1);
1276e3b55780SDimitry Andric } else if (*Buf == '\r') {
1277676fbe81SDimitry Andric // If this is \r\n, skip both characters.
1278e3b55780SDimitry Andric if (Buf + 1 < End && Buf[1] == '\n') {
1279e3b55780SDimitry Andric ++Buf;
1280ec2b103cSEd Schouten }
1281e3b55780SDimitry Andric LineOffsets.push_back(Buf - Start + 1);
1282e3b55780SDimitry Andric }
1283e3b55780SDimitry Andric ++Buf;
1284ec2b103cSEd Schouten }
1285ec2b103cSEd Schouten
1286b60736ecSDimitry Andric return LineOffsetMapping(LineOffsets, Alloc);
1287b60736ecSDimitry Andric }
1288b60736ecSDimitry Andric
LineOffsetMapping(ArrayRef<unsigned> LineOffsets,llvm::BumpPtrAllocator & Alloc)1289b60736ecSDimitry Andric LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1290b60736ecSDimitry Andric llvm::BumpPtrAllocator &Alloc)
1291b60736ecSDimitry Andric : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1292b60736ecSDimitry Andric Storage[0] = LineOffsets.size();
1293b60736ecSDimitry Andric std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1294ec2b103cSEd Schouten }
1295ec2b103cSEd Schouten
1296ec2b103cSEd Schouten /// getLineNumber - Given a SourceLocation, return the spelling line number
1297ec2b103cSEd Schouten /// for the position indicated. This requires building and caching a table of
1298ec2b103cSEd Schouten /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1299ec2b103cSEd Schouten /// about to emit a diagnostic.
getLineNumber(FileID FID,unsigned FilePos,bool * Invalid) const13004a37f65fSRoman Divacky unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
13014a37f65fSRoman Divacky bool *Invalid) const {
130229cafa66SDimitry Andric if (FID.isInvalid()) {
130329cafa66SDimitry Andric if (Invalid)
130429cafa66SDimitry Andric *Invalid = true;
130529cafa66SDimitry Andric return 1;
130629cafa66SDimitry Andric }
130729cafa66SDimitry Andric
1308b60736ecSDimitry Andric const ContentCache *Content;
1309ec2b103cSEd Schouten if (LastLineNoFileIDQuery == FID)
1310ec2b103cSEd Schouten Content = LastLineNoContentCache;
131101af97d3SDimitry Andric else {
131201af97d3SDimitry Andric bool MyInvalid = false;
131301af97d3SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
131401af97d3SDimitry Andric if (MyInvalid || !Entry.isFile()) {
131501af97d3SDimitry Andric if (Invalid)
131601af97d3SDimitry Andric *Invalid = true;
131701af97d3SDimitry Andric return 1;
131801af97d3SDimitry Andric }
131901af97d3SDimitry Andric
1320b60736ecSDimitry Andric Content = &Entry.getFile().getContentCache();
132101af97d3SDimitry Andric }
1322ec2b103cSEd Schouten
1323ec2b103cSEd Schouten // If this is the first use of line information for this buffer, compute the
1324b1c73532SDimitry Andric // SourceLineCache for it on demand.
13259f4dbff6SDimitry Andric if (!Content->SourceLineCache) {
1326e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1327b60736ecSDimitry Andric Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
13284a37f65fSRoman Divacky if (Invalid)
1329b60736ecSDimitry Andric *Invalid = !Buffer;
1330b60736ecSDimitry Andric if (!Buffer)
13314a37f65fSRoman Divacky return 1;
1332b60736ecSDimitry Andric
1333b60736ecSDimitry Andric Content->SourceLineCache =
1334b60736ecSDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
13354a37f65fSRoman Divacky } else if (Invalid)
13364a37f65fSRoman Divacky *Invalid = false;
1337ec2b103cSEd Schouten
1338ec2b103cSEd Schouten // Okay, we know we have a line number table. Do a binary search to find the
1339ec2b103cSEd Schouten // line number that this character position lands on.
1340b60736ecSDimitry Andric const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1341b60736ecSDimitry Andric const unsigned *SourceLineCacheStart = SourceLineCache;
1342b60736ecSDimitry Andric const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1343ec2b103cSEd Schouten
1344ec2b103cSEd Schouten unsigned QueriedFilePos = FilePos+1;
1345ec2b103cSEd Schouten
1346ec2b103cSEd Schouten // FIXME: I would like to be convinced that this code is worth being as
1347ec2b103cSEd Schouten // complicated as it is, binary search isn't that slow.
1348ec2b103cSEd Schouten //
1349ec2b103cSEd Schouten // If it is worth being optimized, then in my opinion it could be more
1350ec2b103cSEd Schouten // performant, simpler, and more obviously correct by just "galloping" outward
1351ec2b103cSEd Schouten // from the queried file position. In fact, this could be incorporated into a
1352ec2b103cSEd Schouten // generic algorithm such as lower_bound_with_hint.
1353ec2b103cSEd Schouten //
1354ec2b103cSEd Schouten // If someone gives me a test case where this matters, and I will do it! - DWD
1355ec2b103cSEd Schouten
1356ec2b103cSEd Schouten // If the previous query was to the same file, we know both the file pos from
1357ec2b103cSEd Schouten // that query and the line number returned. This allows us to narrow the
1358ec2b103cSEd Schouten // search space from the entire file to something near the match.
1359ec2b103cSEd Schouten if (LastLineNoFileIDQuery == FID) {
1360ec2b103cSEd Schouten if (QueriedFilePos >= LastLineNoFilePos) {
1361ec2b103cSEd Schouten // FIXME: Potential overflow?
1362ec2b103cSEd Schouten SourceLineCache = SourceLineCache+LastLineNoResult-1;
1363ec2b103cSEd Schouten
1364ec2b103cSEd Schouten // The query is likely to be nearby the previous one. Here we check to
1365ec2b103cSEd Schouten // see if it is within 5, 10 or 20 lines. It can be far away in cases
1366ec2b103cSEd Schouten // where big comment blocks and vertical whitespace eat up lines but
1367ec2b103cSEd Schouten // contribute no tokens.
1368ec2b103cSEd Schouten if (SourceLineCache+5 < SourceLineCacheEnd) {
1369ec2b103cSEd Schouten if (SourceLineCache[5] > QueriedFilePos)
1370ec2b103cSEd Schouten SourceLineCacheEnd = SourceLineCache+5;
1371ec2b103cSEd Schouten else if (SourceLineCache+10 < SourceLineCacheEnd) {
1372ec2b103cSEd Schouten if (SourceLineCache[10] > QueriedFilePos)
1373ec2b103cSEd Schouten SourceLineCacheEnd = SourceLineCache+10;
1374ec2b103cSEd Schouten else if (SourceLineCache+20 < SourceLineCacheEnd) {
1375ec2b103cSEd Schouten if (SourceLineCache[20] > QueriedFilePos)
1376ec2b103cSEd Schouten SourceLineCacheEnd = SourceLineCache+20;
1377ec2b103cSEd Schouten }
1378ec2b103cSEd Schouten }
1379ec2b103cSEd Schouten }
1380ec2b103cSEd Schouten } else {
1381b60736ecSDimitry Andric if (LastLineNoResult < Content->SourceLineCache.size())
1382ec2b103cSEd Schouten SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1383ec2b103cSEd Schouten }
1384ec2b103cSEd Schouten }
1385ec2b103cSEd Schouten
1386b60736ecSDimitry Andric const unsigned *Pos =
1387b60736ecSDimitry Andric std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1388ec2b103cSEd Schouten unsigned LineNo = Pos-SourceLineCacheStart;
1389ec2b103cSEd Schouten
1390ec2b103cSEd Schouten LastLineNoFileIDQuery = FID;
1391ec2b103cSEd Schouten LastLineNoContentCache = Content;
1392ec2b103cSEd Schouten LastLineNoFilePos = QueriedFilePos;
1393ec2b103cSEd Schouten LastLineNoResult = LineNo;
1394ec2b103cSEd Schouten return LineNo;
1395ec2b103cSEd Schouten }
1396ec2b103cSEd Schouten
getSpellingLineNumber(SourceLocation Loc,bool * Invalid) const1397c3b054d2SDimitry Andric unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1398c3b054d2SDimitry Andric bool *Invalid) const {
1399c3b054d2SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
1400c3b054d2SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1401c3b054d2SDimitry Andric return getLineNumber(LocInfo.first, LocInfo.second);
1402c3b054d2SDimitry Andric }
getExpansionLineNumber(SourceLocation Loc,bool * Invalid) const140336981b17SDimitry Andric unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
14044a37f65fSRoman Divacky bool *Invalid) const {
1405bca07a45SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
140636981b17SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1407ec2b103cSEd Schouten return getLineNumber(LocInfo.first, LocInfo.second);
1408ec2b103cSEd Schouten }
getPresumedLineNumber(SourceLocation Loc,bool * Invalid) const1409c3b054d2SDimitry Andric unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
14104a37f65fSRoman Divacky bool *Invalid) const {
14112b6b257fSDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc);
14122b6b257fSDimitry Andric if (isInvalid(PLoc, Invalid)) return 0;
14132b6b257fSDimitry Andric return PLoc.getLine();
1414ec2b103cSEd Schouten }
1415ec2b103cSEd Schouten
1416ec2b103cSEd Schouten /// getFileCharacteristic - return the file characteristic of the specified
1417ec2b103cSEd Schouten /// source location, indicating whether this is a normal file, a system
1418ec2b103cSEd Schouten /// header, or an "implicit extern C" system header.
1419ec2b103cSEd Schouten ///
1420ec2b103cSEd Schouten /// This state can be modified with flags on GNU linemarker directives like:
1421ec2b103cSEd Schouten /// # 4 "foo.h" 3
1422ec2b103cSEd Schouten /// which changes all source locations in the current file after that to be
1423ec2b103cSEd Schouten /// considered to be from a system header.
1424ec2b103cSEd Schouten SrcMgr::CharacteristicKind
getFileCharacteristic(SourceLocation Loc) const1425ec2b103cSEd Schouten SourceManager::getFileCharacteristic(SourceLocation Loc) const {
142645b53394SDimitry Andric assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
142736981b17SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1428b60736ecSDimitry Andric const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1429b60736ecSDimitry Andric if (!SEntry)
143001af97d3SDimitry Andric return C_User;
143101af97d3SDimitry Andric
1432b60736ecSDimitry Andric const SrcMgr::FileInfo &FI = SEntry->getFile();
1433ec2b103cSEd Schouten
1434ec2b103cSEd Schouten // If there are no #line directives in this file, just return the whole-file
1435ec2b103cSEd Schouten // state.
1436ec2b103cSEd Schouten if (!FI.hasLineDirectives())
1437ec2b103cSEd Schouten return FI.getFileCharacteristic();
1438ec2b103cSEd Schouten
1439ec2b103cSEd Schouten assert(LineTable && "Can't have linetable entries without a LineTable!");
1440ec2b103cSEd Schouten // See if there is a #line directive before the location.
1441ec2b103cSEd Schouten const LineEntry *Entry =
144256d91b49SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1443ec2b103cSEd Schouten
1444ec2b103cSEd Schouten // If this is before the first line marker, use the file characteristic.
1445ec2b103cSEd Schouten if (!Entry)
1446ec2b103cSEd Schouten return FI.getFileCharacteristic();
1447ec2b103cSEd Schouten
1448ec2b103cSEd Schouten return Entry->FileKind;
1449ec2b103cSEd Schouten }
1450ec2b103cSEd Schouten
1451ec2b103cSEd Schouten /// Return the filename or buffer identifier of the buffer the location is in.
145256d91b49SDimitry Andric /// Note that this name does not respect \#line directives. Use getPresumedLoc
1453ec2b103cSEd Schouten /// for normal clients.
getBufferName(SourceLocation Loc,bool * Invalid) const1454bab175ecSDimitry Andric StringRef SourceManager::getBufferName(SourceLocation Loc,
14554a37f65fSRoman Divacky bool *Invalid) const {
1456bca07a45SDimitry Andric if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1457ec2b103cSEd Schouten
1458b60736ecSDimitry Andric auto B = getBufferOrNone(getFileID(Loc));
1459b60736ecSDimitry Andric if (Invalid)
1460b60736ecSDimitry Andric *Invalid = !B;
1461b60736ecSDimitry Andric return B ? B->getBufferIdentifier() : "<invalid buffer>";
1462ec2b103cSEd Schouten }
1463ec2b103cSEd Schouten
1464ec2b103cSEd Schouten /// getPresumedLoc - This method returns the "presumed" location of a
146556d91b49SDimitry Andric /// SourceLocation specifies. A "presumed location" can be modified by \#line
1466ec2b103cSEd Schouten /// or GNU line marker directives. This provides a view on the data that a
1467ec2b103cSEd Schouten /// user should see in diagnostics, for example.
1468ec2b103cSEd Schouten ///
146936981b17SDimitry Andric /// Note that a presumed location is always given as the expansion point of an
147036981b17SDimitry Andric /// expansion location, not at the spelling location.
getPresumedLoc(SourceLocation Loc,bool UseLineDirectives) const1471809500fcSDimitry Andric PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1472809500fcSDimitry Andric bool UseLineDirectives) const {
1473ec2b103cSEd Schouten if (Loc.isInvalid()) return PresumedLoc();
1474ec2b103cSEd Schouten
147536981b17SDimitry Andric // Presumed locations are always for expansion points.
147636981b17SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1477ec2b103cSEd Schouten
147801af97d3SDimitry Andric bool Invalid = false;
147901af97d3SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
148001af97d3SDimitry Andric if (Invalid || !Entry.isFile())
148101af97d3SDimitry Andric return PresumedLoc();
148201af97d3SDimitry Andric
148301af97d3SDimitry Andric const SrcMgr::FileInfo &FI = Entry.getFile();
1484b60736ecSDimitry Andric const SrcMgr::ContentCache *C = &FI.getContentCache();
1485ec2b103cSEd Schouten
1486ec2b103cSEd Schouten // To get the source name, first consult the FileEntry (if one exists)
1487ec2b103cSEd Schouten // before the MemBuffer as this will avoid unnecessarily paging in the
1488ec2b103cSEd Schouten // MemBuffer.
148922989816SDimitry Andric FileID FID = LocInfo.first;
1490bab175ecSDimitry Andric StringRef Filename;
149101af97d3SDimitry Andric if (C->OrigEntry)
149201af97d3SDimitry Andric Filename = C->OrigEntry->getName();
1493b60736ecSDimitry Andric else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1494b60736ecSDimitry Andric Filename = Buffer->getBufferIdentifier();
149501af97d3SDimitry Andric
1496bca07a45SDimitry Andric unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1497bca07a45SDimitry Andric if (Invalid)
1498bca07a45SDimitry Andric return PresumedLoc();
1499bca07a45SDimitry Andric unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1500bca07a45SDimitry Andric if (Invalid)
1501bca07a45SDimitry Andric return PresumedLoc();
1502bca07a45SDimitry Andric
1503ec2b103cSEd Schouten SourceLocation IncludeLoc = FI.getIncludeLoc();
1504ec2b103cSEd Schouten
1505ec2b103cSEd Schouten // If we have #line directives in this file, update and overwrite the physical
1506ec2b103cSEd Schouten // location info if appropriate.
1507809500fcSDimitry Andric if (UseLineDirectives && FI.hasLineDirectives()) {
1508ec2b103cSEd Schouten assert(LineTable && "Can't have linetable entries without a LineTable!");
1509ec2b103cSEd Schouten // See if there is a #line directive before this. If so, get it.
1510ec2b103cSEd Schouten if (const LineEntry *Entry =
151156d91b49SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1512ec2b103cSEd Schouten // If the LineEntry indicates a filename, use it.
151322989816SDimitry Andric if (Entry->FilenameID != -1) {
1514ec2b103cSEd Schouten Filename = LineTable->getFilename(Entry->FilenameID);
151522989816SDimitry Andric // The contents of files referenced by #line are not in the
151622989816SDimitry Andric // SourceManager
151722989816SDimitry Andric FID = FileID::get(0);
151822989816SDimitry Andric }
1519ec2b103cSEd Schouten
1520ec2b103cSEd Schouten // Use the line number specified by the LineEntry. This line number may
1521ec2b103cSEd Schouten // be multiple lines down from the line entry. Add the difference in
1522ec2b103cSEd Schouten // physical line numbers from the query point and the line marker to the
1523ec2b103cSEd Schouten // total.
1524ec2b103cSEd Schouten unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1525ec2b103cSEd Schouten LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1526ec2b103cSEd Schouten
1527ec2b103cSEd Schouten // Note that column numbers are not molested by line markers.
1528ec2b103cSEd Schouten
1529ec2b103cSEd Schouten // Handle virtual #include manipulation.
1530ec2b103cSEd Schouten if (Entry->IncludeOffset) {
1531ec2b103cSEd Schouten IncludeLoc = getLocForStartOfFile(LocInfo.first);
153236981b17SDimitry Andric IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1533ec2b103cSEd Schouten }
1534ec2b103cSEd Schouten }
1535ec2b103cSEd Schouten }
1536ec2b103cSEd Schouten
153722989816SDimitry Andric return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1538ec2b103cSEd Schouten }
1539ec2b103cSEd Schouten
154048675466SDimitry Andric /// Returns whether the PresumedLoc for a given SourceLocation is
1541bfef3995SDimitry Andric /// in the main file.
1542bfef3995SDimitry Andric ///
1543bfef3995SDimitry Andric /// This computes the "presumed" location for a SourceLocation, then checks
1544bfef3995SDimitry Andric /// whether it came from a file other than the main file. This is different
1545bfef3995SDimitry Andric /// from isWrittenInMainFile() because it takes line marker directives into
1546bfef3995SDimitry Andric /// account.
isInMainFile(SourceLocation Loc) const1547bfef3995SDimitry Andric bool SourceManager::isInMainFile(SourceLocation Loc) const {
1548bfef3995SDimitry Andric if (Loc.isInvalid()) return false;
1549bfef3995SDimitry Andric
1550bfef3995SDimitry Andric // Presumed locations are always for expansion points.
1551bfef3995SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1552bfef3995SDimitry Andric
1553b60736ecSDimitry Andric const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1554b60736ecSDimitry Andric if (!Entry)
1555bfef3995SDimitry Andric return false;
1556bfef3995SDimitry Andric
1557b60736ecSDimitry Andric const SrcMgr::FileInfo &FI = Entry->getFile();
1558bfef3995SDimitry Andric
1559bfef3995SDimitry Andric // Check if there is a line directive for this location.
1560bfef3995SDimitry Andric if (FI.hasLineDirectives())
1561bfef3995SDimitry Andric if (const LineEntry *Entry =
1562bfef3995SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1563bfef3995SDimitry Andric if (Entry->IncludeOffset)
1564bfef3995SDimitry Andric return false;
1565bfef3995SDimitry Andric
1566bfef3995SDimitry Andric return FI.getIncludeLoc().isInvalid();
1567bfef3995SDimitry Andric }
1568bfef3995SDimitry Andric
156948675466SDimitry Andric /// The size of the SLocEntry that \p FID represents.
getFileIDSize(FileID FID) const157036981b17SDimitry Andric unsigned SourceManager::getFileIDSize(FileID FID) const {
157136981b17SDimitry Andric bool Invalid = false;
157236981b17SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
157336981b17SDimitry Andric if (Invalid)
157436981b17SDimitry Andric return 0;
157536981b17SDimitry Andric
157636981b17SDimitry Andric int ID = FID.ID;
1577344a3780SDimitry Andric SourceLocation::UIntTy NextOffset;
157836981b17SDimitry Andric if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
157936981b17SDimitry Andric NextOffset = getNextLocalOffset();
158036981b17SDimitry Andric else if (ID+1 == -1)
158136981b17SDimitry Andric NextOffset = MaxLoadedOffset;
158236981b17SDimitry Andric else
158336981b17SDimitry Andric NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
158436981b17SDimitry Andric
158536981b17SDimitry Andric return NextOffset - Entry.getOffset() - 1;
158636981b17SDimitry Andric }
158736981b17SDimitry Andric
1588ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1589ec2b103cSEd Schouten // Other miscellaneous methods.
1590ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1591ec2b103cSEd Schouten
159248675466SDimitry Andric /// Get the source location for the given file:line:col triplet.
1593b897c866SEd Schouten ///
1594b897c866SEd Schouten /// If the source file is included multiple times, the source location will
159536981b17SDimitry Andric /// be based upon an arbitrary inclusion.
translateFileLineCol(const FileEntry * SourceFile,unsigned Line,unsigned Col) const159636981b17SDimitry Andric SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
159736981b17SDimitry Andric unsigned Line,
159836981b17SDimitry Andric unsigned Col) const {
1599b897c866SEd Schouten assert(SourceFile && "Null source file!");
1600b897c866SEd Schouten assert(Line && Col && "Line and column should start from 1!");
1601b897c866SEd Schouten
160236981b17SDimitry Andric FileID FirstFID = translateFile(SourceFile);
160336981b17SDimitry Andric return translateLineCol(FirstFID, Line, Col);
160436981b17SDimitry Andric }
160536981b17SDimitry Andric
160648675466SDimitry Andric /// Get the FileID for the given file.
160736981b17SDimitry Andric ///
160836981b17SDimitry Andric /// If the source file is included multiple times, the FileID will be the
160936981b17SDimitry Andric /// first inclusion.
translateFile(const FileEntry * SourceFile) const161036981b17SDimitry Andric FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
161136981b17SDimitry Andric assert(SourceFile && "Null source file!");
161236981b17SDimitry Andric
1613bca07a45SDimitry Andric // First, check the main file ID, since it is common to look for a
1614bca07a45SDimitry Andric // location in the main file.
161545b53394SDimitry Andric if (MainFileID.isValid()) {
161601af97d3SDimitry Andric bool Invalid = false;
161701af97d3SDimitry Andric const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
161801af97d3SDimitry Andric if (Invalid)
161936981b17SDimitry Andric return FileID();
162001af97d3SDimitry Andric
1621bca07a45SDimitry Andric if (MainSLoc.isFile()) {
1622b60736ecSDimitry Andric if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1623519fc96cSDimitry Andric return MainFileID;
1624bca07a45SDimitry Andric }
1625bca07a45SDimitry Andric }
1626bca07a45SDimitry Andric
1627bca07a45SDimitry Andric // The location we're looking for isn't in the main file; look
162836981b17SDimitry Andric // through all of the local source locations.
162936981b17SDimitry Andric for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1630cfca06d7SDimitry Andric const SLocEntry &SLoc = getLocalSLocEntry(I);
1631b60736ecSDimitry Andric if (SLoc.isFile() &&
1632b60736ecSDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1633519fc96cSDimitry Andric return FileID::get(I);
1634bca07a45SDimitry Andric }
1635519fc96cSDimitry Andric
163636981b17SDimitry Andric // If that still didn't help, try the modules.
163736981b17SDimitry Andric for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
163836981b17SDimitry Andric const SLocEntry &SLoc = getLoadedSLocEntry(I);
1639b60736ecSDimitry Andric if (SLoc.isFile() &&
1640b60736ecSDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1641519fc96cSDimitry Andric return FileID::get(-int(I) - 2);
1642bca07a45SDimitry Andric }
1643bca07a45SDimitry Andric
164436981b17SDimitry Andric return FileID();
164536981b17SDimitry Andric }
164636981b17SDimitry Andric
164748675466SDimitry Andric /// Get the source location in \arg FID for the given line:col.
164836981b17SDimitry Andric /// Returns null location if \arg FID is not a file SLocEntry.
translateLineCol(FileID FID,unsigned Line,unsigned Col) const164936981b17SDimitry Andric SourceLocation SourceManager::translateLineCol(FileID FID,
165036981b17SDimitry Andric unsigned Line,
165136981b17SDimitry Andric unsigned Col) const {
1652bfef3995SDimitry Andric // Lines are used as a one-based index into a zero-based array. This assert
1653bfef3995SDimitry Andric // checks for possible buffer underruns.
165445b53394SDimitry Andric assert(Line && Col && "Line and column should start from 1!");
1655bfef3995SDimitry Andric
165636981b17SDimitry Andric if (FID.isInvalid())
1657b897c866SEd Schouten return SourceLocation();
1658bca07a45SDimitry Andric
165936981b17SDimitry Andric bool Invalid = false;
166036981b17SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
166136981b17SDimitry Andric if (Invalid)
166236981b17SDimitry Andric return SourceLocation();
166336981b17SDimitry Andric
166436981b17SDimitry Andric if (!Entry.isFile())
166536981b17SDimitry Andric return SourceLocation();
166636981b17SDimitry Andric
166736981b17SDimitry Andric SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
166836981b17SDimitry Andric
1669bca07a45SDimitry Andric if (Line == 1 && Col == 1)
167036981b17SDimitry Andric return FileLoc;
1671bca07a45SDimitry Andric
1672b60736ecSDimitry Andric const ContentCache *Content = &Entry.getFile().getContentCache();
1673b897c866SEd Schouten
1674b897c866SEd Schouten // If this is the first use of line information for this buffer, compute the
167536981b17SDimitry Andric // SourceLineCache for it on demand.
1676e3b55780SDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1677b60736ecSDimitry Andric Content->getBufferOrNone(Diag, getFileManager());
1678b60736ecSDimitry Andric if (!Buffer)
16794a37f65fSRoman Divacky return SourceLocation();
1680b60736ecSDimitry Andric if (!Content->SourceLineCache)
1681b60736ecSDimitry Andric Content->SourceLineCache =
1682b60736ecSDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1683b897c866SEd Schouten
1684b60736ecSDimitry Andric if (Line > Content->SourceLineCache.size()) {
1685b60736ecSDimitry Andric unsigned Size = Buffer->getBufferSize();
168679ade4e0SRoman Divacky if (Size > 0)
168779ade4e0SRoman Divacky --Size;
168836981b17SDimitry Andric return FileLoc.getLocWithOffset(Size);
168979ade4e0SRoman Divacky }
169079ade4e0SRoman Divacky
169179ade4e0SRoman Divacky unsigned FilePos = Content->SourceLineCache[Line - 1];
1692dbe13110SDimitry Andric const char *Buf = Buffer->getBufferStart() + FilePos;
1693dbe13110SDimitry Andric unsigned BufLength = Buffer->getBufferSize() - FilePos;
169436981b17SDimitry Andric if (BufLength == 0)
169536981b17SDimitry Andric return FileLoc.getLocWithOffset(FilePos);
169636981b17SDimitry Andric
169779ade4e0SRoman Divacky unsigned i = 0;
169879ade4e0SRoman Divacky
169979ade4e0SRoman Divacky // Check that the given column is valid.
170079ade4e0SRoman Divacky while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
170179ade4e0SRoman Divacky ++i;
170236981b17SDimitry Andric return FileLoc.getLocWithOffset(FilePos + i);
1703b897c866SEd Schouten }
1704b897c866SEd Schouten
170548675466SDimitry Andric /// Compute a map of macro argument chunks to their expanded source
170636981b17SDimitry Andric /// location. Chunks that are not part of a macro argument will map to an
170736981b17SDimitry Andric /// invalid source location. e.g. if a file contains one macro argument at
170836981b17SDimitry Andric /// offset 100 with length 10, this is how the map will be formed:
170936981b17SDimitry Andric /// 0 -> SourceLocation()
171036981b17SDimitry Andric /// 100 -> Expanded macro arg location
171136981b17SDimitry Andric /// 110 -> SourceLocation()
computeMacroArgsCache(MacroArgsMap & MacroArgsCache,FileID FID) const1712bab175ecSDimitry Andric void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
171336981b17SDimitry Andric FileID FID) const {
171445b53394SDimitry Andric assert(FID.isValid());
171536981b17SDimitry Andric
171636981b17SDimitry Andric // Initially no macro argument chunk is present.
171736981b17SDimitry Andric MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
171836981b17SDimitry Andric
171936981b17SDimitry Andric int ID = FID.ID;
1720461a67faSDimitry Andric while (true) {
172136981b17SDimitry Andric ++ID;
172236981b17SDimitry Andric // Stop if there are no more FileIDs to check.
172336981b17SDimitry Andric if (ID > 0) {
172436981b17SDimitry Andric if (unsigned(ID) >= local_sloc_entry_size())
172536981b17SDimitry Andric return;
172636981b17SDimitry Andric } else if (ID == -1) {
172736981b17SDimitry Andric return;
172836981b17SDimitry Andric }
172936981b17SDimitry Andric
1730bfef3995SDimitry Andric bool Invalid = false;
1731bfef3995SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1732bfef3995SDimitry Andric if (Invalid)
1733bfef3995SDimitry Andric return;
173436981b17SDimitry Andric if (Entry.isFile()) {
1735b60736ecSDimitry Andric auto& File = Entry.getFile();
1736b60736ecSDimitry Andric if (File.getFileCharacteristic() == C_User_ModuleMap ||
1737b60736ecSDimitry Andric File.getFileCharacteristic() == C_System_ModuleMap)
1738b60736ecSDimitry Andric continue;
1739b60736ecSDimitry Andric
1740b60736ecSDimitry Andric SourceLocation IncludeLoc = File.getIncludeLoc();
1741cfca06d7SDimitry Andric bool IncludedInFID =
1742cfca06d7SDimitry Andric (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1743cfca06d7SDimitry Andric // Predefined header doesn't have a valid include location in main
1744cfca06d7SDimitry Andric // file, but any files created by it should still be skipped when
1745cfca06d7SDimitry Andric // computing macro args expanded in the main file.
1746b60736ecSDimitry Andric (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1747cfca06d7SDimitry Andric if (IncludedInFID) {
1748cfca06d7SDimitry Andric // Skip the files/macros of the #include'd file, we only care about
1749cfca06d7SDimitry Andric // macros that lexed macro arguments from our file.
175036981b17SDimitry Andric if (Entry.getFile().NumCreatedFIDs)
175136981b17SDimitry Andric ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
175236981b17SDimitry Andric continue;
1753e3b55780SDimitry Andric }
1754cfca06d7SDimitry Andric // If file was included but not from FID, there is no more files/macros
1755cfca06d7SDimitry Andric // that may be "contained" in this file.
1756e3b55780SDimitry Andric if (IncludeLoc.isValid())
1757cfca06d7SDimitry Andric return;
1758cfca06d7SDimitry Andric continue;
175936981b17SDimitry Andric }
176036981b17SDimitry Andric
1761dbe13110SDimitry Andric const ExpansionInfo &ExpInfo = Entry.getExpansion();
1762dbe13110SDimitry Andric
1763dbe13110SDimitry Andric if (ExpInfo.getExpansionLocStart().isFileID()) {
1764dbe13110SDimitry Andric if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1765dbe13110SDimitry Andric return; // No more files/macros that may be "contained" in this file.
1766dbe13110SDimitry Andric }
1767dbe13110SDimitry Andric
1768dbe13110SDimitry Andric if (!ExpInfo.isMacroArgExpansion())
176936981b17SDimitry Andric continue;
177036981b17SDimitry Andric
177113cc256eSDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
177213cc256eSDimitry Andric ExpInfo.getSpellingLoc(),
177313cc256eSDimitry Andric SourceLocation::getMacroLoc(Entry.getOffset()),
177413cc256eSDimitry Andric getFileIDSize(FileID::get(ID)));
1775dbe13110SDimitry Andric }
177613cc256eSDimitry Andric }
177713cc256eSDimitry Andric
associateFileChunkWithMacroArgExp(MacroArgsMap & MacroArgsCache,FileID FID,SourceLocation SpellLoc,SourceLocation ExpansionLoc,unsigned ExpansionLength) const177813cc256eSDimitry Andric void SourceManager::associateFileChunkWithMacroArgExp(
177913cc256eSDimitry Andric MacroArgsMap &MacroArgsCache,
178013cc256eSDimitry Andric FileID FID,
178113cc256eSDimitry Andric SourceLocation SpellLoc,
178213cc256eSDimitry Andric SourceLocation ExpansionLoc,
178313cc256eSDimitry Andric unsigned ExpansionLength) const {
178413cc256eSDimitry Andric if (!SpellLoc.isFileID()) {
1785344a3780SDimitry Andric SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1786344a3780SDimitry Andric SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
178713cc256eSDimitry Andric
178813cc256eSDimitry Andric // The spelling range for this macro argument expansion can span multiple
178913cc256eSDimitry Andric // consecutive FileID entries. Go through each entry contained in the
179013cc256eSDimitry Andric // spelling range and if one is itself a macro argument expansion, recurse
179113cc256eSDimitry Andric // and associate the file chunk that it represents.
179213cc256eSDimitry Andric
179313cc256eSDimitry Andric FileID SpellFID; // Current FileID in the spelling range.
179413cc256eSDimitry Andric unsigned SpellRelativeOffs;
17959f4dbff6SDimitry Andric std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1796461a67faSDimitry Andric while (true) {
179713cc256eSDimitry Andric const SLocEntry &Entry = getSLocEntry(SpellFID);
1798344a3780SDimitry Andric SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
179913cc256eSDimitry Andric unsigned SpellFIDSize = getFileIDSize(SpellFID);
1800344a3780SDimitry Andric SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
180113cc256eSDimitry Andric const ExpansionInfo &Info = Entry.getExpansion();
180213cc256eSDimitry Andric if (Info.isMacroArgExpansion()) {
180313cc256eSDimitry Andric unsigned CurrSpellLength;
180413cc256eSDimitry Andric if (SpellFIDEndOffs < SpellEndOffs)
180513cc256eSDimitry Andric CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
180613cc256eSDimitry Andric else
180713cc256eSDimitry Andric CurrSpellLength = ExpansionLength;
180813cc256eSDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
180913cc256eSDimitry Andric Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
181013cc256eSDimitry Andric ExpansionLoc, CurrSpellLength);
181113cc256eSDimitry Andric }
181213cc256eSDimitry Andric
181313cc256eSDimitry Andric if (SpellFIDEndOffs >= SpellEndOffs)
181413cc256eSDimitry Andric return; // we covered all FileID entries in the spelling range.
181513cc256eSDimitry Andric
181613cc256eSDimitry Andric // Move to the next FileID entry in the spelling range.
181713cc256eSDimitry Andric unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
181813cc256eSDimitry Andric ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
181913cc256eSDimitry Andric ExpansionLength -= advance;
182013cc256eSDimitry Andric ++SpellFID.ID;
182113cc256eSDimitry Andric SpellRelativeOffs = 0;
182213cc256eSDimitry Andric }
182313cc256eSDimitry Andric }
182413cc256eSDimitry Andric
182513cc256eSDimitry Andric assert(SpellLoc.isFileID());
1826dbe13110SDimitry Andric
182736981b17SDimitry Andric unsigned BeginOffs;
182836981b17SDimitry Andric if (!isInFileID(SpellLoc, FID, &BeginOffs))
182913cc256eSDimitry Andric return;
1830dbe13110SDimitry Andric
183113cc256eSDimitry Andric unsigned EndOffs = BeginOffs + ExpansionLength;
183236981b17SDimitry Andric
183336981b17SDimitry Andric // Add a new chunk for this macro argument. A previous macro argument chunk
183436981b17SDimitry Andric // may have been lexed again, so e.g. if the map is
183536981b17SDimitry Andric // 0 -> SourceLocation()
183636981b17SDimitry Andric // 100 -> Expanded loc #1
183736981b17SDimitry Andric // 110 -> SourceLocation()
183848675466SDimitry Andric // and we found a new macro FileID that lexed from offset 105 with length 3,
183936981b17SDimitry Andric // the new map will be:
184036981b17SDimitry Andric // 0 -> SourceLocation()
184136981b17SDimitry Andric // 100 -> Expanded loc #1
184236981b17SDimitry Andric // 105 -> Expanded loc #2
184336981b17SDimitry Andric // 108 -> Expanded loc #1
184436981b17SDimitry Andric // 110 -> SourceLocation()
184536981b17SDimitry Andric //
184636981b17SDimitry Andric // Since re-lexed macro chunks will always be the same size or less of
184736981b17SDimitry Andric // previous chunks, we only need to find where the ending of the new macro
184836981b17SDimitry Andric // chunk is mapped to and update the map with new begin/end mappings.
184936981b17SDimitry Andric
185036981b17SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
185136981b17SDimitry Andric --I;
185236981b17SDimitry Andric SourceLocation EndOffsMappedLoc = I->second;
185313cc256eSDimitry Andric MacroArgsCache[BeginOffs] = ExpansionLoc;
185436981b17SDimitry Andric MacroArgsCache[EndOffs] = EndOffsMappedLoc;
185536981b17SDimitry Andric }
185636981b17SDimitry Andric
updateSlocUsageStats() const1857ac9a064cSDimitry Andric void SourceManager::updateSlocUsageStats() const {
1858ac9a064cSDimitry Andric SourceLocation::UIntTy UsedBytes =
1859ac9a064cSDimitry Andric NextLocalOffset + (MaxLoadedOffset - CurrentLoadedOffset);
1860ac9a064cSDimitry Andric MaxUsedSLocBytes.updateMax(UsedBytes);
1861ac9a064cSDimitry Andric }
1862ac9a064cSDimitry Andric
186348675466SDimitry Andric /// If \arg Loc points inside a function macro argument, the returned
186436981b17SDimitry Andric /// location will be the macro location in which the argument was expanded.
186536981b17SDimitry Andric /// If a macro argument is used multiple times, the expanded location will
186636981b17SDimitry Andric /// be at the first expansion of the argument.
186736981b17SDimitry Andric /// e.g.
186836981b17SDimitry Andric /// MY_MACRO(foo);
186936981b17SDimitry Andric /// ^
187036981b17SDimitry Andric /// Passing a file location pointing at 'foo', will yield a macro location
187136981b17SDimitry Andric /// where 'foo' was expanded into.
187236981b17SDimitry Andric SourceLocation
getMacroArgExpandedLocation(SourceLocation Loc) const187336981b17SDimitry Andric SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
187436981b17SDimitry Andric if (Loc.isInvalid() || !Loc.isFileID())
187536981b17SDimitry Andric return Loc;
187636981b17SDimitry Andric
187736981b17SDimitry Andric FileID FID;
187836981b17SDimitry Andric unsigned Offset;
18799f4dbff6SDimitry Andric std::tie(FID, Offset) = getDecomposedLoc(Loc);
188036981b17SDimitry Andric if (FID.isInvalid())
188136981b17SDimitry Andric return Loc;
188236981b17SDimitry Andric
1883bab175ecSDimitry Andric std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1884bab175ecSDimitry Andric if (!MacroArgsCache) {
1885519fc96cSDimitry Andric MacroArgsCache = std::make_unique<MacroArgsMap>();
1886bab175ecSDimitry Andric computeMacroArgsCache(*MacroArgsCache, FID);
1887bab175ecSDimitry Andric }
188836981b17SDimitry Andric
188936981b17SDimitry Andric assert(!MacroArgsCache->empty());
189036981b17SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1891b60736ecSDimitry Andric // In case every element in MacroArgsCache is greater than Offset we can't
1892b60736ecSDimitry Andric // decrement the iterator.
1893b60736ecSDimitry Andric if (I == MacroArgsCache->begin())
1894b60736ecSDimitry Andric return Loc;
1895b60736ecSDimitry Andric
189636981b17SDimitry Andric --I;
189736981b17SDimitry Andric
1898344a3780SDimitry Andric SourceLocation::UIntTy MacroArgBeginOffs = I->first;
189936981b17SDimitry Andric SourceLocation MacroArgExpandedLoc = I->second;
190036981b17SDimitry Andric if (MacroArgExpandedLoc.isValid())
190136981b17SDimitry Andric return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
190236981b17SDimitry Andric
190336981b17SDimitry Andric return Loc;
190436981b17SDimitry Andric }
190536981b17SDimitry Andric
19066a037251SDimitry Andric std::pair<FileID, unsigned>
getDecomposedIncludedLoc(FileID FID) const19076a037251SDimitry Andric SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1908bfef3995SDimitry Andric if (FID.isInvalid())
1909bfef3995SDimitry Andric return std::make_pair(FileID(), 0);
1910bfef3995SDimitry Andric
19116a037251SDimitry Andric // Uses IncludedLocMap to retrieve/cache the decomposed loc.
19126a037251SDimitry Andric
1913461a67faSDimitry Andric using DecompTy = std::pair<FileID, unsigned>;
1914676fbe81SDimitry Andric auto InsertOp = IncludedLocMap.try_emplace(FID);
19156a037251SDimitry Andric DecompTy &DecompLoc = InsertOp.first->second;
19166a037251SDimitry Andric if (!InsertOp.second)
19176a037251SDimitry Andric return DecompLoc; // already in map.
19186a037251SDimitry Andric
19196a037251SDimitry Andric SourceLocation UpperLoc;
1920bfef3995SDimitry Andric bool Invalid = false;
1921bfef3995SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1922bfef3995SDimitry Andric if (!Invalid) {
19236a037251SDimitry Andric if (Entry.isExpansion())
19246a037251SDimitry Andric UpperLoc = Entry.getExpansion().getExpansionLocStart();
19256a037251SDimitry Andric else
19266a037251SDimitry Andric UpperLoc = Entry.getFile().getIncludeLoc();
1927bfef3995SDimitry Andric }
19286a037251SDimitry Andric
19296a037251SDimitry Andric if (UpperLoc.isValid())
19306a037251SDimitry Andric DecompLoc = getDecomposedLoc(UpperLoc);
19316a037251SDimitry Andric
19326a037251SDimitry Andric return DecompLoc;
19336a037251SDimitry Andric }
19346a037251SDimitry Andric
getUniqueLoadedASTFileID(SourceLocation Loc) const1935ac9a064cSDimitry Andric FileID SourceManager::getUniqueLoadedASTFileID(SourceLocation Loc) const {
1936ac9a064cSDimitry Andric assert(isLoadedSourceLocation(Loc) &&
1937ac9a064cSDimitry Andric "Must be a source location in a loaded PCH/Module file");
1938ac9a064cSDimitry Andric
1939ac9a064cSDimitry Andric auto [FID, Ignore] = getDecomposedLoc(Loc);
1940ac9a064cSDimitry Andric // `LoadedSLocEntryAllocBegin` stores the sorted lowest FID of each loaded
1941ac9a064cSDimitry Andric // allocation. Later allocations have lower FileIDs. The call below is to find
1942ac9a064cSDimitry Andric // the lowest FID of a loaded allocation from any FID in the same allocation.
1943ac9a064cSDimitry Andric // The lowest FID is used to identify a loaded allocation.
1944ac9a064cSDimitry Andric const FileID *FirstFID =
1945ac9a064cSDimitry Andric llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, std::greater<FileID>{});
1946ac9a064cSDimitry Andric
1947ac9a064cSDimitry Andric assert(FirstFID &&
1948ac9a064cSDimitry Andric "The failure to find the first FileID of a "
1949ac9a064cSDimitry Andric "loaded AST from a loaded source location was unexpected.");
1950ac9a064cSDimitry Andric return *FirstFID;
1951ac9a064cSDimitry Andric }
1952ac9a064cSDimitry Andric
isInTheSameTranslationUnitImpl(const std::pair<FileID,unsigned> & LOffs,const std::pair<FileID,unsigned> & ROffs) const1953b1c73532SDimitry Andric bool SourceManager::isInTheSameTranslationUnitImpl(
1954b1c73532SDimitry Andric const std::pair<FileID, unsigned> &LOffs,
1955b1c73532SDimitry Andric const std::pair<FileID, unsigned> &ROffs) const {
1956b1c73532SDimitry Andric // If one is local while the other is loaded.
1957b1c73532SDimitry Andric if (isLoadedFileID(LOffs.first) != isLoadedFileID(ROffs.first))
1958b1c73532SDimitry Andric return false;
1959b1c73532SDimitry Andric
1960b1c73532SDimitry Andric if (isLoadedFileID(LOffs.first) && isLoadedFileID(ROffs.first)) {
1961b1c73532SDimitry Andric auto FindSLocEntryAlloc = [this](FileID FID) {
1962b1c73532SDimitry Andric // Loaded FileIDs are negative, we store the lowest FileID from each
1963b1c73532SDimitry Andric // allocation, later allocations have lower FileIDs.
1964b1c73532SDimitry Andric return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID,
1965b1c73532SDimitry Andric std::greater<FileID>{});
1966b1c73532SDimitry Andric };
1967b1c73532SDimitry Andric
1968b1c73532SDimitry Andric // If both are loaded from different AST files.
1969b1c73532SDimitry Andric if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first))
1970b1c73532SDimitry Andric return false;
1971b1c73532SDimitry Andric }
1972b1c73532SDimitry Andric
1973b1c73532SDimitry Andric return true;
1974b1c73532SDimitry Andric }
1975b1c73532SDimitry Andric
197636981b17SDimitry Andric /// Given a decomposed source location, move it up the include/expansion stack
1977b1c73532SDimitry Andric /// to the parent source location within the same translation unit. If this is
1978b1c73532SDimitry Andric /// possible, return the decomposed version of the parent in Loc and return
1979b1c73532SDimitry Andric /// false. If Loc is a top-level entry, return true and don't modify it.
1980b1c73532SDimitry Andric static bool
MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID,unsigned> & Loc,const SourceManager & SM)1981b1c73532SDimitry Andric MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1982d7279c4cSRoman Divacky const SourceManager &SM) {
19836a037251SDimitry Andric std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1984b1c73532SDimitry Andric if (UpperLoc.first.isInvalid() ||
1985b1c73532SDimitry Andric !SM.isInTheSameTranslationUnitImpl(UpperLoc, Loc))
1986d7279c4cSRoman Divacky return true; // We reached the top.
1987d7279c4cSRoman Divacky
19886a037251SDimitry Andric Loc = UpperLoc;
1989d7279c4cSRoman Divacky return false;
1990d7279c4cSRoman Divacky }
1991d7279c4cSRoman Divacky
1992809500fcSDimitry Andric /// Return the cache entry for comparing the given file IDs
1993809500fcSDimitry Andric /// for isBeforeInTranslationUnit.
getInBeforeInTUCache(FileID LFID,FileID RFID) const1994809500fcSDimitry Andric InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1995809500fcSDimitry Andric FileID RFID) const {
1996809500fcSDimitry Andric // This is a magic number for limiting the cache size. It was experimentally
1997809500fcSDimitry Andric // derived from a small Objective-C project (where the cache filled
1998809500fcSDimitry Andric // out to ~250 items). We can make it larger if necessary.
1999e3b55780SDimitry Andric // FIXME: this is almost certainly full these days. Use an LRU cache?
2000809500fcSDimitry Andric enum { MagicCacheSize = 300 };
2001809500fcSDimitry Andric IsBeforeInTUCacheKey Key(LFID, RFID);
2002809500fcSDimitry Andric
2003809500fcSDimitry Andric // If the cache size isn't too large, do a lookup and if necessary default
2004809500fcSDimitry Andric // construct an entry. We can then return it to the caller for direct
2005809500fcSDimitry Andric // use. When they update the value, the cache will get automatically
2006809500fcSDimitry Andric // updated as well.
2007809500fcSDimitry Andric if (IBTUCache.size() < MagicCacheSize)
2008e3b55780SDimitry Andric return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
2009809500fcSDimitry Andric
2010809500fcSDimitry Andric // Otherwise, do a lookup that will not construct a new value.
2011809500fcSDimitry Andric InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2012809500fcSDimitry Andric if (I != IBTUCache.end())
2013809500fcSDimitry Andric return I->second;
2014809500fcSDimitry Andric
2015809500fcSDimitry Andric // Fall back to the overflow value.
2016e3b55780SDimitry Andric IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
2017809500fcSDimitry Andric return IBTUCacheOverflow;
2018809500fcSDimitry Andric }
2019d7279c4cSRoman Divacky
202048675466SDimitry Andric /// Determines the order of 2 source locations in the translation unit.
20214ebdf5c4SEd Schouten ///
20224ebdf5c4SEd Schouten /// \returns true if LHS source location comes before RHS, false otherwise.
isBeforeInTranslationUnit(SourceLocation LHS,SourceLocation RHS) const20234ebdf5c4SEd Schouten bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
20244ebdf5c4SEd Schouten SourceLocation RHS) const {
20254ebdf5c4SEd Schouten assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
20264ebdf5c4SEd Schouten if (LHS == RHS)
20274ebdf5c4SEd Schouten return false;
20284ebdf5c4SEd Schouten
20294ebdf5c4SEd Schouten std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
20304ebdf5c4SEd Schouten std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
20314ebdf5c4SEd Schouten
2032bfef3995SDimitry Andric // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2033bfef3995SDimitry Andric // is a serialized one referring to a file that was removed after we loaded
2034bfef3995SDimitry Andric // the PCH.
2035bfef3995SDimitry Andric if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2036bfef3995SDimitry Andric return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2037bfef3995SDimitry Andric
2038cf1b4019SDimitry Andric std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2039cf1b4019SDimitry Andric if (InSameTU.first)
2040cf1b4019SDimitry Andric return InSameTU.second;
2041b1c73532SDimitry Andric // TODO: This should be unreachable, but some clients are calling this
2042b1c73532SDimitry Andric // function before making sure LHS and RHS are in the same TU.
2043d7279c4cSRoman Divacky return LOffs.first < ROffs.first;
20444c8b2481SRoman Divacky }
20454c8b2481SRoman Divacky
isInTheSameTranslationUnit(std::pair<FileID,unsigned> & LOffs,std::pair<FileID,unsigned> & ROffs) const2046cf1b4019SDimitry Andric std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2047cf1b4019SDimitry Andric std::pair<FileID, unsigned> &LOffs,
2048cf1b4019SDimitry Andric std::pair<FileID, unsigned> &ROffs) const {
2049b1c73532SDimitry Andric // If the source locations are not in the same TU, return early.
2050b1c73532SDimitry Andric if (!isInTheSameTranslationUnitImpl(LOffs, ROffs))
2051b1c73532SDimitry Andric return std::make_pair(false, false);
2052b1c73532SDimitry Andric
2053cf1b4019SDimitry Andric // If the source locations are in the same file, just compare offsets.
2054cf1b4019SDimitry Andric if (LOffs.first == ROffs.first)
2055cf1b4019SDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second);
2056cf1b4019SDimitry Andric
2057cf1b4019SDimitry Andric // If we are comparing a source location with multiple locations in the same
2058cf1b4019SDimitry Andric // file, we get a big win by caching the result.
2059cf1b4019SDimitry Andric InBeforeInTUCacheEntry &IsBeforeInTUCache =
2060cf1b4019SDimitry Andric getInBeforeInTUCache(LOffs.first, ROffs.first);
2061cf1b4019SDimitry Andric
2062cf1b4019SDimitry Andric // If we are comparing a source location with multiple locations in the same
2063cf1b4019SDimitry Andric // file, we get a big win by caching the result.
2064e3b55780SDimitry Andric if (IsBeforeInTUCache.isCacheValid())
2065cf1b4019SDimitry Andric return std::make_pair(
2066cf1b4019SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2067cf1b4019SDimitry Andric
2068e3b55780SDimitry Andric // Okay, we missed in the cache, we'll compute the answer and populate it.
2069cf1b4019SDimitry Andric // We need to find the common ancestor. The only way of doing this is to
2070cf1b4019SDimitry Andric // build the complete include chain for one and then walking up the chain
2071cf1b4019SDimitry Andric // of the other looking for a match.
2072e3b55780SDimitry Andric
2073e3b55780SDimitry Andric // A location within a FileID on the path up from LOffs to the main file.
2074e3b55780SDimitry Andric struct Entry {
2075b1c73532SDimitry Andric std::pair<FileID, unsigned> DecomposedLoc; // FileID redundant, but clearer.
2076b1c73532SDimitry Andric FileID ChildFID; // Used for breaking ties. Invalid for the initial loc.
2077e3b55780SDimitry Andric };
2078e3b55780SDimitry Andric llvm::SmallDenseMap<FileID, Entry, 16> LChain;
2079e3b55780SDimitry Andric
2080b1c73532SDimitry Andric FileID LChild;
2081cf1b4019SDimitry Andric do {
2082b1c73532SDimitry Andric LChain.try_emplace(LOffs.first, Entry{LOffs, LChild});
2083cf1b4019SDimitry Andric // We catch the case where LOffs is in a file included by ROffs and
2084cf1b4019SDimitry Andric // quit early. The other way round unfortunately remains suboptimal.
2085e3b55780SDimitry Andric if (LOffs.first == ROffs.first)
2086e3b55780SDimitry Andric break;
2087b1c73532SDimitry Andric LChild = LOffs.first;
2088b1c73532SDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(LOffs, *this));
2089cf1b4019SDimitry Andric
2090b1c73532SDimitry Andric FileID RChild;
2091e3b55780SDimitry Andric do {
2092b1c73532SDimitry Andric auto LIt = LChain.find(ROffs.first);
2093b1c73532SDimitry Andric if (LIt != LChain.end()) {
2094e3b55780SDimitry Andric // Compare the locations within the common file and cache them.
2095b1c73532SDimitry Andric LOffs = LIt->second.DecomposedLoc;
2096b1c73532SDimitry Andric LChild = LIt->second.ChildFID;
2097b1c73532SDimitry Andric // The relative order of LChild and RChild is a tiebreaker when
2098e3b55780SDimitry Andric // - locs expand to the same location (occurs in macro arg expansion)
2099e3b55780SDimitry Andric // - one loc is a parent of the other (we consider the parent as "first")
2100b1c73532SDimitry Andric // For the parent entry to be first, its invalid child file ID must
2101b1c73532SDimitry Andric // compare smaller to the valid child file ID of the other entry.
2102e3b55780SDimitry Andric // However loaded FileIDs are <0, so we perform *unsigned* comparison!
2103e3b55780SDimitry Andric // This changes the relative order of local vs loaded FileIDs, but it
2104e3b55780SDimitry Andric // doesn't matter as these are never mixed in macro expansion.
2105b1c73532SDimitry Andric unsigned LChildID = LChild.ID;
2106b1c73532SDimitry Andric unsigned RChildID = RChild.ID;
2107e3b55780SDimitry Andric assert(((LOffs.second != ROffs.second) ||
2108b1c73532SDimitry Andric (LChildID == 0 || RChildID == 0) ||
2109b1c73532SDimitry Andric isInSameSLocAddrSpace(getComposedLoc(LChild, 0),
2110b1c73532SDimitry Andric getComposedLoc(RChild, 0), nullptr)) &&
2111e3b55780SDimitry Andric "Mixed local/loaded FileIDs with same include location?");
2112e3b55780SDimitry Andric IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
2113b1c73532SDimitry Andric LChildID < RChildID);
2114cf1b4019SDimitry Andric return std::make_pair(
2115cf1b4019SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2116cf1b4019SDimitry Andric }
2117b1c73532SDimitry Andric RChild = ROffs.first;
2118b1c73532SDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(ROffs, *this));
2119e3b55780SDimitry Andric
2120b1c73532SDimitry Andric // If we found no match, the location is either in a built-ins buffer or
2121b1c73532SDimitry Andric // associated with global inline asm. PR5662 and PR22576 are examples.
2122b1c73532SDimitry Andric
2123b1c73532SDimitry Andric StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2124b1c73532SDimitry Andric StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
2125b1c73532SDimitry Andric
2126b1c73532SDimitry Andric bool LIsBuiltins = LB == "<built-in>";
2127b1c73532SDimitry Andric bool RIsBuiltins = RB == "<built-in>";
2128b1c73532SDimitry Andric // Sort built-in before non-built-in.
2129b1c73532SDimitry Andric if (LIsBuiltins || RIsBuiltins) {
2130b1c73532SDimitry Andric if (LIsBuiltins != RIsBuiltins)
2131b1c73532SDimitry Andric return std::make_pair(true, LIsBuiltins);
2132b1c73532SDimitry Andric // Both are in built-in buffers, but from different files. We just claim
2133b1c73532SDimitry Andric // that lower IDs come first.
2134b1c73532SDimitry Andric return std::make_pair(true, LOffs.first < ROffs.first);
2135b1c73532SDimitry Andric }
2136b1c73532SDimitry Andric
2137b1c73532SDimitry Andric bool LIsAsm = LB == "<inline asm>";
2138b1c73532SDimitry Andric bool RIsAsm = RB == "<inline asm>";
2139b1c73532SDimitry Andric // Sort assembler after built-ins, but before the rest.
2140b1c73532SDimitry Andric if (LIsAsm || RIsAsm) {
2141b1c73532SDimitry Andric if (LIsAsm != RIsAsm)
2142b1c73532SDimitry Andric return std::make_pair(true, RIsAsm);
2143b1c73532SDimitry Andric assert(LOffs.first == ROffs.first);
2144b1c73532SDimitry Andric return std::make_pair(true, false);
2145b1c73532SDimitry Andric }
2146b1c73532SDimitry Andric
2147b1c73532SDimitry Andric bool LIsScratch = LB == "<scratch space>";
2148b1c73532SDimitry Andric bool RIsScratch = RB == "<scratch space>";
2149b1c73532SDimitry Andric // Sort scratch after inline asm, but before the rest.
2150b1c73532SDimitry Andric if (LIsScratch || RIsScratch) {
2151b1c73532SDimitry Andric if (LIsScratch != RIsScratch)
2152b1c73532SDimitry Andric return std::make_pair(true, LIsScratch);
2153b1c73532SDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second);
2154b1c73532SDimitry Andric }
2155b1c73532SDimitry Andric
2156b1c73532SDimitry Andric llvm_unreachable("Unsortable locations found");
2157cf1b4019SDimitry Andric }
2158cf1b4019SDimitry Andric
PrintStats() const2159ec2b103cSEd Schouten void SourceManager::PrintStats() const {
21604c8b2481SRoman Divacky llvm::errs() << "\n*** Source Manager Stats:\n";
21614c8b2481SRoman Divacky llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2162ec2b103cSEd Schouten << " mem buffers mapped.\n";
2163b1c73532SDimitry Andric llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntries allocated ("
216436981b17SDimitry Andric << llvm::capacity_in_bytes(LocalSLocEntryTable)
2165b1c73532SDimitry Andric << " bytes of capacity), " << NextLocalOffset
2166b1c73532SDimitry Andric << "B of SLoc address space used.\n";
216736981b17SDimitry Andric llvm::errs() << LoadedSLocEntryTable.size()
2168b1c73532SDimitry Andric << " loaded SLocEntries allocated ("
2169b1c73532SDimitry Andric << llvm::capacity_in_bytes(LoadedSLocEntryTable)
2170b1c73532SDimitry Andric << " bytes of capacity), "
217136981b17SDimitry Andric << MaxLoadedOffset - CurrentLoadedOffset
2172b1c73532SDimitry Andric << "B of SLoc address space used.\n";
2173ec2b103cSEd Schouten
2174ec2b103cSEd Schouten unsigned NumLineNumsComputed = 0;
2175ec2b103cSEd Schouten unsigned NumFileBytesMapped = 0;
2176ec2b103cSEd Schouten for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2177b60736ecSDimitry Andric NumLineNumsComputed += bool(I->second->SourceLineCache);
2178ec2b103cSEd Schouten NumFileBytesMapped += I->second->getSizeBytesMapped();
2179ec2b103cSEd Schouten }
218036981b17SDimitry Andric unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2181ec2b103cSEd Schouten
21824c8b2481SRoman Divacky llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
218336981b17SDimitry Andric << NumLineNumsComputed << " files with line #'s computed, "
218436981b17SDimitry Andric << NumMacroArgsComputed << " files with macro args computed.\n";
21854c8b2481SRoman Divacky llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2186ec2b103cSEd Schouten << NumBinaryProbes << " binary.\n";
2187ec2b103cSEd Schouten }
2188ec2b103cSEd Schouten
dump() const218945b53394SDimitry Andric LLVM_DUMP_METHOD void SourceManager::dump() const {
219045b53394SDimitry Andric llvm::raw_ostream &out = llvm::errs();
219145b53394SDimitry Andric
219245b53394SDimitry Andric auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2193e3b55780SDimitry Andric std::optional<SourceLocation::UIntTy> NextStart) {
219445b53394SDimitry Andric out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
219545b53394SDimitry Andric << " <SourceLocation " << Entry.getOffset() << ":";
219645b53394SDimitry Andric if (NextStart)
219745b53394SDimitry Andric out << *NextStart << ">\n";
219845b53394SDimitry Andric else
219945b53394SDimitry Andric out << "???\?>\n";
220045b53394SDimitry Andric if (Entry.isFile()) {
220145b53394SDimitry Andric auto &FI = Entry.getFile();
220245b53394SDimitry Andric if (FI.NumCreatedFIDs)
220345b53394SDimitry Andric out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
220445b53394SDimitry Andric << ">\n";
220545b53394SDimitry Andric if (FI.getIncludeLoc().isValid())
220645b53394SDimitry Andric out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2207b60736ecSDimitry Andric auto &CC = FI.getContentCache();
2208b60736ecSDimitry Andric out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
220945b53394SDimitry Andric << "\n";
2210b60736ecSDimitry Andric if (CC.BufferOverridden)
221145b53394SDimitry Andric out << " contents overridden\n";
2212b60736ecSDimitry Andric if (CC.ContentsEntry != CC.OrigEntry) {
221345b53394SDimitry Andric out << " contents from "
2214b60736ecSDimitry Andric << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
221545b53394SDimitry Andric << "\n";
221645b53394SDimitry Andric }
221745b53394SDimitry Andric } else {
221845b53394SDimitry Andric auto &EI = Entry.getExpansion();
221945b53394SDimitry Andric out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
222045b53394SDimitry Andric out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
222145b53394SDimitry Andric << " range <" << EI.getExpansionLocStart().getOffset() << ":"
222245b53394SDimitry Andric << EI.getExpansionLocEnd().getOffset() << ">\n";
222345b53394SDimitry Andric }
222445b53394SDimitry Andric };
222545b53394SDimitry Andric
222645b53394SDimitry Andric // Dump local SLocEntries.
222745b53394SDimitry Andric for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
222845b53394SDimitry Andric DumpSLocEntry(ID, LocalSLocEntryTable[ID],
222945b53394SDimitry Andric ID == NumIDs - 1 ? NextLocalOffset
223045b53394SDimitry Andric : LocalSLocEntryTable[ID + 1].getOffset());
223145b53394SDimitry Andric }
223245b53394SDimitry Andric // Dump loaded SLocEntries.
2233e3b55780SDimitry Andric std::optional<SourceLocation::UIntTy> NextStart;
223445b53394SDimitry Andric for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
223545b53394SDimitry Andric int ID = -(int)Index - 2;
223645b53394SDimitry Andric if (SLocEntryLoaded[Index]) {
223745b53394SDimitry Andric DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
223845b53394SDimitry Andric NextStart = LoadedSLocEntryTable[Index].getOffset();
223945b53394SDimitry Andric } else {
2240e3b55780SDimitry Andric NextStart = std::nullopt;
224145b53394SDimitry Andric }
224245b53394SDimitry Andric }
224345b53394SDimitry Andric }
224445b53394SDimitry Andric
noteSLocAddressSpaceUsage(DiagnosticsEngine & Diag,std::optional<unsigned> MaxNotes) const2245e3b55780SDimitry Andric void SourceManager::noteSLocAddressSpaceUsage(
2246e3b55780SDimitry Andric DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {
2247e3b55780SDimitry Andric struct Info {
2248e3b55780SDimitry Andric // A location where this file was entered.
2249e3b55780SDimitry Andric SourceLocation Loc;
2250e3b55780SDimitry Andric // Number of times this FileEntry was entered.
2251e3b55780SDimitry Andric unsigned Inclusions = 0;
2252e3b55780SDimitry Andric // Size usage from the file itself.
2253e3b55780SDimitry Andric uint64_t DirectSize = 0;
2254e3b55780SDimitry Andric // Total size usage from the file and its macro expansions.
2255e3b55780SDimitry Andric uint64_t TotalSize = 0;
2256e3b55780SDimitry Andric };
2257e3b55780SDimitry Andric using UsageMap = llvm::MapVector<const FileEntry*, Info>;
2258e3b55780SDimitry Andric
2259e3b55780SDimitry Andric UsageMap Usage;
2260e3b55780SDimitry Andric uint64_t CountedSize = 0;
2261e3b55780SDimitry Andric
2262e3b55780SDimitry Andric auto AddUsageForFileID = [&](FileID ID) {
2263e3b55780SDimitry Andric // The +1 here is because getFileIDSize doesn't include the extra byte for
2264e3b55780SDimitry Andric // the one-past-the-end location.
2265e3b55780SDimitry Andric unsigned Size = getFileIDSize(ID) + 1;
2266e3b55780SDimitry Andric
2267e3b55780SDimitry Andric // Find the file that used this address space, either directly or by
2268e3b55780SDimitry Andric // macro expansion.
2269e3b55780SDimitry Andric SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));
2270e3b55780SDimitry Andric FileID FileLocID = getFileID(FileStart);
2271e3b55780SDimitry Andric const FileEntry *Entry = getFileEntryForID(FileLocID);
2272e3b55780SDimitry Andric
2273e3b55780SDimitry Andric Info &EntryInfo = Usage[Entry];
2274e3b55780SDimitry Andric if (EntryInfo.Loc.isInvalid())
2275e3b55780SDimitry Andric EntryInfo.Loc = FileStart;
2276e3b55780SDimitry Andric if (ID == FileLocID) {
2277e3b55780SDimitry Andric ++EntryInfo.Inclusions;
2278e3b55780SDimitry Andric EntryInfo.DirectSize += Size;
2279e3b55780SDimitry Andric }
2280e3b55780SDimitry Andric EntryInfo.TotalSize += Size;
2281e3b55780SDimitry Andric CountedSize += Size;
2282e3b55780SDimitry Andric };
2283e3b55780SDimitry Andric
2284e3b55780SDimitry Andric // Loaded SLocEntries have indexes counting downwards from -2.
2285e3b55780SDimitry Andric for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2286e3b55780SDimitry Andric AddUsageForFileID(FileID::get(-2 - Index));
2287e3b55780SDimitry Andric }
2288e3b55780SDimitry Andric // Local SLocEntries have indexes counting upwards from 0.
2289e3b55780SDimitry Andric for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
2290e3b55780SDimitry Andric AddUsageForFileID(FileID::get(Index));
2291e3b55780SDimitry Andric }
2292e3b55780SDimitry Andric
2293e3b55780SDimitry Andric // Sort the usage by size from largest to smallest. Break ties by raw source
2294e3b55780SDimitry Andric // location.
2295e3b55780SDimitry Andric auto SortedUsage = Usage.takeVector();
2296e3b55780SDimitry Andric auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {
2297e3b55780SDimitry Andric return A.second.TotalSize > B.second.TotalSize ||
2298e3b55780SDimitry Andric (A.second.TotalSize == B.second.TotalSize &&
2299e3b55780SDimitry Andric A.second.Loc < B.second.Loc);
2300e3b55780SDimitry Andric };
2301e3b55780SDimitry Andric auto SortedEnd = SortedUsage.end();
2302e3b55780SDimitry Andric if (MaxNotes && SortedUsage.size() > *MaxNotes) {
2303e3b55780SDimitry Andric SortedEnd = SortedUsage.begin() + *MaxNotes;
2304e3b55780SDimitry Andric std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);
2305e3b55780SDimitry Andric }
2306e3b55780SDimitry Andric std::sort(SortedUsage.begin(), SortedEnd, Cmp);
2307e3b55780SDimitry Andric
2308e3b55780SDimitry Andric // Produce note on sloc address space usage total.
2309e3b55780SDimitry Andric uint64_t LocalUsage = NextLocalOffset;
2310e3b55780SDimitry Andric uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
2311e3b55780SDimitry Andric int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /
2312e3b55780SDimitry Andric MaxLoadedOffset);
2313e3b55780SDimitry Andric Diag.Report(SourceLocation(), diag::note_total_sloc_usage)
2314e3b55780SDimitry Andric << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;
2315e3b55780SDimitry Andric
2316e3b55780SDimitry Andric // Produce notes on sloc address space usage for each file with a high usage.
2317e3b55780SDimitry Andric uint64_t ReportedSize = 0;
2318e3b55780SDimitry Andric for (auto &[Entry, FileInfo] :
2319e3b55780SDimitry Andric llvm::make_range(SortedUsage.begin(), SortedEnd)) {
2320e3b55780SDimitry Andric Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)
2321e3b55780SDimitry Andric << FileInfo.Inclusions << FileInfo.DirectSize
2322e3b55780SDimitry Andric << (FileInfo.TotalSize - FileInfo.DirectSize);
2323e3b55780SDimitry Andric ReportedSize += FileInfo.TotalSize;
2324e3b55780SDimitry Andric }
2325e3b55780SDimitry Andric
2326e3b55780SDimitry Andric // Describe any remaining usage not reported in the per-file usage.
2327e3b55780SDimitry Andric if (ReportedSize != CountedSize) {
2328e3b55780SDimitry Andric Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)
2329e3b55780SDimitry Andric << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
2330e3b55780SDimitry Andric }
2331e3b55780SDimitry Andric }
2332e3b55780SDimitry Andric
2333461a67faSDimitry Andric ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
233401af97d3SDimitry Andric
233501af97d3SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down
233601af97d3SDimitry Andric /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes() const233701af97d3SDimitry Andric SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
233801af97d3SDimitry Andric size_t malloc_bytes = 0;
233901af97d3SDimitry Andric size_t mmap_bytes = 0;
234001af97d3SDimitry Andric
234101af97d3SDimitry Andric for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
234201af97d3SDimitry Andric if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
234301af97d3SDimitry Andric switch (MemBufferInfos[i]->getMemoryBufferKind()) {
234401af97d3SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_MMap:
234501af97d3SDimitry Andric mmap_bytes += sized_mapped;
234601af97d3SDimitry Andric break;
234701af97d3SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_Malloc:
234801af97d3SDimitry Andric malloc_bytes += sized_mapped;
234901af97d3SDimitry Andric break;
235001af97d3SDimitry Andric }
235101af97d3SDimitry Andric
235201af97d3SDimitry Andric return MemoryBufferSizes(malloc_bytes, mmap_bytes);
235301af97d3SDimitry Andric }
235401af97d3SDimitry Andric
getDataStructureSizes() const235536981b17SDimitry Andric size_t SourceManager::getDataStructureSizes() const {
2356b1c73532SDimitry Andric size_t size = llvm::capacity_in_bytes(MemBufferInfos) +
2357b1c73532SDimitry Andric llvm::capacity_in_bytes(LocalSLocEntryTable) +
2358b1c73532SDimitry Andric llvm::capacity_in_bytes(LoadedSLocEntryTable) +
2359b1c73532SDimitry Andric llvm::capacity_in_bytes(SLocEntryLoaded) +
2360b1c73532SDimitry Andric llvm::capacity_in_bytes(FileInfos);
236156d91b49SDimitry Andric
236256d91b49SDimitry Andric if (OverriddenFilesInfo)
236356d91b49SDimitry Andric size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
236456d91b49SDimitry Andric
236556d91b49SDimitry Andric return size;
236636981b17SDimitry Andric }
236748675466SDimitry Andric
SourceManagerForFile(StringRef FileName,StringRef Content)236848675466SDimitry Andric SourceManagerForFile::SourceManagerForFile(StringRef FileName,
236948675466SDimitry Andric StringRef Content) {
237048675466SDimitry Andric // This is referenced by `FileMgr` and will be released by `FileMgr` when it
237148675466SDimitry Andric // is deleted.
2372676fbe81SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2373676fbe81SDimitry Andric new llvm::vfs::InMemoryFileSystem);
237448675466SDimitry Andric InMemoryFileSystem->addFile(
237548675466SDimitry Andric FileName, 0,
237648675466SDimitry Andric llvm::MemoryBuffer::getMemBuffer(Content, FileName,
237748675466SDimitry Andric /*RequiresNullTerminator=*/false));
237848675466SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced
237948675466SDimitry Andric // in `Environment` so that `FileMgr` can out-live this function scope.
238048675466SDimitry Andric FileMgr =
2381519fc96cSDimitry Andric std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
238248675466SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced
238348675466SDimitry Andric // by `Environment` due to the same reason above.
2384519fc96cSDimitry Andric Diagnostics = std::make_unique<DiagnosticsEngine>(
238548675466SDimitry Andric IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
238648675466SDimitry Andric new DiagnosticOptions);
2387519fc96cSDimitry Andric SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2388b1c73532SDimitry Andric FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName));
2389b1c73532SDimitry Andric FileID ID =
2390b1c73532SDimitry Andric SourceMgr->createFileID(FE, SourceLocation(), clang::SrcMgr::C_User);
239148675466SDimitry Andric assert(ID.isValid());
239248675466SDimitry Andric SourceMgr->setMainFileID(ID);
239348675466SDimitry Andric }
2394