10b57cec5SDimitry Andric //===- SourceManager.cpp - Track and cache source files -------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the SourceManager interface.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
140b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
150b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
160b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
170b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
180b57cec5SDimitry Andric #include "clang/Basic/SourceManagerInternals.h"
190b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
20bdd1243dSDimitry Andric #include "llvm/ADT/MapVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
230b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
245ffd83dbSDimitry Andric #include "llvm/ADT/StringSwitch.h"
250b57cec5SDimitry Andric #include "llvm/Support/Allocator.h"
260b57cec5SDimitry Andric #include "llvm/Support/Capacity.h"
270b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
28fe6060f1SDimitry Andric #include "llvm/Support/Endian.h"
290b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
300b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
310b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
320b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
330b57cec5SDimitry Andric #include "llvm/Support/Path.h"
340b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
350b57cec5SDimitry Andric #include <algorithm>
360b57cec5SDimitry Andric #include <cassert>
370b57cec5SDimitry Andric #include <cstddef>
380b57cec5SDimitry Andric #include <cstdint>
390b57cec5SDimitry Andric #include <memory>
40bdd1243dSDimitry Andric #include <optional>
410b57cec5SDimitry Andric #include <tuple>
420b57cec5SDimitry Andric #include <utility>
430b57cec5SDimitry Andric #include <vector>
440b57cec5SDimitry Andric
450b57cec5SDimitry Andric using namespace clang;
460b57cec5SDimitry Andric using namespace SrcMgr;
470b57cec5SDimitry Andric using llvm::MemoryBuffer;
480b57cec5SDimitry Andric
490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
500b57cec5SDimitry Andric // SourceManager Helper Classes
510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
540b57cec5SDimitry Andric /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
getSizeBytesMapped() const550b57cec5SDimitry Andric unsigned ContentCache::getSizeBytesMapped() const {
56e8d8bef9SDimitry Andric return Buffer ? Buffer->getBufferSize() : 0;
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric
590b57cec5SDimitry Andric /// Returns the kind of memory used to back the memory buffer for
600b57cec5SDimitry Andric /// this content cache. This is used for performance analysis.
getMemoryBufferKind() const610b57cec5SDimitry Andric llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
625e801ac6SDimitry Andric if (Buffer == nullptr) {
635e801ac6SDimitry Andric assert(0 && "Buffer should never be null");
640b57cec5SDimitry Andric return llvm::MemoryBuffer::MemoryBuffer_Malloc;
655e801ac6SDimitry Andric }
66e8d8bef9SDimitry Andric return Buffer->getBufferKind();
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric
690b57cec5SDimitry Andric /// getSize - Returns the size of the content encapsulated by this ContentCache.
700b57cec5SDimitry Andric /// This can be the size of the source file or the size of an arbitrary
710b57cec5SDimitry Andric /// scratch buffer. If the ContentCache encapsulates a source file, that
720b57cec5SDimitry Andric /// file is not lazily brought in from disk to satisfy this query.
getSize() const730b57cec5SDimitry Andric unsigned ContentCache::getSize() const {
74e8d8bef9SDimitry Andric return Buffer ? (unsigned)Buffer->getBufferSize()
750b57cec5SDimitry Andric : (unsigned)ContentsEntry->getSize();
760b57cec5SDimitry Andric }
770b57cec5SDimitry Andric
getInvalidBOM(StringRef BufStr)78480093f4SDimitry Andric const char *ContentCache::getInvalidBOM(StringRef BufStr) {
79480093f4SDimitry Andric // If the buffer is valid, check to see if it has a UTF Byte Order Mark
80480093f4SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See
81480093f4SDimitry Andric // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
82480093f4SDimitry Andric const char *InvalidBOM =
83480093f4SDimitry Andric llvm::StringSwitch<const char *>(BufStr)
84480093f4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
85480093f4SDimitry Andric "UTF-32 (BE)")
86480093f4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
87480093f4SDimitry Andric "UTF-32 (LE)")
88480093f4SDimitry Andric .StartsWith("\xFE\xFF", "UTF-16 (BE)")
89480093f4SDimitry Andric .StartsWith("\xFF\xFE", "UTF-16 (LE)")
90480093f4SDimitry Andric .StartsWith("\x2B\x2F\x76", "UTF-7")
91480093f4SDimitry Andric .StartsWith("\xF7\x64\x4C", "UTF-1")
92480093f4SDimitry Andric .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
93480093f4SDimitry Andric .StartsWith("\x0E\xFE\xFF", "SCSU")
94480093f4SDimitry Andric .StartsWith("\xFB\xEE\x28", "BOCU-1")
95480093f4SDimitry Andric .StartsWith("\x84\x31\x95\x33", "GB-18030")
96480093f4SDimitry Andric .Default(nullptr);
97480093f4SDimitry Andric
98480093f4SDimitry Andric return InvalidBOM;
99480093f4SDimitry Andric }
100480093f4SDimitry Andric
101bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine & Diag,FileManager & FM,SourceLocation Loc) const102e8d8bef9SDimitry Andric ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
103e8d8bef9SDimitry Andric SourceLocation Loc) const {
1040b57cec5SDimitry Andric // Lazily create the Buffer for ContentCaches that wrap files. If we already
1050b57cec5SDimitry Andric // computed it, just return what we have.
106e8d8bef9SDimitry Andric if (IsBufferInvalid)
107bdd1243dSDimitry Andric return std::nullopt;
108e8d8bef9SDimitry Andric if (Buffer)
109e8d8bef9SDimitry Andric return Buffer->getMemBufferRef();
110e8d8bef9SDimitry Andric if (!ContentsEntry)
111bdd1243dSDimitry Andric return std::nullopt;
1120b57cec5SDimitry Andric
113e8d8bef9SDimitry Andric // Start with the assumption that the buffer is invalid to simplify early
114e8d8bef9SDimitry Andric // return paths.
115e8d8bef9SDimitry Andric IsBufferInvalid = true;
1160b57cec5SDimitry Andric
1175f757f3fSDimitry Andric auto BufferOrError = FM.getBufferForFile(*ContentsEntry, IsFileVolatile);
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric // If we were unable to open the file, then we are in an inconsistent
1200b57cec5SDimitry Andric // situation where the content cache referenced a file which no longer
1210b57cec5SDimitry Andric // exists. Most likely, we were using a stat cache with an invalid entry but
1220b57cec5SDimitry Andric // the file could also have been removed during processing. Since we can't
1230b57cec5SDimitry Andric // really deal with this situation, just create an empty buffer.
1240b57cec5SDimitry Andric if (!BufferOrError) {
1250b57cec5SDimitry Andric if (Diag.isDiagnosticInFlight())
1260b57cec5SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
1270b57cec5SDimitry Andric ContentsEntry->getName(),
1280b57cec5SDimitry Andric BufferOrError.getError().message());
1290b57cec5SDimitry Andric else
1300b57cec5SDimitry Andric Diag.Report(Loc, diag::err_cannot_open_file)
1310b57cec5SDimitry Andric << ContentsEntry->getName() << BufferOrError.getError().message();
1320b57cec5SDimitry Andric
133bdd1243dSDimitry Andric return std::nullopt;
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric
136e8d8bef9SDimitry Andric Buffer = std::move(*BufferOrError);
1370b57cec5SDimitry Andric
138e8d8bef9SDimitry Andric // Check that the file's size fits in an 'unsigned' (with room for a
139e8d8bef9SDimitry Andric // past-the-end value). This is deeply regrettable, but various parts of
140e8d8bef9SDimitry Andric // Clang (including elsewhere in this file!) use 'unsigned' to represent file
141e8d8bef9SDimitry Andric // offsets, line numbers, string literal lengths, and so on, and fail
142e8d8bef9SDimitry Andric // miserably on large source files.
143e8d8bef9SDimitry Andric //
144e8d8bef9SDimitry Andric // Note: ContentsEntry could be a named pipe, in which case
145e8d8bef9SDimitry Andric // ContentsEntry::getSize() could have the wrong size. Use
146e8d8bef9SDimitry Andric // MemoryBuffer::getBufferSize() instead.
147e8d8bef9SDimitry Andric if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
148e8d8bef9SDimitry Andric if (Diag.isDiagnosticInFlight())
149e8d8bef9SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_file_too_large,
150e8d8bef9SDimitry Andric ContentsEntry->getName());
151e8d8bef9SDimitry Andric else
152e8d8bef9SDimitry Andric Diag.Report(Loc, diag::err_file_too_large)
153e8d8bef9SDimitry Andric << ContentsEntry->getName();
154e8d8bef9SDimitry Andric
155bdd1243dSDimitry Andric return std::nullopt;
156e8d8bef9SDimitry Andric }
157e8d8bef9SDimitry Andric
158e8d8bef9SDimitry Andric // Unless this is a named pipe (in which case we can handle a mismatch),
159e8d8bef9SDimitry Andric // check that the file's size is the same as in the file entry (which may
1600b57cec5SDimitry Andric // have come from a stat cache).
161e8d8bef9SDimitry Andric if (!ContentsEntry->isNamedPipe() &&
162e8d8bef9SDimitry Andric Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
1630b57cec5SDimitry Andric if (Diag.isDiagnosticInFlight())
1640b57cec5SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_file_modified,
1650b57cec5SDimitry Andric ContentsEntry->getName());
1660b57cec5SDimitry Andric else
1670b57cec5SDimitry Andric Diag.Report(Loc, diag::err_file_modified)
1680b57cec5SDimitry Andric << ContentsEntry->getName();
1690b57cec5SDimitry Andric
170bdd1243dSDimitry Andric return std::nullopt;
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric
1730b57cec5SDimitry Andric // If the buffer is valid, check to see if it has a UTF Byte Order Mark
1740b57cec5SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See
1750b57cec5SDimitry Andric // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
176e8d8bef9SDimitry Andric StringRef BufStr = Buffer->getBuffer();
177480093f4SDimitry Andric const char *InvalidBOM = getInvalidBOM(BufStr);
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric if (InvalidBOM) {
1800b57cec5SDimitry Andric Diag.Report(Loc, diag::err_unsupported_bom)
1810b57cec5SDimitry Andric << InvalidBOM << ContentsEntry->getName();
182bdd1243dSDimitry Andric return std::nullopt;
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric
185e8d8bef9SDimitry Andric // Buffer has been validated.
186e8d8bef9SDimitry Andric IsBufferInvalid = false;
187e8d8bef9SDimitry Andric return Buffer->getMemBufferRef();
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
getLineTableFilenameID(StringRef Name)1900b57cec5SDimitry Andric unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
1910b57cec5SDimitry Andric auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
1920b57cec5SDimitry Andric if (IterBool.second)
1930b57cec5SDimitry Andric FilenamesByID.push_back(&*IterBool.first);
1940b57cec5SDimitry Andric return IterBool.first->second;
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric /// Add a line note to the line table that indicates that there is a \#line or
1980b57cec5SDimitry Andric /// GNU line marker at the specified FID/Offset location which changes the
1990b57cec5SDimitry Andric /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
2000b57cec5SDimitry Andric /// change the presumed \#include stack. If it is 1, this is a file entry, if
2010b57cec5SDimitry Andric /// it is 2 then this is a file exit. FileKind specifies whether this is a
2020b57cec5SDimitry Andric /// system header or extern C system header.
AddLineNote(FileID FID,unsigned Offset,unsigned LineNo,int FilenameID,unsigned EntryExit,SrcMgr::CharacteristicKind FileKind)2030b57cec5SDimitry Andric void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
2040b57cec5SDimitry Andric int FilenameID, unsigned EntryExit,
2050b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileKind) {
2060b57cec5SDimitry Andric std::vector<LineEntry> &Entries = LineEntries[FID];
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
2090b57cec5SDimitry Andric "Adding line entries out of order!");
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric unsigned IncludeOffset = 0;
212349cc55cSDimitry Andric if (EntryExit == 1) {
213349cc55cSDimitry Andric // Push #include
2140b57cec5SDimitry Andric IncludeOffset = Offset-1;
215349cc55cSDimitry Andric } else {
216349cc55cSDimitry Andric const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
217349cc55cSDimitry Andric if (EntryExit == 2) {
218349cc55cSDimitry Andric // Pop #include
219349cc55cSDimitry Andric assert(PrevEntry && PrevEntry->IncludeOffset &&
220349cc55cSDimitry Andric "PPDirectives should have caught case when popping empty include "
221349cc55cSDimitry Andric "stack");
222349cc55cSDimitry Andric PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
223349cc55cSDimitry Andric }
224349cc55cSDimitry Andric if (PrevEntry) {
2250b57cec5SDimitry Andric IncludeOffset = PrevEntry->IncludeOffset;
226349cc55cSDimitry Andric if (FilenameID == -1) {
227349cc55cSDimitry Andric // An unspecified FilenameID means use the previous (or containing)
228349cc55cSDimitry Andric // filename if available, or the main source file otherwise.
229349cc55cSDimitry Andric FilenameID = PrevEntry->FilenameID;
230349cc55cSDimitry Andric }
231349cc55cSDimitry Andric }
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric
2340b57cec5SDimitry Andric Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
2350b57cec5SDimitry Andric IncludeOffset));
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric /// FindNearestLineEntry - Find the line entry nearest to FID that is before
2390b57cec5SDimitry Andric /// it. If there is no line entry before Offset in FID, return null.
FindNearestLineEntry(FileID FID,unsigned Offset)2400b57cec5SDimitry Andric const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
2410b57cec5SDimitry Andric unsigned Offset) {
2420b57cec5SDimitry Andric const std::vector<LineEntry> &Entries = LineEntries[FID];
2430b57cec5SDimitry Andric assert(!Entries.empty() && "No #line entries for this FID after all!");
2440b57cec5SDimitry Andric
2450b57cec5SDimitry Andric // It is very common for the query to be after the last #line, check this
2460b57cec5SDimitry Andric // first.
2470b57cec5SDimitry Andric if (Entries.back().FileOffset <= Offset)
2480b57cec5SDimitry Andric return &Entries.back();
2490b57cec5SDimitry Andric
2500b57cec5SDimitry Andric // Do a binary search to find the maximal element that is still before Offset.
2510b57cec5SDimitry Andric std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
2520b57cec5SDimitry Andric if (I == Entries.begin())
2530b57cec5SDimitry Andric return nullptr;
2540b57cec5SDimitry Andric return &*--I;
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric
2570b57cec5SDimitry Andric /// Add a new line entry that has already been encoded into
2580b57cec5SDimitry Andric /// the internal representation of the line table.
AddEntry(FileID FID,const std::vector<LineEntry> & Entries)2590b57cec5SDimitry Andric void LineTableInfo::AddEntry(FileID FID,
2600b57cec5SDimitry Andric const std::vector<LineEntry> &Entries) {
2610b57cec5SDimitry Andric LineEntries[FID] = Entries;
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric
2640b57cec5SDimitry Andric /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
getLineTableFilenameID(StringRef Name)2650b57cec5SDimitry Andric unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
2660b57cec5SDimitry Andric return getLineTable().getLineTableFilenameID(Name);
2670b57cec5SDimitry Andric }
2680b57cec5SDimitry Andric
2690b57cec5SDimitry Andric /// AddLineNote - Add a line note to the line table for the FileID and offset
2700b57cec5SDimitry Andric /// specified by Loc. If FilenameID is -1, it is considered to be
2710b57cec5SDimitry Andric /// unspecified.
AddLineNote(SourceLocation Loc,unsigned LineNo,int FilenameID,bool IsFileEntry,bool IsFileExit,SrcMgr::CharacteristicKind FileKind)2720b57cec5SDimitry Andric void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
2730b57cec5SDimitry Andric int FilenameID, bool IsFileEntry,
2740b57cec5SDimitry Andric bool IsFileExit,
2750b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileKind) {
2760b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
2770b57cec5SDimitry Andric
2780b57cec5SDimitry Andric bool Invalid = false;
2790b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
2800b57cec5SDimitry Andric if (!Entry.isFile() || Invalid)
2810b57cec5SDimitry Andric return;
2820b57cec5SDimitry Andric
2830b57cec5SDimitry Andric const SrcMgr::FileInfo &FileInfo = Entry.getFile();
2840b57cec5SDimitry Andric
2850b57cec5SDimitry Andric // Remember that this file has #line directives now if it doesn't already.
2860b57cec5SDimitry Andric const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric (void) getLineTable();
2890b57cec5SDimitry Andric
2900b57cec5SDimitry Andric unsigned EntryExit = 0;
2910b57cec5SDimitry Andric if (IsFileEntry)
2920b57cec5SDimitry Andric EntryExit = 1;
2930b57cec5SDimitry Andric else if (IsFileExit)
2940b57cec5SDimitry Andric EntryExit = 2;
2950b57cec5SDimitry Andric
2960b57cec5SDimitry Andric LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
2970b57cec5SDimitry Andric EntryExit, FileKind);
2980b57cec5SDimitry Andric }
2990b57cec5SDimitry Andric
getLineTable()3000b57cec5SDimitry Andric LineTableInfo &SourceManager::getLineTable() {
3010b57cec5SDimitry Andric if (!LineTable)
3020b57cec5SDimitry Andric LineTable.reset(new LineTableInfo());
3030b57cec5SDimitry Andric return *LineTable;
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric
3060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3070b57cec5SDimitry Andric // Private 'Create' methods.
3080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3090b57cec5SDimitry Andric
SourceManager(DiagnosticsEngine & Diag,FileManager & FileMgr,bool UserFilesAreVolatile)3100b57cec5SDimitry Andric SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
3110b57cec5SDimitry Andric bool UserFilesAreVolatile)
3120b57cec5SDimitry Andric : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
3130b57cec5SDimitry Andric clearIDTables();
3140b57cec5SDimitry Andric Diag.setSourceManager(this);
3150b57cec5SDimitry Andric }
3160b57cec5SDimitry Andric
~SourceManager()3170b57cec5SDimitry Andric SourceManager::~SourceManager() {
3180b57cec5SDimitry Andric // Delete FileEntry objects corresponding to content caches. Since the actual
3190b57cec5SDimitry Andric // content cache objects are bump pointer allocated, we just have to run the
3200b57cec5SDimitry Andric // dtors, but we call the deallocate method for completeness.
3210b57cec5SDimitry Andric for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
3220b57cec5SDimitry Andric if (MemBufferInfos[i]) {
3230b57cec5SDimitry Andric MemBufferInfos[i]->~ContentCache();
3240b57cec5SDimitry Andric ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric }
3275f757f3fSDimitry Andric for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
3280b57cec5SDimitry Andric if (I->second) {
3290b57cec5SDimitry Andric I->second->~ContentCache();
3300b57cec5SDimitry Andric ContentCacheAlloc.Deallocate(I->second);
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric }
3330b57cec5SDimitry Andric }
3340b57cec5SDimitry Andric
clearIDTables()3350b57cec5SDimitry Andric void SourceManager::clearIDTables() {
3360b57cec5SDimitry Andric MainFileID = FileID();
3370b57cec5SDimitry Andric LocalSLocEntryTable.clear();
3380b57cec5SDimitry Andric LoadedSLocEntryTable.clear();
3390b57cec5SDimitry Andric SLocEntryLoaded.clear();
3405f757f3fSDimitry Andric SLocEntryOffsetLoaded.clear();
3410b57cec5SDimitry Andric LastLineNoFileIDQuery = FileID();
3420b57cec5SDimitry Andric LastLineNoContentCache = nullptr;
3430b57cec5SDimitry Andric LastFileIDLookup = FileID();
3440b57cec5SDimitry Andric
3450b57cec5SDimitry Andric if (LineTable)
3460b57cec5SDimitry Andric LineTable->clear();
3470b57cec5SDimitry Andric
3480b57cec5SDimitry Andric // Use up FileID #0 as an invalid expansion.
3490b57cec5SDimitry Andric NextLocalOffset = 0;
3500b57cec5SDimitry Andric CurrentLoadedOffset = MaxLoadedOffset;
3510b57cec5SDimitry Andric createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric
isMainFile(const FileEntry & SourceFile)354e8d8bef9SDimitry Andric bool SourceManager::isMainFile(const FileEntry &SourceFile) {
3555ffd83dbSDimitry Andric assert(MainFileID.isValid() && "expected initialized SourceManager");
356e8d8bef9SDimitry Andric if (auto *FE = getFileEntryForID(MainFileID))
3575ffd83dbSDimitry Andric return FE->getUID() == SourceFile.getUID();
358e8d8bef9SDimitry Andric return false;
3595ffd83dbSDimitry Andric }
3605ffd83dbSDimitry Andric
initializeForReplay(const SourceManager & Old)3610b57cec5SDimitry Andric void SourceManager::initializeForReplay(const SourceManager &Old) {
3620b57cec5SDimitry Andric assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
3630b57cec5SDimitry Andric
3640b57cec5SDimitry Andric auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
3650b57cec5SDimitry Andric auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
3660b57cec5SDimitry Andric Clone->OrigEntry = Cache->OrigEntry;
3670b57cec5SDimitry Andric Clone->ContentsEntry = Cache->ContentsEntry;
3680b57cec5SDimitry Andric Clone->BufferOverridden = Cache->BufferOverridden;
369a7dea167SDimitry Andric Clone->IsFileVolatile = Cache->IsFileVolatile;
3700b57cec5SDimitry Andric Clone->IsTransient = Cache->IsTransient;
371e8d8bef9SDimitry Andric Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
3720b57cec5SDimitry Andric return Clone;
3730b57cec5SDimitry Andric };
3740b57cec5SDimitry Andric
3750b57cec5SDimitry Andric // Ensure all SLocEntries are loaded from the external source.
3760b57cec5SDimitry Andric for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
3770b57cec5SDimitry Andric if (!Old.SLocEntryLoaded[I])
3780b57cec5SDimitry Andric Old.loadSLocEntry(I, nullptr);
3790b57cec5SDimitry Andric
3800b57cec5SDimitry Andric // Inherit any content cache data from the old source manager.
3810b57cec5SDimitry Andric for (auto &FileInfo : Old.FileInfos) {
3820b57cec5SDimitry Andric SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
3830b57cec5SDimitry Andric if (Slot)
3840b57cec5SDimitry Andric continue;
3850b57cec5SDimitry Andric Slot = CloneContentCache(FileInfo.second);
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric
getOrCreateContentCache(FileEntryRef FileEnt,bool isSystemFile)389e8d8bef9SDimitry Andric ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
3900b57cec5SDimitry Andric bool isSystemFile) {
3910b57cec5SDimitry Andric // Do we already have information about this file?
3920b57cec5SDimitry Andric ContentCache *&Entry = FileInfos[FileEnt];
393e8d8bef9SDimitry Andric if (Entry)
394e8d8bef9SDimitry Andric return *Entry;
3950b57cec5SDimitry Andric
3960b57cec5SDimitry Andric // Nope, create a new Cache entry.
3970b57cec5SDimitry Andric Entry = ContentCacheAlloc.Allocate<ContentCache>();
3980b57cec5SDimitry Andric
3990b57cec5SDimitry Andric if (OverriddenFilesInfo) {
4000b57cec5SDimitry Andric // If the file contents are overridden with contents from another file,
4010b57cec5SDimitry Andric // pass that file to ContentCache.
402bdd1243dSDimitry Andric auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
4030b57cec5SDimitry Andric if (overI == OverriddenFilesInfo->OverriddenFiles.end())
4040b57cec5SDimitry Andric new (Entry) ContentCache(FileEnt);
4050b57cec5SDimitry Andric else
4060b57cec5SDimitry Andric new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
4070b57cec5SDimitry Andric : overI->second,
4080b57cec5SDimitry Andric overI->second);
4090b57cec5SDimitry Andric } else {
4100b57cec5SDimitry Andric new (Entry) ContentCache(FileEnt);
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric
413a7dea167SDimitry Andric Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
4140b57cec5SDimitry Andric Entry->IsTransient = FilesAreTransient;
415e8d8bef9SDimitry Andric Entry->BufferOverridden |= FileEnt.isNamedPipe();
4160b57cec5SDimitry Andric
417e8d8bef9SDimitry Andric return *Entry;
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric
4200b57cec5SDimitry Andric /// Create a new ContentCache for the specified memory buffer.
4210b57cec5SDimitry Andric /// This does no caching.
createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buffer)422e8d8bef9SDimitry Andric ContentCache &SourceManager::createMemBufferContentCache(
423e8d8bef9SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer) {
4240b57cec5SDimitry Andric // Add a new ContentCache to the MemBufferInfos list and return it.
4250b57cec5SDimitry Andric ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
4260b57cec5SDimitry Andric new (Entry) ContentCache();
4270b57cec5SDimitry Andric MemBufferInfos.push_back(Entry);
428e8d8bef9SDimitry Andric Entry->setBuffer(std::move(Buffer));
429e8d8bef9SDimitry Andric return *Entry;
4300b57cec5SDimitry Andric }
4310b57cec5SDimitry Andric
loadSLocEntry(unsigned Index,bool * Invalid) const4320b57cec5SDimitry Andric const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
4330b57cec5SDimitry Andric bool *Invalid) const {
4340b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index]);
4350b57cec5SDimitry Andric if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
4360b57cec5SDimitry Andric if (Invalid)
4370b57cec5SDimitry Andric *Invalid = true;
4380b57cec5SDimitry Andric // If the file of the SLocEntry changed we could still have loaded it.
4390b57cec5SDimitry Andric if (!SLocEntryLoaded[Index]) {
4400b57cec5SDimitry Andric // Try to recover; create a SLocEntry so the rest of clang can handle it.
441e8d8bef9SDimitry Andric if (!FakeSLocEntryForRecovery)
442e8d8bef9SDimitry Andric FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
443a7dea167SDimitry Andric 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
444e8d8bef9SDimitry Andric SrcMgr::C_User, "")));
445e8d8bef9SDimitry Andric return *FakeSLocEntryForRecovery;
4460b57cec5SDimitry Andric }
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric
4490b57cec5SDimitry Andric return LoadedSLocEntryTable[Index];
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric
452fe6060f1SDimitry Andric std::pair<int, SourceLocation::UIntTy>
AllocateLoadedSLocEntries(unsigned NumSLocEntries,SourceLocation::UIntTy TotalSize)4530b57cec5SDimitry Andric SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
454fe6060f1SDimitry Andric SourceLocation::UIntTy TotalSize) {
4550b57cec5SDimitry Andric assert(ExternalSLocEntries && "Don't have an external sloc source");
4560b57cec5SDimitry Andric // Make sure we're not about to run out of source locations.
457bdd1243dSDimitry Andric if (CurrentLoadedOffset < TotalSize ||
458bdd1243dSDimitry Andric CurrentLoadedOffset - TotalSize < NextLocalOffset) {
4590b57cec5SDimitry Andric return std::make_pair(0, 0);
460bdd1243dSDimitry Andric }
4610b57cec5SDimitry Andric LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
4620b57cec5SDimitry Andric SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
4635f757f3fSDimitry Andric SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());
4640b57cec5SDimitry Andric CurrentLoadedOffset -= TotalSize;
4655f757f3fSDimitry Andric int BaseID = -int(LoadedSLocEntryTable.size()) - 1;
4665f757f3fSDimitry Andric LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));
4675f757f3fSDimitry Andric return std::make_pair(BaseID, CurrentLoadedOffset);
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a
4710b57cec5SDimitry Andric /// fake, non-empty buffer.
getFakeBufferForRecovery() const472e8d8bef9SDimitry Andric llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
4730b57cec5SDimitry Andric if (!FakeBufferForRecovery)
4740b57cec5SDimitry Andric FakeBufferForRecovery =
4750b57cec5SDimitry Andric llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
4760b57cec5SDimitry Andric
477e8d8bef9SDimitry Andric return *FakeBufferForRecovery;
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric
4800b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a
4810b57cec5SDimitry Andric /// fake content cache.
getFakeContentCacheForRecovery() const482e8d8bef9SDimitry Andric SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
4830b57cec5SDimitry Andric if (!FakeContentCacheForRecovery) {
484a7dea167SDimitry Andric FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
485e8d8bef9SDimitry Andric FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
4860b57cec5SDimitry Andric }
487e8d8bef9SDimitry Andric return *FakeContentCacheForRecovery;
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric /// Returns the previous in-order FileID or an invalid FileID if there
4910b57cec5SDimitry Andric /// is no previous one.
getPreviousFileID(FileID FID) const4920b57cec5SDimitry Andric FileID SourceManager::getPreviousFileID(FileID FID) const {
4930b57cec5SDimitry Andric if (FID.isInvalid())
4940b57cec5SDimitry Andric return FileID();
4950b57cec5SDimitry Andric
4960b57cec5SDimitry Andric int ID = FID.ID;
4970b57cec5SDimitry Andric if (ID == -1)
4980b57cec5SDimitry Andric return FileID();
4990b57cec5SDimitry Andric
5000b57cec5SDimitry Andric if (ID > 0) {
5010b57cec5SDimitry Andric if (ID-1 == 0)
5020b57cec5SDimitry Andric return FileID();
5030b57cec5SDimitry Andric } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
5040b57cec5SDimitry Andric return FileID();
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric
5070b57cec5SDimitry Andric return FileID::get(ID-1);
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric
5100b57cec5SDimitry Andric /// Returns the next in-order FileID or an invalid FileID if there is
5110b57cec5SDimitry Andric /// no next one.
getNextFileID(FileID FID) const5120b57cec5SDimitry Andric FileID SourceManager::getNextFileID(FileID FID) const {
5130b57cec5SDimitry Andric if (FID.isInvalid())
5140b57cec5SDimitry Andric return FileID();
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric int ID = FID.ID;
5170b57cec5SDimitry Andric if (ID > 0) {
5180b57cec5SDimitry Andric if (unsigned(ID+1) >= local_sloc_entry_size())
5190b57cec5SDimitry Andric return FileID();
5200b57cec5SDimitry Andric } else if (ID+1 >= -1) {
5210b57cec5SDimitry Andric return FileID();
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric
5240b57cec5SDimitry Andric return FileID::get(ID+1);
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric
5270b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5280b57cec5SDimitry Andric // Methods to create new FileID's and macro expansions.
5290b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5300b57cec5SDimitry Andric
5315ffd83dbSDimitry Andric /// Create a new FileID that represents the specified file
5325ffd83dbSDimitry Andric /// being \#included from the specified IncludePosition.
createFileID(FileEntryRef SourceFile,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)5335ffd83dbSDimitry Andric FileID SourceManager::createFileID(FileEntryRef SourceFile,
5345ffd83dbSDimitry Andric SourceLocation IncludePos,
5355ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
536fe6060f1SDimitry Andric int LoadedID,
537fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
538e8d8bef9SDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
539e8d8bef9SDimitry Andric isSystem(FileCharacter));
540e8d8bef9SDimitry Andric
541e8d8bef9SDimitry Andric // If this is a named pipe, immediately load the buffer to ensure subsequent
542e8d8bef9SDimitry Andric // calls to ContentCache::getSize() are accurate.
543e8d8bef9SDimitry Andric if (IR.ContentsEntry->isNamedPipe())
544e8d8bef9SDimitry Andric (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
545e8d8bef9SDimitry Andric
546e8d8bef9SDimitry Andric return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
5475ffd83dbSDimitry Andric LoadedID, LoadedOffset);
5485ffd83dbSDimitry Andric }
5495ffd83dbSDimitry Andric
5505ffd83dbSDimitry Andric /// Create a new FileID that represents the specified memory buffer.
5515ffd83dbSDimitry Andric ///
5525ffd83dbSDimitry Andric /// This does no caching of the buffer and takes ownership of the
5535ffd83dbSDimitry 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)5545ffd83dbSDimitry Andric FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
5555ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
556fe6060f1SDimitry Andric int LoadedID,
557fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset,
5585ffd83dbSDimitry Andric SourceLocation IncludeLoc) {
5595ffd83dbSDimitry Andric StringRef Name = Buffer->getBufferIdentifier();
560e8d8bef9SDimitry Andric return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
561e8d8bef9SDimitry Andric IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
5625ffd83dbSDimitry Andric }
5635ffd83dbSDimitry Andric
5645ffd83dbSDimitry Andric /// Create a new FileID that represents the specified memory buffer.
5655ffd83dbSDimitry Andric ///
5665ffd83dbSDimitry Andric /// This does not take ownership of the MemoryBuffer. The memory buffer must
5675ffd83dbSDimitry Andric /// outlive the SourceManager.
createFileID(const llvm::MemoryBufferRef & Buffer,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset,SourceLocation IncludeLoc)568e8d8bef9SDimitry Andric FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
5695ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
570fe6060f1SDimitry Andric int LoadedID,
571fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset,
5725ffd83dbSDimitry Andric SourceLocation IncludeLoc) {
573e8d8bef9SDimitry Andric return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
574e8d8bef9SDimitry Andric LoadedID, LoadedOffset, IncludeLoc);
5755ffd83dbSDimitry Andric }
5765ffd83dbSDimitry Andric
5775ffd83dbSDimitry Andric /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
5785ffd83dbSDimitry Andric /// new FileID for the \p SourceFile.
5795ffd83dbSDimitry Andric FileID
getOrCreateFileID(FileEntryRef SourceFile,SrcMgr::CharacteristicKind FileCharacter)5805f757f3fSDimitry Andric SourceManager::getOrCreateFileID(FileEntryRef SourceFile,
5815ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter) {
5825ffd83dbSDimitry Andric FileID ID = translateFile(SourceFile);
5835ffd83dbSDimitry Andric return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
5845ffd83dbSDimitry Andric FileCharacter);
5855ffd83dbSDimitry Andric }
5865ffd83dbSDimitry Andric
5870b57cec5SDimitry Andric /// createFileID - Create a new FileID for the specified ContentCache and
5880b57cec5SDimitry Andric /// include position. This works regardless of whether the ContentCache
5890b57cec5SDimitry Andric /// corresponds to a file or some other input source.
createFileIDImpl(ContentCache & File,StringRef Filename,SourceLocation IncludePos,SrcMgr::CharacteristicKind FileCharacter,int LoadedID,SourceLocation::UIntTy LoadedOffset)590e8d8bef9SDimitry Andric FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
5910b57cec5SDimitry Andric SourceLocation IncludePos,
5920b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileCharacter,
593fe6060f1SDimitry Andric int LoadedID,
594fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
5950b57cec5SDimitry Andric if (LoadedID < 0) {
5960b57cec5SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID");
5970b57cec5SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2;
5980b57cec5SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
5990b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded");
600a7dea167SDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get(
601a7dea167SDimitry Andric LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
6025f757f3fSDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
6030b57cec5SDimitry Andric return FileID::get(LoadedID);
6040b57cec5SDimitry Andric }
605e8d8bef9SDimitry Andric unsigned FileSize = File.getSize();
6065ffd83dbSDimitry Andric if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
6075ffd83dbSDimitry Andric NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
6085f757f3fSDimitry Andric Diag.Report(IncludePos, diag::err_sloc_space_too_large);
609bdd1243dSDimitry Andric noteSLocAddressSpaceUsage(Diag);
6105ffd83dbSDimitry Andric return FileID();
6115ffd83dbSDimitry Andric }
612a7dea167SDimitry Andric LocalSLocEntryTable.push_back(
613a7dea167SDimitry Andric SLocEntry::get(NextLocalOffset,
614a7dea167SDimitry Andric FileInfo::get(IncludePos, File, FileCharacter, Filename)));
6150b57cec5SDimitry Andric // We do a +1 here because we want a SourceLocation that means "the end of the
6160b57cec5SDimitry Andric // file", e.g. for the "no newline at the end of the file" diagnostic.
6170b57cec5SDimitry Andric NextLocalOffset += FileSize + 1;
6180b57cec5SDimitry Andric
6190b57cec5SDimitry Andric // Set LastFileIDLookup to the newly created file. The next getFileID call is
6200b57cec5SDimitry Andric // almost guaranteed to be from that file.
6210b57cec5SDimitry Andric FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
6220b57cec5SDimitry Andric return LastFileIDLookup = FID;
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric
createMacroArgExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLoc,unsigned Length)62581ad6265SDimitry Andric SourceLocation SourceManager::createMacroArgExpansionLoc(
62681ad6265SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
6270b57cec5SDimitry Andric ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
6280b57cec5SDimitry Andric ExpansionLoc);
62981ad6265SDimitry Andric return createExpansionLocImpl(Info, Length);
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric
createExpansionLoc(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned Length,bool ExpansionIsTokenRange,int LoadedID,SourceLocation::UIntTy LoadedOffset)632fe6060f1SDimitry Andric SourceLocation SourceManager::createExpansionLoc(
633fe6060f1SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
63481ad6265SDimitry Andric SourceLocation ExpansionLocEnd, unsigned Length,
635fe6060f1SDimitry Andric bool ExpansionIsTokenRange, int LoadedID,
636fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
6370b57cec5SDimitry Andric ExpansionInfo Info = ExpansionInfo::create(
6380b57cec5SDimitry Andric SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
63981ad6265SDimitry Andric return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric
createTokenSplitLoc(SourceLocation Spelling,SourceLocation TokenStart,SourceLocation TokenEnd)6420b57cec5SDimitry Andric SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
6430b57cec5SDimitry Andric SourceLocation TokenStart,
6440b57cec5SDimitry Andric SourceLocation TokenEnd) {
6450b57cec5SDimitry Andric assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
6460b57cec5SDimitry Andric "token spans multiple files");
6470b57cec5SDimitry Andric return createExpansionLocImpl(
6480b57cec5SDimitry Andric ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
6490b57cec5SDimitry Andric TokenEnd.getOffset() - TokenStart.getOffset());
6500b57cec5SDimitry Andric }
6510b57cec5SDimitry Andric
6520b57cec5SDimitry Andric SourceLocation
createExpansionLocImpl(const ExpansionInfo & Info,unsigned Length,int LoadedID,SourceLocation::UIntTy LoadedOffset)6530b57cec5SDimitry Andric SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
65481ad6265SDimitry Andric unsigned Length, int LoadedID,
655fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) {
6560b57cec5SDimitry Andric if (LoadedID < 0) {
6570b57cec5SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID");
6580b57cec5SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2;
6590b57cec5SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
6600b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded");
6610b57cec5SDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
6625f757f3fSDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
6630b57cec5SDimitry Andric return SourceLocation::getMacroLoc(LoadedOffset);
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
6665f757f3fSDimitry Andric if (NextLocalOffset + Length + 1 <= NextLocalOffset ||
6675f757f3fSDimitry Andric NextLocalOffset + Length + 1 > CurrentLoadedOffset) {
6685f757f3fSDimitry Andric Diag.Report(SourceLocation(), diag::err_sloc_space_too_large);
6695f757f3fSDimitry Andric // FIXME: call `noteSLocAddressSpaceUsage` to report details to users and
6705f757f3fSDimitry Andric // use a source location from `Info` to point at an error.
6715f757f3fSDimitry Andric // Currently, both cause Clang to run indefinitely, this needs to be fixed.
6725f757f3fSDimitry Andric // FIXME: return an error instead of crashing. Returning invalid source
6735f757f3fSDimitry Andric // locations causes compiler to run indefinitely.
6745f757f3fSDimitry Andric llvm::report_fatal_error("ran out of source locations");
6755f757f3fSDimitry Andric }
6760b57cec5SDimitry Andric // See createFileID for that +1.
67781ad6265SDimitry Andric NextLocalOffset += Length + 1;
67881ad6265SDimitry Andric return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric
681bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(FileEntryRef File)6825f757f3fSDimitry Andric SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) {
6835f757f3fSDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(File);
684e8d8bef9SDimitry Andric return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric
overrideFileContents(FileEntryRef SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)687e8d8bef9SDimitry Andric void SourceManager::overrideFileContents(
6885f757f3fSDimitry Andric FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
6895f757f3fSDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);
6900b57cec5SDimitry Andric
691e8d8bef9SDimitry Andric IR.setBuffer(std::move(Buffer));
692e8d8bef9SDimitry Andric IR.BufferOverridden = true;
6930b57cec5SDimitry Andric
6940b57cec5SDimitry Andric getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric
overrideFileContents(const FileEntry * SourceFile,FileEntryRef NewFile)6970b57cec5SDimitry Andric void SourceManager::overrideFileContents(const FileEntry *SourceFile,
698bdd1243dSDimitry Andric FileEntryRef NewFile) {
699bdd1243dSDimitry Andric assert(SourceFile->getSize() == NewFile.getSize() &&
7000b57cec5SDimitry Andric "Different sizes, use the FileManager to create a virtual file with "
7010b57cec5SDimitry Andric "the correct size");
7025f757f3fSDimitry Andric assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&
7030b57cec5SDimitry Andric "This function should be called at the initialization stage, before "
7040b57cec5SDimitry Andric "any parsing occurs.");
705bdd1243dSDimitry Andric // FileEntryRef is not default-constructible.
706bdd1243dSDimitry Andric auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
707bdd1243dSDimitry Andric std::make_pair(SourceFile, NewFile));
708bdd1243dSDimitry Andric if (!Pair.second)
709bdd1243dSDimitry Andric Pair.first->second = NewFile;
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric
712bdd1243dSDimitry Andric OptionalFileEntryRef
bypassFileContentsOverride(FileEntryRef File)713e8d8bef9SDimitry Andric SourceManager::bypassFileContentsOverride(FileEntryRef File) {
714e8d8bef9SDimitry Andric assert(isFileOverridden(&File.getFileEntry()));
715bdd1243dSDimitry Andric OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
7160b57cec5SDimitry Andric
717a7dea167SDimitry Andric // If the file can't be found in the FS, give up.
718a7dea167SDimitry Andric if (!BypassFile)
719bdd1243dSDimitry Andric return std::nullopt;
7200b57cec5SDimitry Andric
721e8d8bef9SDimitry Andric (void)getOrCreateContentCache(*BypassFile);
722e8d8bef9SDimitry Andric return BypassFile;
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric
setFileIsTransient(FileEntryRef File)7255f757f3fSDimitry Andric void SourceManager::setFileIsTransient(FileEntryRef File) {
7265f757f3fSDimitry Andric getOrCreateContentCache(File).IsTransient = true;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric
729bdd1243dSDimitry Andric std::optional<StringRef>
getNonBuiltinFilenameForID(FileID FID) const730e8d8bef9SDimitry Andric SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
731e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
732e8d8bef9SDimitry Andric if (Entry->getFile().getContentCache().OrigEntry)
733e8d8bef9SDimitry Andric return Entry->getFile().getName();
734bdd1243dSDimitry Andric return std::nullopt;
7355ffd83dbSDimitry Andric }
7365ffd83dbSDimitry Andric
getBufferData(FileID FID,bool * Invalid) const7370b57cec5SDimitry Andric StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
738e8d8bef9SDimitry Andric auto B = getBufferDataOrNone(FID);
7390b57cec5SDimitry Andric if (Invalid)
740e8d8bef9SDimitry Andric *Invalid = !B;
741e8d8bef9SDimitry Andric return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
7420b57cec5SDimitry Andric }
7430b57cec5SDimitry Andric
744bdd1243dSDimitry Andric std::optional<StringRef>
getBufferDataIfLoaded(FileID FID) const745e8d8bef9SDimitry Andric SourceManager::getBufferDataIfLoaded(FileID FID) const {
746e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
747e8d8bef9SDimitry Andric return Entry->getFile().getContentCache().getBufferDataIfLoaded();
748bdd1243dSDimitry Andric return std::nullopt;
749e8d8bef9SDimitry Andric }
7500b57cec5SDimitry Andric
getBufferDataOrNone(FileID FID) const751bdd1243dSDimitry Andric std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
752e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
753e8d8bef9SDimitry Andric if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
754e8d8bef9SDimitry Andric Diag, getFileManager(), SourceLocation()))
755e8d8bef9SDimitry Andric return B->getBuffer();
756bdd1243dSDimitry Andric return std::nullopt;
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric
7590b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7600b57cec5SDimitry Andric // SourceLocation manipulation methods.
7610b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7620b57cec5SDimitry Andric
7630b57cec5SDimitry Andric /// Return the FileID for a SourceLocation.
7640b57cec5SDimitry Andric ///
7650b57cec5SDimitry Andric /// This is the cache-miss path of getFileID. Not as hot as that function, but
7660b57cec5SDimitry Andric /// still very important. It is responsible for finding the entry in the
7670b57cec5SDimitry Andric /// SLocEntry tables that contains the specified location.
getFileIDSlow(SourceLocation::UIntTy SLocOffset) const768fe6060f1SDimitry Andric FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
7690b57cec5SDimitry Andric if (!SLocOffset)
7700b57cec5SDimitry Andric return FileID::get(0);
7710b57cec5SDimitry Andric
7720b57cec5SDimitry Andric // Now it is time to search for the correct file. See where the SLocOffset
7730b57cec5SDimitry Andric // sits in the global view and consult local or loaded buffers for it.
7740b57cec5SDimitry Andric if (SLocOffset < NextLocalOffset)
7750b57cec5SDimitry Andric return getFileIDLocal(SLocOffset);
7760b57cec5SDimitry Andric return getFileIDLoaded(SLocOffset);
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric
7790b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a low offset.
7800b57cec5SDimitry Andric ///
7810b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a local buffer, not a
7820b57cec5SDimitry Andric /// loaded one.
getFileIDLocal(SourceLocation::UIntTy SLocOffset) const783fe6060f1SDimitry Andric FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
7840b57cec5SDimitry Andric assert(SLocOffset < NextLocalOffset && "Bad function choice");
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric // After the first and second level caches, I see two common sorts of
7870b57cec5SDimitry Andric // behavior: 1) a lot of searched FileID's are "near" the cached file
7880b57cec5SDimitry Andric // location or are "near" the cached expansion location. 2) others are just
7890b57cec5SDimitry Andric // completely random and may be a very long way away.
7900b57cec5SDimitry Andric //
7910b57cec5SDimitry Andric // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
7920b57cec5SDimitry Andric // then we fall back to a less cache efficient, but more scalable, binary
7930b57cec5SDimitry Andric // search to find the location.
7940b57cec5SDimitry Andric
7950b57cec5SDimitry Andric // See if this is near the file point - worst case we start scanning from the
7960b57cec5SDimitry Andric // most newly created FileID.
7970b57cec5SDimitry Andric
798bdd1243dSDimitry Andric // LessIndex - This is the lower bound of the range that we're searching.
799bdd1243dSDimitry Andric // We know that the offset corresponding to the FileID is less than
800bdd1243dSDimitry Andric // SLocOffset.
801bdd1243dSDimitry Andric unsigned LessIndex = 0;
802bdd1243dSDimitry Andric // upper bound of the search range.
803bdd1243dSDimitry Andric unsigned GreaterIndex = LocalSLocEntryTable.size();
804bdd1243dSDimitry Andric if (LastFileIDLookup.ID >= 0) {
805bdd1243dSDimitry Andric // Use the LastFileIDLookup to prune the search space.
806bdd1243dSDimitry Andric if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
807bdd1243dSDimitry Andric LessIndex = LastFileIDLookup.ID;
808bdd1243dSDimitry Andric else
809bdd1243dSDimitry Andric GreaterIndex = LastFileIDLookup.ID;
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric
812bdd1243dSDimitry Andric // Find the FileID that contains this.
8130b57cec5SDimitry Andric unsigned NumProbes = 0;
8140b57cec5SDimitry Andric while (true) {
815bdd1243dSDimitry Andric --GreaterIndex;
816bdd1243dSDimitry Andric assert(GreaterIndex < LocalSLocEntryTable.size());
817bdd1243dSDimitry Andric if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
818bdd1243dSDimitry Andric FileID Res = FileID::get(int(GreaterIndex));
8195ffd83dbSDimitry Andric // Remember it. We have good locality across FileID lookups.
8200b57cec5SDimitry Andric LastFileIDLookup = Res;
8210b57cec5SDimitry Andric NumLinearScans += NumProbes+1;
8220b57cec5SDimitry Andric return Res;
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric if (++NumProbes == 8)
8250b57cec5SDimitry Andric break;
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric
8280b57cec5SDimitry Andric NumProbes = 0;
8290b57cec5SDimitry Andric while (true) {
8300b57cec5SDimitry Andric unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
831fe6060f1SDimitry Andric SourceLocation::UIntTy MidOffset =
832fe6060f1SDimitry Andric getLocalSLocEntry(MiddleIndex).getOffset();
8330b57cec5SDimitry Andric
8340b57cec5SDimitry Andric ++NumProbes;
8350b57cec5SDimitry Andric
8360b57cec5SDimitry Andric // If the offset of the midpoint is too large, chop the high side of the
8370b57cec5SDimitry Andric // range to the midpoint.
8380b57cec5SDimitry Andric if (MidOffset > SLocOffset) {
8390b57cec5SDimitry Andric GreaterIndex = MiddleIndex;
8400b57cec5SDimitry Andric continue;
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric
8430b57cec5SDimitry Andric // If the middle index contains the value, succeed and return.
8445ffd83dbSDimitry Andric if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
8455ffd83dbSDimitry Andric SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
8460b57cec5SDimitry Andric FileID Res = FileID::get(MiddleIndex);
8470b57cec5SDimitry Andric
8485ffd83dbSDimitry Andric // Remember it. We have good locality across FileID lookups.
8490b57cec5SDimitry Andric LastFileIDLookup = Res;
8500b57cec5SDimitry Andric NumBinaryProbes += NumProbes;
8510b57cec5SDimitry Andric return Res;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric
8540b57cec5SDimitry Andric // Otherwise, move the low-side up to the middle index.
8550b57cec5SDimitry Andric LessIndex = MiddleIndex;
8560b57cec5SDimitry Andric }
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric
8590b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a high offset.
8600b57cec5SDimitry Andric ///
8610b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a loaded buffer, not a
8620b57cec5SDimitry Andric /// local one.
getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const863fe6060f1SDimitry Andric FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
8640b57cec5SDimitry Andric if (SLocOffset < CurrentLoadedOffset) {
8650b57cec5SDimitry Andric assert(0 && "Invalid SLocOffset or bad function choice");
8660b57cec5SDimitry Andric return FileID();
8670b57cec5SDimitry Andric }
8680b57cec5SDimitry Andric
8695f757f3fSDimitry Andric return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric
8720b57cec5SDimitry Andric SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const8730b57cec5SDimitry Andric getExpansionLocSlowCase(SourceLocation Loc) const {
8740b57cec5SDimitry Andric do {
8750b57cec5SDimitry Andric // Note: If Loc indicates an offset into a token that came from a macro
8760b57cec5SDimitry Andric // expansion (e.g. the 5th character of the token) we do not want to add
8770b57cec5SDimitry Andric // this offset when going to the expansion location. The expansion
8780b57cec5SDimitry Andric // location is the macro invocation, which the offset has nothing to do
8790b57cec5SDimitry Andric // with. This is unlike when we get the spelling loc, because the offset
8800b57cec5SDimitry Andric // directly correspond to the token whose spelling we're inspecting.
8810b57cec5SDimitry Andric Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
8820b57cec5SDimitry Andric } while (!Loc.isFileID());
8830b57cec5SDimitry Andric
8840b57cec5SDimitry Andric return Loc;
8850b57cec5SDimitry Andric }
8860b57cec5SDimitry Andric
getSpellingLocSlowCase(SourceLocation Loc) const8870b57cec5SDimitry Andric SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
8880b57cec5SDimitry Andric do {
8890b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
8900b57cec5SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
8910b57cec5SDimitry Andric Loc = Loc.getLocWithOffset(LocInfo.second);
8920b57cec5SDimitry Andric } while (!Loc.isFileID());
8930b57cec5SDimitry Andric return Loc;
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric
getFileLocSlowCase(SourceLocation Loc) const8960b57cec5SDimitry Andric SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
8970b57cec5SDimitry Andric do {
8980b57cec5SDimitry Andric if (isMacroArgExpansion(Loc))
8990b57cec5SDimitry Andric Loc = getImmediateSpellingLoc(Loc);
9000b57cec5SDimitry Andric else
9010b57cec5SDimitry Andric Loc = getImmediateExpansionRange(Loc).getBegin();
9020b57cec5SDimitry Andric } while (!Loc.isFileID());
9030b57cec5SDimitry Andric return Loc;
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric
9060b57cec5SDimitry Andric
9070b57cec5SDimitry Andric std::pair<FileID, unsigned>
getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry * E) const9080b57cec5SDimitry Andric SourceManager::getDecomposedExpansionLocSlowCase(
9090b57cec5SDimitry Andric const SrcMgr::SLocEntry *E) const {
9100b57cec5SDimitry Andric // If this is an expansion record, walk through all the expansion points.
9110b57cec5SDimitry Andric FileID FID;
9120b57cec5SDimitry Andric SourceLocation Loc;
9130b57cec5SDimitry Andric unsigned Offset;
9140b57cec5SDimitry Andric do {
9150b57cec5SDimitry Andric Loc = E->getExpansion().getExpansionLocStart();
9160b57cec5SDimitry Andric
9170b57cec5SDimitry Andric FID = getFileID(Loc);
9180b57cec5SDimitry Andric E = &getSLocEntry(FID);
9190b57cec5SDimitry Andric Offset = Loc.getOffset()-E->getOffset();
9200b57cec5SDimitry Andric } while (!Loc.isFileID());
9210b57cec5SDimitry Andric
9220b57cec5SDimitry Andric return std::make_pair(FID, Offset);
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric
9250b57cec5SDimitry Andric std::pair<FileID, unsigned>
getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry * E,unsigned Offset) const9260b57cec5SDimitry Andric SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
9270b57cec5SDimitry Andric unsigned Offset) const {
9280b57cec5SDimitry Andric // If this is an expansion record, walk through all the expansion points.
9290b57cec5SDimitry Andric FileID FID;
9300b57cec5SDimitry Andric SourceLocation Loc;
9310b57cec5SDimitry Andric do {
9320b57cec5SDimitry Andric Loc = E->getExpansion().getSpellingLoc();
9330b57cec5SDimitry Andric Loc = Loc.getLocWithOffset(Offset);
9340b57cec5SDimitry Andric
9350b57cec5SDimitry Andric FID = getFileID(Loc);
9360b57cec5SDimitry Andric E = &getSLocEntry(FID);
9370b57cec5SDimitry Andric Offset = Loc.getOffset()-E->getOffset();
9380b57cec5SDimitry Andric } while (!Loc.isFileID());
9390b57cec5SDimitry Andric
9400b57cec5SDimitry Andric return std::make_pair(FID, Offset);
9410b57cec5SDimitry Andric }
9420b57cec5SDimitry Andric
9430b57cec5SDimitry Andric /// getImmediateSpellingLoc - Given a SourceLocation object, return the
9440b57cec5SDimitry Andric /// spelling location referenced by the ID. This is the first level down
9450b57cec5SDimitry Andric /// towards the place where the characters that make up the lexed token can be
9460b57cec5SDimitry Andric /// found. This should not generally be used by clients.
getImmediateSpellingLoc(SourceLocation Loc) const9470b57cec5SDimitry Andric SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
9480b57cec5SDimitry Andric if (Loc.isFileID()) return Loc;
9490b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
9500b57cec5SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
9510b57cec5SDimitry Andric return Loc.getLocWithOffset(LocInfo.second);
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric
9545ffd83dbSDimitry Andric /// Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc) const9555ffd83dbSDimitry Andric StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
9565f757f3fSDimitry Andric if (OptionalFileEntryRef F = getFileEntryRefForID(getFileID(SpellingLoc)))
9575ffd83dbSDimitry Andric return F->getName();
9585ffd83dbSDimitry Andric return StringRef();
9595ffd83dbSDimitry Andric }
9605ffd83dbSDimitry Andric
9610b57cec5SDimitry Andric /// getImmediateExpansionRange - Loc is required to be an expansion location.
9620b57cec5SDimitry Andric /// Return the start/end of the expansion information.
9630b57cec5SDimitry Andric CharSourceRange
getImmediateExpansionRange(SourceLocation Loc) const9640b57cec5SDimitry Andric SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
9650b57cec5SDimitry Andric assert(Loc.isMacroID() && "Not a macro expansion loc!");
9660b57cec5SDimitry Andric const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
9670b57cec5SDimitry Andric return Expansion.getExpansionLocRange();
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric
getTopMacroCallerLoc(SourceLocation Loc) const9700b57cec5SDimitry Andric SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
9710b57cec5SDimitry Andric while (isMacroArgExpansion(Loc))
9720b57cec5SDimitry Andric Loc = getImmediateSpellingLoc(Loc);
9730b57cec5SDimitry Andric return Loc;
9740b57cec5SDimitry Andric }
9750b57cec5SDimitry Andric
9760b57cec5SDimitry Andric /// getExpansionRange - Given a SourceLocation object, return the range of
9770b57cec5SDimitry Andric /// tokens covered by the expansion in the ultimate file.
getExpansionRange(SourceLocation Loc) const9780b57cec5SDimitry Andric CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
9790b57cec5SDimitry Andric if (Loc.isFileID())
9800b57cec5SDimitry Andric return CharSourceRange(SourceRange(Loc, Loc), true);
9810b57cec5SDimitry Andric
9820b57cec5SDimitry Andric CharSourceRange Res = getImmediateExpansionRange(Loc);
9830b57cec5SDimitry Andric
9840b57cec5SDimitry Andric // Fully resolve the start and end locations to their ultimate expansion
9850b57cec5SDimitry Andric // points.
9860b57cec5SDimitry Andric while (!Res.getBegin().isFileID())
9870b57cec5SDimitry Andric Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
9880b57cec5SDimitry Andric while (!Res.getEnd().isFileID()) {
9890b57cec5SDimitry Andric CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
9900b57cec5SDimitry Andric Res.setEnd(EndRange.getEnd());
9910b57cec5SDimitry Andric Res.setTokenRange(EndRange.isTokenRange());
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric return Res;
9940b57cec5SDimitry Andric }
9950b57cec5SDimitry Andric
isMacroArgExpansion(SourceLocation Loc,SourceLocation * StartLoc) const9960b57cec5SDimitry Andric bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
9970b57cec5SDimitry Andric SourceLocation *StartLoc) const {
9980b57cec5SDimitry Andric if (!Loc.isMacroID()) return false;
9990b57cec5SDimitry Andric
10000b57cec5SDimitry Andric FileID FID = getFileID(Loc);
10010b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
10020b57cec5SDimitry Andric if (!Expansion.isMacroArgExpansion()) return false;
10030b57cec5SDimitry Andric
10040b57cec5SDimitry Andric if (StartLoc)
10050b57cec5SDimitry Andric *StartLoc = Expansion.getExpansionLocStart();
10060b57cec5SDimitry Andric return true;
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric
isMacroBodyExpansion(SourceLocation Loc) const10090b57cec5SDimitry Andric bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
10100b57cec5SDimitry Andric if (!Loc.isMacroID()) return false;
10110b57cec5SDimitry Andric
10120b57cec5SDimitry Andric FileID FID = getFileID(Loc);
10130b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
10140b57cec5SDimitry Andric return Expansion.isMacroBodyExpansion();
10150b57cec5SDimitry Andric }
10160b57cec5SDimitry Andric
isAtStartOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroBegin) const10170b57cec5SDimitry Andric bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
10180b57cec5SDimitry Andric SourceLocation *MacroBegin) const {
10190b57cec5SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
10200b57cec5SDimitry Andric
10210b57cec5SDimitry Andric std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
10220b57cec5SDimitry Andric if (DecompLoc.second > 0)
10230b57cec5SDimitry Andric return false; // Does not point at the start of expansion range.
10240b57cec5SDimitry Andric
10250b57cec5SDimitry Andric bool Invalid = false;
10260b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo =
10270b57cec5SDimitry Andric getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
10280b57cec5SDimitry Andric if (Invalid)
10290b57cec5SDimitry Andric return false;
10300b57cec5SDimitry Andric SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
10310b57cec5SDimitry Andric
10320b57cec5SDimitry Andric if (ExpInfo.isMacroArgExpansion()) {
10330b57cec5SDimitry Andric // For macro argument expansions, check if the previous FileID is part of
10340b57cec5SDimitry Andric // the same argument expansion, in which case this Loc is not at the
10350b57cec5SDimitry Andric // beginning of the expansion.
10360b57cec5SDimitry Andric FileID PrevFID = getPreviousFileID(DecompLoc.first);
10370b57cec5SDimitry Andric if (!PrevFID.isInvalid()) {
10380b57cec5SDimitry Andric const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
10390b57cec5SDimitry Andric if (Invalid)
10400b57cec5SDimitry Andric return false;
10410b57cec5SDimitry Andric if (PrevEntry.isExpansion() &&
10420b57cec5SDimitry Andric PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
10430b57cec5SDimitry Andric return false;
10440b57cec5SDimitry Andric }
10450b57cec5SDimitry Andric }
10460b57cec5SDimitry Andric
10470b57cec5SDimitry Andric if (MacroBegin)
10480b57cec5SDimitry Andric *MacroBegin = ExpLoc;
10490b57cec5SDimitry Andric return true;
10500b57cec5SDimitry Andric }
10510b57cec5SDimitry Andric
isAtEndOfImmediateMacroExpansion(SourceLocation Loc,SourceLocation * MacroEnd) const10520b57cec5SDimitry Andric bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
10530b57cec5SDimitry Andric SourceLocation *MacroEnd) const {
10540b57cec5SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
10550b57cec5SDimitry Andric
10560b57cec5SDimitry Andric FileID FID = getFileID(Loc);
10570b57cec5SDimitry Andric SourceLocation NextLoc = Loc.getLocWithOffset(1);
10580b57cec5SDimitry Andric if (isInFileID(NextLoc, FID))
10590b57cec5SDimitry Andric return false; // Does not point at the end of expansion range.
10600b57cec5SDimitry Andric
10610b57cec5SDimitry Andric bool Invalid = false;
10620b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo =
10630b57cec5SDimitry Andric getSLocEntry(FID, &Invalid).getExpansion();
10640b57cec5SDimitry Andric if (Invalid)
10650b57cec5SDimitry Andric return false;
10660b57cec5SDimitry Andric
10670b57cec5SDimitry Andric if (ExpInfo.isMacroArgExpansion()) {
10680b57cec5SDimitry Andric // For macro argument expansions, check if the next FileID is part of the
10690b57cec5SDimitry Andric // same argument expansion, in which case this Loc is not at the end of the
10700b57cec5SDimitry Andric // expansion.
10710b57cec5SDimitry Andric FileID NextFID = getNextFileID(FID);
10720b57cec5SDimitry Andric if (!NextFID.isInvalid()) {
10730b57cec5SDimitry Andric const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
10740b57cec5SDimitry Andric if (Invalid)
10750b57cec5SDimitry Andric return false;
10760b57cec5SDimitry Andric if (NextEntry.isExpansion() &&
10770b57cec5SDimitry Andric NextEntry.getExpansion().getExpansionLocStart() ==
10780b57cec5SDimitry Andric ExpInfo.getExpansionLocStart())
10790b57cec5SDimitry Andric return false;
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric
10830b57cec5SDimitry Andric if (MacroEnd)
10840b57cec5SDimitry Andric *MacroEnd = ExpInfo.getExpansionLocEnd();
10850b57cec5SDimitry Andric return true;
10860b57cec5SDimitry Andric }
10870b57cec5SDimitry Andric
10880b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10890b57cec5SDimitry Andric // Queries about the code at a SourceLocation.
10900b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10910b57cec5SDimitry Andric
10920b57cec5SDimitry Andric /// getCharacterData - Return a pointer to the start of the specified location
10930b57cec5SDimitry Andric /// in the appropriate MemoryBuffer.
getCharacterData(SourceLocation SL,bool * Invalid) const10940b57cec5SDimitry Andric const char *SourceManager::getCharacterData(SourceLocation SL,
10950b57cec5SDimitry Andric bool *Invalid) const {
10960b57cec5SDimitry Andric // Note that this is a hot function in the getSpelling() path, which is
10970b57cec5SDimitry Andric // heavily used by -E mode.
10980b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
10990b57cec5SDimitry Andric
11000b57cec5SDimitry Andric // Note that calling 'getBuffer()' may lazily page in a source file.
11010b57cec5SDimitry Andric bool CharDataInvalid = false;
11020b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
11030b57cec5SDimitry Andric if (CharDataInvalid || !Entry.isFile()) {
11040b57cec5SDimitry Andric if (Invalid)
11050b57cec5SDimitry Andric *Invalid = true;
11060b57cec5SDimitry Andric
11070b57cec5SDimitry Andric return "<<<<INVALID BUFFER>>>>";
11080b57cec5SDimitry Andric }
1109bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1110e8d8bef9SDimitry Andric Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1111e8d8bef9SDimitry Andric SourceLocation());
11120b57cec5SDimitry Andric if (Invalid)
1113e8d8bef9SDimitry Andric *Invalid = !Buffer;
1114e8d8bef9SDimitry Andric return Buffer ? Buffer->getBufferStart() + LocInfo.second
1115e8d8bef9SDimitry Andric : "<<<<INVALID BUFFER>>>>";
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric
11180b57cec5SDimitry Andric /// getColumnNumber - Return the column # for the specified file position.
11190b57cec5SDimitry Andric /// this is significantly cheaper to compute than the line number.
getColumnNumber(FileID FID,unsigned FilePos,bool * Invalid) const11200b57cec5SDimitry Andric unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
11210b57cec5SDimitry Andric bool *Invalid) const {
1122bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
11230b57cec5SDimitry Andric if (Invalid)
1124e8d8bef9SDimitry Andric *Invalid = !MemBuf;
11250b57cec5SDimitry Andric
1126e8d8bef9SDimitry Andric if (!MemBuf)
11270b57cec5SDimitry Andric return 1;
11280b57cec5SDimitry Andric
11290b57cec5SDimitry Andric // It is okay to request a position just past the end of the buffer.
11300b57cec5SDimitry Andric if (FilePos > MemBuf->getBufferSize()) {
11310b57cec5SDimitry Andric if (Invalid)
11320b57cec5SDimitry Andric *Invalid = true;
11330b57cec5SDimitry Andric return 1;
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric
11360b57cec5SDimitry Andric const char *Buf = MemBuf->getBufferStart();
11370b57cec5SDimitry Andric // See if we just calculated the line number for this FilePos and can use
11380b57cec5SDimitry Andric // that to lookup the start of the line instead of searching for it.
1139e8d8bef9SDimitry Andric if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1140e8d8bef9SDimitry Andric LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1141e8d8bef9SDimitry Andric const unsigned *SourceLineCache =
1142e8d8bef9SDimitry Andric LastLineNoContentCache->SourceLineCache.begin();
11430b57cec5SDimitry Andric unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
11440b57cec5SDimitry Andric unsigned LineEnd = SourceLineCache[LastLineNoResult];
11450b57cec5SDimitry Andric if (FilePos >= LineStart && FilePos < LineEnd) {
11460b57cec5SDimitry Andric // LineEnd is the LineStart of the next line.
11470b57cec5SDimitry Andric // A line ends with separator LF or CR+LF on Windows.
11480b57cec5SDimitry Andric // FilePos might point to the last separator,
11490b57cec5SDimitry Andric // but we need a column number at most 1 + the last column.
11500b57cec5SDimitry Andric if (FilePos + 1 == LineEnd && FilePos > LineStart) {
11510b57cec5SDimitry Andric if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
11520b57cec5SDimitry Andric --FilePos;
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric return FilePos - LineStart + 1;
11550b57cec5SDimitry Andric }
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric
11580b57cec5SDimitry Andric unsigned LineStart = FilePos;
11590b57cec5SDimitry Andric while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
11600b57cec5SDimitry Andric --LineStart;
11610b57cec5SDimitry Andric return FilePos-LineStart+1;
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric
11640b57cec5SDimitry Andric // isInvalid - Return the result of calling loc.isInvalid(), and
11650b57cec5SDimitry Andric // if Invalid is not null, set its value to same.
11660b57cec5SDimitry Andric template<typename LocType>
isInvalid(LocType Loc,bool * Invalid)11670b57cec5SDimitry Andric static bool isInvalid(LocType Loc, bool *Invalid) {
11680b57cec5SDimitry Andric bool MyInvalid = Loc.isInvalid();
11690b57cec5SDimitry Andric if (Invalid)
11700b57cec5SDimitry Andric *Invalid = MyInvalid;
11710b57cec5SDimitry Andric return MyInvalid;
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric
getSpellingColumnNumber(SourceLocation Loc,bool * Invalid) const11740b57cec5SDimitry Andric unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
11750b57cec5SDimitry Andric bool *Invalid) const {
11760b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
11770b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
11780b57cec5SDimitry Andric return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric
getExpansionColumnNumber(SourceLocation Loc,bool * Invalid) const11810b57cec5SDimitry Andric unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
11820b57cec5SDimitry Andric bool *Invalid) const {
11830b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
11840b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
11850b57cec5SDimitry Andric return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric
getPresumedColumnNumber(SourceLocation Loc,bool * Invalid) const11880b57cec5SDimitry Andric unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
11890b57cec5SDimitry Andric bool *Invalid) const {
11900b57cec5SDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc);
11910b57cec5SDimitry Andric if (isInvalid(PLoc, Invalid)) return 0;
11920b57cec5SDimitry Andric return PLoc.getColumn();
11930b57cec5SDimitry Andric }
11940b57cec5SDimitry Andric
1195fe6060f1SDimitry Andric // Check if mutli-byte word x has bytes between m and n, included. This may also
1196fe6060f1SDimitry Andric // catch bytes equal to n + 1.
1197fe6060f1SDimitry Andric // The returned value holds a 0x80 at each byte position that holds a match.
1198fe6060f1SDimitry Andric // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1199fe6060f1SDimitry Andric template <class T>
likelyhasbetween(T x,unsigned char m,unsigned char n)1200fe6060f1SDimitry Andric static constexpr inline T likelyhasbetween(T x, unsigned char m,
1201fe6060f1SDimitry Andric unsigned char n) {
1202fe6060f1SDimitry Andric return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1203fe6060f1SDimitry Andric ((x & ~static_cast<T>(0) / 255 * 127) +
1204fe6060f1SDimitry Andric (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1205fe6060f1SDimitry Andric ~static_cast<T>(0) / 255 * 128;
1206fe6060f1SDimitry Andric }
12070b57cec5SDimitry Andric
get(llvm::MemoryBufferRef Buffer,llvm::BumpPtrAllocator & Alloc)1208e8d8bef9SDimitry Andric LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1209e8d8bef9SDimitry Andric llvm::BumpPtrAllocator &Alloc) {
1210fe6060f1SDimitry Andric
12110b57cec5SDimitry Andric // Find the file offsets of all of the *physical* source lines. This does
12120b57cec5SDimitry Andric // not look at trigraphs, escaped newlines, or anything else tricky.
12130b57cec5SDimitry Andric SmallVector<unsigned, 256> LineOffsets;
12140b57cec5SDimitry Andric
12150b57cec5SDimitry Andric // Line #1 starts at char 0.
12160b57cec5SDimitry Andric LineOffsets.push_back(0);
12170b57cec5SDimitry Andric
1218bdd1243dSDimitry Andric const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();
1219e8d8bef9SDimitry Andric const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1220bdd1243dSDimitry Andric const unsigned char *Buf = Start;
1221fe6060f1SDimitry Andric
1222fe6060f1SDimitry Andric uint64_t Word;
1223fe6060f1SDimitry Andric
1224fe6060f1SDimitry Andric // scan sizeof(Word) bytes at a time for new lines.
1225fe6060f1SDimitry Andric // This is much faster than scanning each byte independently.
1226bdd1243dSDimitry Andric if ((unsigned long)(End - Start) > sizeof(Word)) {
1227fe6060f1SDimitry Andric do {
12285f757f3fSDimitry Andric Word = llvm::support::endian::read64(Buf, llvm::endianness::little);
1229fe6060f1SDimitry Andric // no new line => jump over sizeof(Word) bytes.
1230fe6060f1SDimitry Andric auto Mask = likelyhasbetween(Word, '\n', '\r');
1231fe6060f1SDimitry Andric if (!Mask) {
1232bdd1243dSDimitry Andric Buf += sizeof(Word);
1233fe6060f1SDimitry Andric continue;
1234fe6060f1SDimitry Andric }
1235fe6060f1SDimitry Andric
1236fe6060f1SDimitry Andric // At that point, Mask contains 0x80 set at each byte that holds a value
1237fe6060f1SDimitry Andric // in [\n, \r + 1 [
1238fe6060f1SDimitry Andric
1239fe6060f1SDimitry Andric // Scan for the next newline - it's very likely there's one.
124006c3fb27SDimitry Andric unsigned N = llvm::countr_zero(Mask) - 7; // -7 because 0x80 is the marker
1241fe6060f1SDimitry Andric Word >>= N;
1242bdd1243dSDimitry Andric Buf += N / 8 + 1;
1243fe6060f1SDimitry Andric unsigned char Byte = Word;
1244bdd1243dSDimitry Andric switch (Byte) {
1245bdd1243dSDimitry Andric case '\r':
1246fe6060f1SDimitry Andric // If this is \r\n, skip both characters.
1247bdd1243dSDimitry Andric if (*Buf == '\n') {
1248bdd1243dSDimitry Andric ++Buf;
1249fe6060f1SDimitry Andric }
125006c3fb27SDimitry Andric [[fallthrough]];
1251bdd1243dSDimitry Andric case '\n':
1252bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start);
1253bdd1243dSDimitry Andric };
1254bdd1243dSDimitry Andric } while (Buf < End - sizeof(Word) - 1);
1255fe6060f1SDimitry Andric }
1256fe6060f1SDimitry Andric
1257fe6060f1SDimitry Andric // Handle tail using a regular check.
1258bdd1243dSDimitry Andric while (Buf < End) {
1259bdd1243dSDimitry Andric if (*Buf == '\n') {
1260bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start + 1);
1261bdd1243dSDimitry Andric } else if (*Buf == '\r') {
12620b57cec5SDimitry Andric // If this is \r\n, skip both characters.
1263bdd1243dSDimitry Andric if (Buf + 1 < End && Buf[1] == '\n') {
1264bdd1243dSDimitry Andric ++Buf;
12650b57cec5SDimitry Andric }
1266bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start + 1);
1267bdd1243dSDimitry Andric }
1268bdd1243dSDimitry Andric ++Buf;
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric
1271e8d8bef9SDimitry Andric return LineOffsetMapping(LineOffsets, Alloc);
1272e8d8bef9SDimitry Andric }
1273e8d8bef9SDimitry Andric
LineOffsetMapping(ArrayRef<unsigned> LineOffsets,llvm::BumpPtrAllocator & Alloc)1274e8d8bef9SDimitry Andric LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1275e8d8bef9SDimitry Andric llvm::BumpPtrAllocator &Alloc)
1276e8d8bef9SDimitry Andric : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1277e8d8bef9SDimitry Andric Storage[0] = LineOffsets.size();
1278e8d8bef9SDimitry Andric std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric
12810b57cec5SDimitry Andric /// getLineNumber - Given a SourceLocation, return the spelling line number
12820b57cec5SDimitry Andric /// for the position indicated. This requires building and caching a table of
12830b57cec5SDimitry Andric /// line offsets for the MemoryBuffer, so this is not cheap: use only when
12840b57cec5SDimitry Andric /// about to emit a diagnostic.
getLineNumber(FileID FID,unsigned FilePos,bool * Invalid) const12850b57cec5SDimitry Andric unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
12860b57cec5SDimitry Andric bool *Invalid) const {
12870b57cec5SDimitry Andric if (FID.isInvalid()) {
12880b57cec5SDimitry Andric if (Invalid)
12890b57cec5SDimitry Andric *Invalid = true;
12900b57cec5SDimitry Andric return 1;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric
1293e8d8bef9SDimitry Andric const ContentCache *Content;
12940b57cec5SDimitry Andric if (LastLineNoFileIDQuery == FID)
12950b57cec5SDimitry Andric Content = LastLineNoContentCache;
12960b57cec5SDimitry Andric else {
12970b57cec5SDimitry Andric bool MyInvalid = false;
12980b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
12990b57cec5SDimitry Andric if (MyInvalid || !Entry.isFile()) {
13000b57cec5SDimitry Andric if (Invalid)
13010b57cec5SDimitry Andric *Invalid = true;
13020b57cec5SDimitry Andric return 1;
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric
1305e8d8bef9SDimitry Andric Content = &Entry.getFile().getContentCache();
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric
13080b57cec5SDimitry Andric // If this is the first use of line information for this buffer, compute the
13095f757f3fSDimitry Andric // SourceLineCache for it on demand.
13100b57cec5SDimitry Andric if (!Content->SourceLineCache) {
1311bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1312e8d8bef9SDimitry Andric Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
13130b57cec5SDimitry Andric if (Invalid)
1314e8d8bef9SDimitry Andric *Invalid = !Buffer;
1315e8d8bef9SDimitry Andric if (!Buffer)
13160b57cec5SDimitry Andric return 1;
1317e8d8bef9SDimitry Andric
1318e8d8bef9SDimitry Andric Content->SourceLineCache =
1319e8d8bef9SDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
13200b57cec5SDimitry Andric } else if (Invalid)
13210b57cec5SDimitry Andric *Invalid = false;
13220b57cec5SDimitry Andric
13230b57cec5SDimitry Andric // Okay, we know we have a line number table. Do a binary search to find the
13240b57cec5SDimitry Andric // line number that this character position lands on.
1325e8d8bef9SDimitry Andric const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1326e8d8bef9SDimitry Andric const unsigned *SourceLineCacheStart = SourceLineCache;
1327e8d8bef9SDimitry Andric const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
13280b57cec5SDimitry Andric
13290b57cec5SDimitry Andric unsigned QueriedFilePos = FilePos+1;
13300b57cec5SDimitry Andric
13310b57cec5SDimitry Andric // FIXME: I would like to be convinced that this code is worth being as
13320b57cec5SDimitry Andric // complicated as it is, binary search isn't that slow.
13330b57cec5SDimitry Andric //
13340b57cec5SDimitry Andric // If it is worth being optimized, then in my opinion it could be more
13350b57cec5SDimitry Andric // performant, simpler, and more obviously correct by just "galloping" outward
13360b57cec5SDimitry Andric // from the queried file position. In fact, this could be incorporated into a
13370b57cec5SDimitry Andric // generic algorithm such as lower_bound_with_hint.
13380b57cec5SDimitry Andric //
13390b57cec5SDimitry Andric // If someone gives me a test case where this matters, and I will do it! - DWD
13400b57cec5SDimitry Andric
13410b57cec5SDimitry Andric // If the previous query was to the same file, we know both the file pos from
13420b57cec5SDimitry Andric // that query and the line number returned. This allows us to narrow the
13430b57cec5SDimitry Andric // search space from the entire file to something near the match.
13440b57cec5SDimitry Andric if (LastLineNoFileIDQuery == FID) {
13450b57cec5SDimitry Andric if (QueriedFilePos >= LastLineNoFilePos) {
13460b57cec5SDimitry Andric // FIXME: Potential overflow?
13470b57cec5SDimitry Andric SourceLineCache = SourceLineCache+LastLineNoResult-1;
13480b57cec5SDimitry Andric
13490b57cec5SDimitry Andric // The query is likely to be nearby the previous one. Here we check to
13500b57cec5SDimitry Andric // see if it is within 5, 10 or 20 lines. It can be far away in cases
13510b57cec5SDimitry Andric // where big comment blocks and vertical whitespace eat up lines but
13520b57cec5SDimitry Andric // contribute no tokens.
13530b57cec5SDimitry Andric if (SourceLineCache+5 < SourceLineCacheEnd) {
13540b57cec5SDimitry Andric if (SourceLineCache[5] > QueriedFilePos)
13550b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+5;
13560b57cec5SDimitry Andric else if (SourceLineCache+10 < SourceLineCacheEnd) {
13570b57cec5SDimitry Andric if (SourceLineCache[10] > QueriedFilePos)
13580b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+10;
13590b57cec5SDimitry Andric else if (SourceLineCache+20 < SourceLineCacheEnd) {
13600b57cec5SDimitry Andric if (SourceLineCache[20] > QueriedFilePos)
13610b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+20;
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric }
13650b57cec5SDimitry Andric } else {
1366e8d8bef9SDimitry Andric if (LastLineNoResult < Content->SourceLineCache.size())
13670b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric }
13700b57cec5SDimitry Andric
1371e8d8bef9SDimitry Andric const unsigned *Pos =
1372e8d8bef9SDimitry Andric std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
13730b57cec5SDimitry Andric unsigned LineNo = Pos-SourceLineCacheStart;
13740b57cec5SDimitry Andric
13750b57cec5SDimitry Andric LastLineNoFileIDQuery = FID;
13760b57cec5SDimitry Andric LastLineNoContentCache = Content;
13770b57cec5SDimitry Andric LastLineNoFilePos = QueriedFilePos;
13780b57cec5SDimitry Andric LastLineNoResult = LineNo;
13790b57cec5SDimitry Andric return LineNo;
13800b57cec5SDimitry Andric }
13810b57cec5SDimitry Andric
getSpellingLineNumber(SourceLocation Loc,bool * Invalid) const13820b57cec5SDimitry Andric unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
13830b57cec5SDimitry Andric bool *Invalid) const {
13840b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
13850b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
13860b57cec5SDimitry Andric return getLineNumber(LocInfo.first, LocInfo.second);
13870b57cec5SDimitry Andric }
getExpansionLineNumber(SourceLocation Loc,bool * Invalid) const13880b57cec5SDimitry Andric unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
13890b57cec5SDimitry Andric bool *Invalid) const {
13900b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0;
13910b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
13920b57cec5SDimitry Andric return getLineNumber(LocInfo.first, LocInfo.second);
13930b57cec5SDimitry Andric }
getPresumedLineNumber(SourceLocation Loc,bool * Invalid) const13940b57cec5SDimitry Andric unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
13950b57cec5SDimitry Andric bool *Invalid) const {
13960b57cec5SDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc);
13970b57cec5SDimitry Andric if (isInvalid(PLoc, Invalid)) return 0;
13980b57cec5SDimitry Andric return PLoc.getLine();
13990b57cec5SDimitry Andric }
14000b57cec5SDimitry Andric
14010b57cec5SDimitry Andric /// getFileCharacteristic - return the file characteristic of the specified
14020b57cec5SDimitry Andric /// source location, indicating whether this is a normal file, a system
14030b57cec5SDimitry Andric /// header, or an "implicit extern C" system header.
14040b57cec5SDimitry Andric ///
14050b57cec5SDimitry Andric /// This state can be modified with flags on GNU linemarker directives like:
14060b57cec5SDimitry Andric /// # 4 "foo.h" 3
14070b57cec5SDimitry Andric /// which changes all source locations in the current file after that to be
14080b57cec5SDimitry Andric /// considered to be from a system header.
14090b57cec5SDimitry Andric SrcMgr::CharacteristicKind
getFileCharacteristic(SourceLocation Loc) const14100b57cec5SDimitry Andric SourceManager::getFileCharacteristic(SourceLocation Loc) const {
14110b57cec5SDimitry Andric assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
14120b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1413e8d8bef9SDimitry Andric const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1414e8d8bef9SDimitry Andric if (!SEntry)
14150b57cec5SDimitry Andric return C_User;
14160b57cec5SDimitry Andric
1417e8d8bef9SDimitry Andric const SrcMgr::FileInfo &FI = SEntry->getFile();
14180b57cec5SDimitry Andric
14190b57cec5SDimitry Andric // If there are no #line directives in this file, just return the whole-file
14200b57cec5SDimitry Andric // state.
14210b57cec5SDimitry Andric if (!FI.hasLineDirectives())
14220b57cec5SDimitry Andric return FI.getFileCharacteristic();
14230b57cec5SDimitry Andric
14240b57cec5SDimitry Andric assert(LineTable && "Can't have linetable entries without a LineTable!");
14250b57cec5SDimitry Andric // See if there is a #line directive before the location.
14260b57cec5SDimitry Andric const LineEntry *Entry =
14270b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
14280b57cec5SDimitry Andric
14290b57cec5SDimitry Andric // If this is before the first line marker, use the file characteristic.
14300b57cec5SDimitry Andric if (!Entry)
14310b57cec5SDimitry Andric return FI.getFileCharacteristic();
14320b57cec5SDimitry Andric
14330b57cec5SDimitry Andric return Entry->FileKind;
14340b57cec5SDimitry Andric }
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric /// Return the filename or buffer identifier of the buffer the location is in.
14370b57cec5SDimitry Andric /// Note that this name does not respect \#line directives. Use getPresumedLoc
14380b57cec5SDimitry Andric /// for normal clients.
getBufferName(SourceLocation Loc,bool * Invalid) const14390b57cec5SDimitry Andric StringRef SourceManager::getBufferName(SourceLocation Loc,
14400b57cec5SDimitry Andric bool *Invalid) const {
14410b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return "<invalid loc>";
14420b57cec5SDimitry Andric
1443e8d8bef9SDimitry Andric auto B = getBufferOrNone(getFileID(Loc));
1444e8d8bef9SDimitry Andric if (Invalid)
1445e8d8bef9SDimitry Andric *Invalid = !B;
1446e8d8bef9SDimitry Andric return B ? B->getBufferIdentifier() : "<invalid buffer>";
14470b57cec5SDimitry Andric }
14480b57cec5SDimitry Andric
14490b57cec5SDimitry Andric /// getPresumedLoc - This method returns the "presumed" location of a
14500b57cec5SDimitry Andric /// SourceLocation specifies. A "presumed location" can be modified by \#line
14510b57cec5SDimitry Andric /// or GNU line marker directives. This provides a view on the data that a
14520b57cec5SDimitry Andric /// user should see in diagnostics, for example.
14530b57cec5SDimitry Andric ///
14540b57cec5SDimitry Andric /// Note that a presumed location is always given as the expansion point of an
14550b57cec5SDimitry Andric /// expansion location, not at the spelling location.
getPresumedLoc(SourceLocation Loc,bool UseLineDirectives) const14560b57cec5SDimitry Andric PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
14570b57cec5SDimitry Andric bool UseLineDirectives) const {
14580b57cec5SDimitry Andric if (Loc.isInvalid()) return PresumedLoc();
14590b57cec5SDimitry Andric
14600b57cec5SDimitry Andric // Presumed locations are always for expansion points.
14610b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
14620b57cec5SDimitry Andric
14630b57cec5SDimitry Andric bool Invalid = false;
14640b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
14650b57cec5SDimitry Andric if (Invalid || !Entry.isFile())
14660b57cec5SDimitry Andric return PresumedLoc();
14670b57cec5SDimitry Andric
14680b57cec5SDimitry Andric const SrcMgr::FileInfo &FI = Entry.getFile();
1469e8d8bef9SDimitry Andric const SrcMgr::ContentCache *C = &FI.getContentCache();
14700b57cec5SDimitry Andric
14710b57cec5SDimitry Andric // To get the source name, first consult the FileEntry (if one exists)
14720b57cec5SDimitry Andric // before the MemBuffer as this will avoid unnecessarily paging in the
14730b57cec5SDimitry Andric // MemBuffer.
14740b57cec5SDimitry Andric FileID FID = LocInfo.first;
14750b57cec5SDimitry Andric StringRef Filename;
14760b57cec5SDimitry Andric if (C->OrigEntry)
14770b57cec5SDimitry Andric Filename = C->OrigEntry->getName();
1478e8d8bef9SDimitry Andric else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1479e8d8bef9SDimitry Andric Filename = Buffer->getBufferIdentifier();
14800b57cec5SDimitry Andric
14810b57cec5SDimitry Andric unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
14820b57cec5SDimitry Andric if (Invalid)
14830b57cec5SDimitry Andric return PresumedLoc();
14840b57cec5SDimitry Andric unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
14850b57cec5SDimitry Andric if (Invalid)
14860b57cec5SDimitry Andric return PresumedLoc();
14870b57cec5SDimitry Andric
14880b57cec5SDimitry Andric SourceLocation IncludeLoc = FI.getIncludeLoc();
14890b57cec5SDimitry Andric
14900b57cec5SDimitry Andric // If we have #line directives in this file, update and overwrite the physical
14910b57cec5SDimitry Andric // location info if appropriate.
14920b57cec5SDimitry Andric if (UseLineDirectives && FI.hasLineDirectives()) {
14930b57cec5SDimitry Andric assert(LineTable && "Can't have linetable entries without a LineTable!");
14940b57cec5SDimitry Andric // See if there is a #line directive before this. If so, get it.
14950b57cec5SDimitry Andric if (const LineEntry *Entry =
14960b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
14970b57cec5SDimitry Andric // If the LineEntry indicates a filename, use it.
14980b57cec5SDimitry Andric if (Entry->FilenameID != -1) {
14990b57cec5SDimitry Andric Filename = LineTable->getFilename(Entry->FilenameID);
15000b57cec5SDimitry Andric // The contents of files referenced by #line are not in the
15010b57cec5SDimitry Andric // SourceManager
15020b57cec5SDimitry Andric FID = FileID::get(0);
15030b57cec5SDimitry Andric }
15040b57cec5SDimitry Andric
15050b57cec5SDimitry Andric // Use the line number specified by the LineEntry. This line number may
15060b57cec5SDimitry Andric // be multiple lines down from the line entry. Add the difference in
15070b57cec5SDimitry Andric // physical line numbers from the query point and the line marker to the
15080b57cec5SDimitry Andric // total.
15090b57cec5SDimitry Andric unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
15100b57cec5SDimitry Andric LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
15110b57cec5SDimitry Andric
15120b57cec5SDimitry Andric // Note that column numbers are not molested by line markers.
15130b57cec5SDimitry Andric
15140b57cec5SDimitry Andric // Handle virtual #include manipulation.
15150b57cec5SDimitry Andric if (Entry->IncludeOffset) {
15160b57cec5SDimitry Andric IncludeLoc = getLocForStartOfFile(LocInfo.first);
15170b57cec5SDimitry Andric IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
15180b57cec5SDimitry Andric }
15190b57cec5SDimitry Andric }
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric
15220b57cec5SDimitry Andric return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
15230b57cec5SDimitry Andric }
15240b57cec5SDimitry Andric
15250b57cec5SDimitry Andric /// Returns whether the PresumedLoc for a given SourceLocation is
15260b57cec5SDimitry Andric /// in the main file.
15270b57cec5SDimitry Andric ///
15280b57cec5SDimitry Andric /// This computes the "presumed" location for a SourceLocation, then checks
15290b57cec5SDimitry Andric /// whether it came from a file other than the main file. This is different
15300b57cec5SDimitry Andric /// from isWrittenInMainFile() because it takes line marker directives into
15310b57cec5SDimitry Andric /// account.
isInMainFile(SourceLocation Loc) const15320b57cec5SDimitry Andric bool SourceManager::isInMainFile(SourceLocation Loc) const {
15330b57cec5SDimitry Andric if (Loc.isInvalid()) return false;
15340b57cec5SDimitry Andric
15350b57cec5SDimitry Andric // Presumed locations are always for expansion points.
15360b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
15370b57cec5SDimitry Andric
1538e8d8bef9SDimitry Andric const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1539e8d8bef9SDimitry Andric if (!Entry)
15400b57cec5SDimitry Andric return false;
15410b57cec5SDimitry Andric
1542e8d8bef9SDimitry Andric const SrcMgr::FileInfo &FI = Entry->getFile();
15430b57cec5SDimitry Andric
15440b57cec5SDimitry Andric // Check if there is a line directive for this location.
15450b57cec5SDimitry Andric if (FI.hasLineDirectives())
15460b57cec5SDimitry Andric if (const LineEntry *Entry =
15470b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
15480b57cec5SDimitry Andric if (Entry->IncludeOffset)
15490b57cec5SDimitry Andric return false;
15500b57cec5SDimitry Andric
15510b57cec5SDimitry Andric return FI.getIncludeLoc().isInvalid();
15520b57cec5SDimitry Andric }
15530b57cec5SDimitry Andric
15540b57cec5SDimitry Andric /// The size of the SLocEntry that \p FID represents.
getFileIDSize(FileID FID) const15550b57cec5SDimitry Andric unsigned SourceManager::getFileIDSize(FileID FID) const {
15560b57cec5SDimitry Andric bool Invalid = false;
15570b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
15580b57cec5SDimitry Andric if (Invalid)
15590b57cec5SDimitry Andric return 0;
15600b57cec5SDimitry Andric
15610b57cec5SDimitry Andric int ID = FID.ID;
1562fe6060f1SDimitry Andric SourceLocation::UIntTy NextOffset;
15630b57cec5SDimitry Andric if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
15640b57cec5SDimitry Andric NextOffset = getNextLocalOffset();
15650b57cec5SDimitry Andric else if (ID+1 == -1)
15660b57cec5SDimitry Andric NextOffset = MaxLoadedOffset;
15670b57cec5SDimitry Andric else
15680b57cec5SDimitry Andric NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric return NextOffset - Entry.getOffset() - 1;
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric
15730b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15740b57cec5SDimitry Andric // Other miscellaneous methods.
15750b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15760b57cec5SDimitry Andric
15770b57cec5SDimitry Andric /// Get the source location for the given file:line:col triplet.
15780b57cec5SDimitry Andric ///
15790b57cec5SDimitry Andric /// If the source file is included multiple times, the source location will
15800b57cec5SDimitry Andric /// be based upon an arbitrary inclusion.
translateFileLineCol(const FileEntry * SourceFile,unsigned Line,unsigned Col) const15810b57cec5SDimitry Andric SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
15820b57cec5SDimitry Andric unsigned Line,
15830b57cec5SDimitry Andric unsigned Col) const {
15840b57cec5SDimitry Andric assert(SourceFile && "Null source file!");
15850b57cec5SDimitry Andric assert(Line && Col && "Line and column should start from 1!");
15860b57cec5SDimitry Andric
15870b57cec5SDimitry Andric FileID FirstFID = translateFile(SourceFile);
15880b57cec5SDimitry Andric return translateLineCol(FirstFID, Line, Col);
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric
15910b57cec5SDimitry Andric /// Get the FileID for the given file.
15920b57cec5SDimitry Andric ///
15930b57cec5SDimitry Andric /// If the source file is included multiple times, the FileID will be the
15940b57cec5SDimitry Andric /// first inclusion.
translateFile(const FileEntry * SourceFile) const15950b57cec5SDimitry Andric FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
15960b57cec5SDimitry Andric assert(SourceFile && "Null source file!");
15970b57cec5SDimitry Andric
15980b57cec5SDimitry Andric // First, check the main file ID, since it is common to look for a
15990b57cec5SDimitry Andric // location in the main file.
16000b57cec5SDimitry Andric if (MainFileID.isValid()) {
16010b57cec5SDimitry Andric bool Invalid = false;
16020b57cec5SDimitry Andric const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
16030b57cec5SDimitry Andric if (Invalid)
16040b57cec5SDimitry Andric return FileID();
16050b57cec5SDimitry Andric
16060b57cec5SDimitry Andric if (MainSLoc.isFile()) {
1607e8d8bef9SDimitry Andric if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1608a7dea167SDimitry Andric return MainFileID;
16090b57cec5SDimitry Andric }
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric // The location we're looking for isn't in the main file; look
16130b57cec5SDimitry Andric // through all of the local source locations.
16140b57cec5SDimitry Andric for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
16155ffd83dbSDimitry Andric const SLocEntry &SLoc = getLocalSLocEntry(I);
1616e8d8bef9SDimitry Andric if (SLoc.isFile() &&
1617e8d8bef9SDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1618a7dea167SDimitry Andric return FileID::get(I);
16190b57cec5SDimitry Andric }
1620a7dea167SDimitry Andric
16210b57cec5SDimitry Andric // If that still didn't help, try the modules.
16220b57cec5SDimitry Andric for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
16230b57cec5SDimitry Andric const SLocEntry &SLoc = getLoadedSLocEntry(I);
1624e8d8bef9SDimitry Andric if (SLoc.isFile() &&
1625e8d8bef9SDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1626a7dea167SDimitry Andric return FileID::get(-int(I) - 2);
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric
16290b57cec5SDimitry Andric return FileID();
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric
16320b57cec5SDimitry Andric /// Get the source location in \arg FID for the given line:col.
16330b57cec5SDimitry Andric /// Returns null location if \arg FID is not a file SLocEntry.
translateLineCol(FileID FID,unsigned Line,unsigned Col) const16340b57cec5SDimitry Andric SourceLocation SourceManager::translateLineCol(FileID FID,
16350b57cec5SDimitry Andric unsigned Line,
16360b57cec5SDimitry Andric unsigned Col) const {
16370b57cec5SDimitry Andric // Lines are used as a one-based index into a zero-based array. This assert
16380b57cec5SDimitry Andric // checks for possible buffer underruns.
16390b57cec5SDimitry Andric assert(Line && Col && "Line and column should start from 1!");
16400b57cec5SDimitry Andric
16410b57cec5SDimitry Andric if (FID.isInvalid())
16420b57cec5SDimitry Andric return SourceLocation();
16430b57cec5SDimitry Andric
16440b57cec5SDimitry Andric bool Invalid = false;
16450b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
16460b57cec5SDimitry Andric if (Invalid)
16470b57cec5SDimitry Andric return SourceLocation();
16480b57cec5SDimitry Andric
16490b57cec5SDimitry Andric if (!Entry.isFile())
16500b57cec5SDimitry Andric return SourceLocation();
16510b57cec5SDimitry Andric
16520b57cec5SDimitry Andric SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
16530b57cec5SDimitry Andric
16540b57cec5SDimitry Andric if (Line == 1 && Col == 1)
16550b57cec5SDimitry Andric return FileLoc;
16560b57cec5SDimitry Andric
1657e8d8bef9SDimitry Andric const ContentCache *Content = &Entry.getFile().getContentCache();
16580b57cec5SDimitry Andric
16590b57cec5SDimitry Andric // If this is the first use of line information for this buffer, compute the
16600b57cec5SDimitry Andric // SourceLineCache for it on demand.
1661bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer =
1662e8d8bef9SDimitry Andric Content->getBufferOrNone(Diag, getFileManager());
1663e8d8bef9SDimitry Andric if (!Buffer)
16640b57cec5SDimitry Andric return SourceLocation();
1665e8d8bef9SDimitry Andric if (!Content->SourceLineCache)
1666e8d8bef9SDimitry Andric Content->SourceLineCache =
1667e8d8bef9SDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
16680b57cec5SDimitry Andric
1669e8d8bef9SDimitry Andric if (Line > Content->SourceLineCache.size()) {
1670e8d8bef9SDimitry Andric unsigned Size = Buffer->getBufferSize();
16710b57cec5SDimitry Andric if (Size > 0)
16720b57cec5SDimitry Andric --Size;
16730b57cec5SDimitry Andric return FileLoc.getLocWithOffset(Size);
16740b57cec5SDimitry Andric }
16750b57cec5SDimitry Andric
16760b57cec5SDimitry Andric unsigned FilePos = Content->SourceLineCache[Line - 1];
16770b57cec5SDimitry Andric const char *Buf = Buffer->getBufferStart() + FilePos;
16780b57cec5SDimitry Andric unsigned BufLength = Buffer->getBufferSize() - FilePos;
16790b57cec5SDimitry Andric if (BufLength == 0)
16800b57cec5SDimitry Andric return FileLoc.getLocWithOffset(FilePos);
16810b57cec5SDimitry Andric
16820b57cec5SDimitry Andric unsigned i = 0;
16830b57cec5SDimitry Andric
16840b57cec5SDimitry Andric // Check that the given column is valid.
16850b57cec5SDimitry Andric while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
16860b57cec5SDimitry Andric ++i;
16870b57cec5SDimitry Andric return FileLoc.getLocWithOffset(FilePos + i);
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric
16900b57cec5SDimitry Andric /// Compute a map of macro argument chunks to their expanded source
16910b57cec5SDimitry Andric /// location. Chunks that are not part of a macro argument will map to an
16920b57cec5SDimitry Andric /// invalid source location. e.g. if a file contains one macro argument at
16930b57cec5SDimitry Andric /// offset 100 with length 10, this is how the map will be formed:
16940b57cec5SDimitry Andric /// 0 -> SourceLocation()
16950b57cec5SDimitry Andric /// 100 -> Expanded macro arg location
16960b57cec5SDimitry Andric /// 110 -> SourceLocation()
computeMacroArgsCache(MacroArgsMap & MacroArgsCache,FileID FID) const16970b57cec5SDimitry Andric void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
16980b57cec5SDimitry Andric FileID FID) const {
16990b57cec5SDimitry Andric assert(FID.isValid());
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric // Initially no macro argument chunk is present.
17020b57cec5SDimitry Andric MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
17030b57cec5SDimitry Andric
17040b57cec5SDimitry Andric int ID = FID.ID;
17050b57cec5SDimitry Andric while (true) {
17060b57cec5SDimitry Andric ++ID;
17070b57cec5SDimitry Andric // Stop if there are no more FileIDs to check.
17080b57cec5SDimitry Andric if (ID > 0) {
17090b57cec5SDimitry Andric if (unsigned(ID) >= local_sloc_entry_size())
17100b57cec5SDimitry Andric return;
17110b57cec5SDimitry Andric } else if (ID == -1) {
17120b57cec5SDimitry Andric return;
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric bool Invalid = false;
17160b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
17170b57cec5SDimitry Andric if (Invalid)
17180b57cec5SDimitry Andric return;
17190b57cec5SDimitry Andric if (Entry.isFile()) {
1720e8d8bef9SDimitry Andric auto& File = Entry.getFile();
1721e8d8bef9SDimitry Andric if (File.getFileCharacteristic() == C_User_ModuleMap ||
1722e8d8bef9SDimitry Andric File.getFileCharacteristic() == C_System_ModuleMap)
1723e8d8bef9SDimitry Andric continue;
1724e8d8bef9SDimitry Andric
1725e8d8bef9SDimitry Andric SourceLocation IncludeLoc = File.getIncludeLoc();
17265ffd83dbSDimitry Andric bool IncludedInFID =
17275ffd83dbSDimitry Andric (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
17285ffd83dbSDimitry Andric // Predefined header doesn't have a valid include location in main
17295ffd83dbSDimitry Andric // file, but any files created by it should still be skipped when
17305ffd83dbSDimitry Andric // computing macro args expanded in the main file.
1731e8d8bef9SDimitry Andric (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
17325ffd83dbSDimitry Andric if (IncludedInFID) {
17335ffd83dbSDimitry Andric // Skip the files/macros of the #include'd file, we only care about
17345ffd83dbSDimitry Andric // macros that lexed macro arguments from our file.
17350b57cec5SDimitry Andric if (Entry.getFile().NumCreatedFIDs)
17360b57cec5SDimitry Andric ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
17370b57cec5SDimitry Andric continue;
1738bdd1243dSDimitry Andric }
17395ffd83dbSDimitry Andric // If file was included but not from FID, there is no more files/macros
17405ffd83dbSDimitry Andric // that may be "contained" in this file.
1741bdd1243dSDimitry Andric if (IncludeLoc.isValid())
17425ffd83dbSDimitry Andric return;
17435ffd83dbSDimitry Andric continue;
17440b57cec5SDimitry Andric }
17450b57cec5SDimitry Andric
17460b57cec5SDimitry Andric const ExpansionInfo &ExpInfo = Entry.getExpansion();
17470b57cec5SDimitry Andric
17480b57cec5SDimitry Andric if (ExpInfo.getExpansionLocStart().isFileID()) {
17490b57cec5SDimitry Andric if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
17500b57cec5SDimitry Andric return; // No more files/macros that may be "contained" in this file.
17510b57cec5SDimitry Andric }
17520b57cec5SDimitry Andric
17530b57cec5SDimitry Andric if (!ExpInfo.isMacroArgExpansion())
17540b57cec5SDimitry Andric continue;
17550b57cec5SDimitry Andric
17560b57cec5SDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
17570b57cec5SDimitry Andric ExpInfo.getSpellingLoc(),
17580b57cec5SDimitry Andric SourceLocation::getMacroLoc(Entry.getOffset()),
17590b57cec5SDimitry Andric getFileIDSize(FileID::get(ID)));
17600b57cec5SDimitry Andric }
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric
associateFileChunkWithMacroArgExp(MacroArgsMap & MacroArgsCache,FileID FID,SourceLocation SpellLoc,SourceLocation ExpansionLoc,unsigned ExpansionLength) const17630b57cec5SDimitry Andric void SourceManager::associateFileChunkWithMacroArgExp(
17640b57cec5SDimitry Andric MacroArgsMap &MacroArgsCache,
17650b57cec5SDimitry Andric FileID FID,
17660b57cec5SDimitry Andric SourceLocation SpellLoc,
17670b57cec5SDimitry Andric SourceLocation ExpansionLoc,
17680b57cec5SDimitry Andric unsigned ExpansionLength) const {
17690b57cec5SDimitry Andric if (!SpellLoc.isFileID()) {
1770fe6060f1SDimitry Andric SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1771fe6060f1SDimitry Andric SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
17720b57cec5SDimitry Andric
17730b57cec5SDimitry Andric // The spelling range for this macro argument expansion can span multiple
17740b57cec5SDimitry Andric // consecutive FileID entries. Go through each entry contained in the
17750b57cec5SDimitry Andric // spelling range and if one is itself a macro argument expansion, recurse
17760b57cec5SDimitry Andric // and associate the file chunk that it represents.
17770b57cec5SDimitry Andric
17780b57cec5SDimitry Andric FileID SpellFID; // Current FileID in the spelling range.
17790b57cec5SDimitry Andric unsigned SpellRelativeOffs;
17800b57cec5SDimitry Andric std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
17810b57cec5SDimitry Andric while (true) {
17820b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(SpellFID);
1783fe6060f1SDimitry Andric SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
17840b57cec5SDimitry Andric unsigned SpellFIDSize = getFileIDSize(SpellFID);
1785fe6060f1SDimitry Andric SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
17860b57cec5SDimitry Andric const ExpansionInfo &Info = Entry.getExpansion();
17870b57cec5SDimitry Andric if (Info.isMacroArgExpansion()) {
17880b57cec5SDimitry Andric unsigned CurrSpellLength;
17890b57cec5SDimitry Andric if (SpellFIDEndOffs < SpellEndOffs)
17900b57cec5SDimitry Andric CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
17910b57cec5SDimitry Andric else
17920b57cec5SDimitry Andric CurrSpellLength = ExpansionLength;
17930b57cec5SDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
17940b57cec5SDimitry Andric Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
17950b57cec5SDimitry Andric ExpansionLoc, CurrSpellLength);
17960b57cec5SDimitry Andric }
17970b57cec5SDimitry Andric
17980b57cec5SDimitry Andric if (SpellFIDEndOffs >= SpellEndOffs)
17990b57cec5SDimitry Andric return; // we covered all FileID entries in the spelling range.
18000b57cec5SDimitry Andric
18010b57cec5SDimitry Andric // Move to the next FileID entry in the spelling range.
18020b57cec5SDimitry Andric unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
18030b57cec5SDimitry Andric ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
18040b57cec5SDimitry Andric ExpansionLength -= advance;
18050b57cec5SDimitry Andric ++SpellFID.ID;
18060b57cec5SDimitry Andric SpellRelativeOffs = 0;
18070b57cec5SDimitry Andric }
18080b57cec5SDimitry Andric }
18090b57cec5SDimitry Andric
18100b57cec5SDimitry Andric assert(SpellLoc.isFileID());
18110b57cec5SDimitry Andric
18120b57cec5SDimitry Andric unsigned BeginOffs;
18130b57cec5SDimitry Andric if (!isInFileID(SpellLoc, FID, &BeginOffs))
18140b57cec5SDimitry Andric return;
18150b57cec5SDimitry Andric
18160b57cec5SDimitry Andric unsigned EndOffs = BeginOffs + ExpansionLength;
18170b57cec5SDimitry Andric
18180b57cec5SDimitry Andric // Add a new chunk for this macro argument. A previous macro argument chunk
18190b57cec5SDimitry Andric // may have been lexed again, so e.g. if the map is
18200b57cec5SDimitry Andric // 0 -> SourceLocation()
18210b57cec5SDimitry Andric // 100 -> Expanded loc #1
18220b57cec5SDimitry Andric // 110 -> SourceLocation()
18230b57cec5SDimitry Andric // and we found a new macro FileID that lexed from offset 105 with length 3,
18240b57cec5SDimitry Andric // the new map will be:
18250b57cec5SDimitry Andric // 0 -> SourceLocation()
18260b57cec5SDimitry Andric // 100 -> Expanded loc #1
18270b57cec5SDimitry Andric // 105 -> Expanded loc #2
18280b57cec5SDimitry Andric // 108 -> Expanded loc #1
18290b57cec5SDimitry Andric // 110 -> SourceLocation()
18300b57cec5SDimitry Andric //
18310b57cec5SDimitry Andric // Since re-lexed macro chunks will always be the same size or less of
18320b57cec5SDimitry Andric // previous chunks, we only need to find where the ending of the new macro
18330b57cec5SDimitry Andric // chunk is mapped to and update the map with new begin/end mappings.
18340b57cec5SDimitry Andric
18350b57cec5SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
18360b57cec5SDimitry Andric --I;
18370b57cec5SDimitry Andric SourceLocation EndOffsMappedLoc = I->second;
18380b57cec5SDimitry Andric MacroArgsCache[BeginOffs] = ExpansionLoc;
18390b57cec5SDimitry Andric MacroArgsCache[EndOffs] = EndOffsMappedLoc;
18400b57cec5SDimitry Andric }
18410b57cec5SDimitry Andric
18420b57cec5SDimitry Andric /// If \arg Loc points inside a function macro argument, the returned
18430b57cec5SDimitry Andric /// location will be the macro location in which the argument was expanded.
18440b57cec5SDimitry Andric /// If a macro argument is used multiple times, the expanded location will
18450b57cec5SDimitry Andric /// be at the first expansion of the argument.
18460b57cec5SDimitry Andric /// e.g.
18470b57cec5SDimitry Andric /// MY_MACRO(foo);
18480b57cec5SDimitry Andric /// ^
18490b57cec5SDimitry Andric /// Passing a file location pointing at 'foo', will yield a macro location
18500b57cec5SDimitry Andric /// where 'foo' was expanded into.
18510b57cec5SDimitry Andric SourceLocation
getMacroArgExpandedLocation(SourceLocation Loc) const18520b57cec5SDimitry Andric SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
18530b57cec5SDimitry Andric if (Loc.isInvalid() || !Loc.isFileID())
18540b57cec5SDimitry Andric return Loc;
18550b57cec5SDimitry Andric
18560b57cec5SDimitry Andric FileID FID;
18570b57cec5SDimitry Andric unsigned Offset;
18580b57cec5SDimitry Andric std::tie(FID, Offset) = getDecomposedLoc(Loc);
18590b57cec5SDimitry Andric if (FID.isInvalid())
18600b57cec5SDimitry Andric return Loc;
18610b57cec5SDimitry Andric
18620b57cec5SDimitry Andric std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
18630b57cec5SDimitry Andric if (!MacroArgsCache) {
1864a7dea167SDimitry Andric MacroArgsCache = std::make_unique<MacroArgsMap>();
18650b57cec5SDimitry Andric computeMacroArgsCache(*MacroArgsCache, FID);
18660b57cec5SDimitry Andric }
18670b57cec5SDimitry Andric
18680b57cec5SDimitry Andric assert(!MacroArgsCache->empty());
18690b57cec5SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1870e8d8bef9SDimitry Andric // In case every element in MacroArgsCache is greater than Offset we can't
1871e8d8bef9SDimitry Andric // decrement the iterator.
1872e8d8bef9SDimitry Andric if (I == MacroArgsCache->begin())
1873e8d8bef9SDimitry Andric return Loc;
1874e8d8bef9SDimitry Andric
18750b57cec5SDimitry Andric --I;
18760b57cec5SDimitry Andric
1877fe6060f1SDimitry Andric SourceLocation::UIntTy MacroArgBeginOffs = I->first;
18780b57cec5SDimitry Andric SourceLocation MacroArgExpandedLoc = I->second;
18790b57cec5SDimitry Andric if (MacroArgExpandedLoc.isValid())
18800b57cec5SDimitry Andric return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
18810b57cec5SDimitry Andric
18820b57cec5SDimitry Andric return Loc;
18830b57cec5SDimitry Andric }
18840b57cec5SDimitry Andric
18850b57cec5SDimitry Andric std::pair<FileID, unsigned>
getDecomposedIncludedLoc(FileID FID) const18860b57cec5SDimitry Andric SourceManager::getDecomposedIncludedLoc(FileID FID) const {
18870b57cec5SDimitry Andric if (FID.isInvalid())
18880b57cec5SDimitry Andric return std::make_pair(FileID(), 0);
18890b57cec5SDimitry Andric
18900b57cec5SDimitry Andric // Uses IncludedLocMap to retrieve/cache the decomposed loc.
18910b57cec5SDimitry Andric
18920b57cec5SDimitry Andric using DecompTy = std::pair<FileID, unsigned>;
18930b57cec5SDimitry Andric auto InsertOp = IncludedLocMap.try_emplace(FID);
18940b57cec5SDimitry Andric DecompTy &DecompLoc = InsertOp.first->second;
18950b57cec5SDimitry Andric if (!InsertOp.second)
18960b57cec5SDimitry Andric return DecompLoc; // already in map.
18970b57cec5SDimitry Andric
18980b57cec5SDimitry Andric SourceLocation UpperLoc;
18990b57cec5SDimitry Andric bool Invalid = false;
19000b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
19010b57cec5SDimitry Andric if (!Invalid) {
19020b57cec5SDimitry Andric if (Entry.isExpansion())
19030b57cec5SDimitry Andric UpperLoc = Entry.getExpansion().getExpansionLocStart();
19040b57cec5SDimitry Andric else
19050b57cec5SDimitry Andric UpperLoc = Entry.getFile().getIncludeLoc();
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric
19080b57cec5SDimitry Andric if (UpperLoc.isValid())
19090b57cec5SDimitry Andric DecompLoc = getDecomposedLoc(UpperLoc);
19100b57cec5SDimitry Andric
19110b57cec5SDimitry Andric return DecompLoc;
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric
isInTheSameTranslationUnitImpl(const std::pair<FileID,unsigned> & LOffs,const std::pair<FileID,unsigned> & ROffs) const19145f757f3fSDimitry Andric bool SourceManager::isInTheSameTranslationUnitImpl(
19155f757f3fSDimitry Andric const std::pair<FileID, unsigned> &LOffs,
19165f757f3fSDimitry Andric const std::pair<FileID, unsigned> &ROffs) const {
19175f757f3fSDimitry Andric // If one is local while the other is loaded.
19185f757f3fSDimitry Andric if (isLoadedFileID(LOffs.first) != isLoadedFileID(ROffs.first))
19195f757f3fSDimitry Andric return false;
19205f757f3fSDimitry Andric
19215f757f3fSDimitry Andric if (isLoadedFileID(LOffs.first) && isLoadedFileID(ROffs.first)) {
19225f757f3fSDimitry Andric auto FindSLocEntryAlloc = [this](FileID FID) {
19235f757f3fSDimitry Andric // Loaded FileIDs are negative, we store the lowest FileID from each
19245f757f3fSDimitry Andric // allocation, later allocations have lower FileIDs.
19255f757f3fSDimitry Andric return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID,
19265f757f3fSDimitry Andric std::greater<FileID>{});
19275f757f3fSDimitry Andric };
19285f757f3fSDimitry Andric
19295f757f3fSDimitry Andric // If both are loaded from different AST files.
19305f757f3fSDimitry Andric if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first))
19315f757f3fSDimitry Andric return false;
19325f757f3fSDimitry Andric }
19335f757f3fSDimitry Andric
19345f757f3fSDimitry Andric return true;
19355f757f3fSDimitry Andric }
19365f757f3fSDimitry Andric
19370b57cec5SDimitry Andric /// Given a decomposed source location, move it up the include/expansion stack
19385f757f3fSDimitry Andric /// to the parent source location within the same translation unit. If this is
19395f757f3fSDimitry Andric /// possible, return the decomposed version of the parent in Loc and return
19405f757f3fSDimitry Andric /// false. If Loc is a top-level entry, return true and don't modify it.
19415f757f3fSDimitry Andric static bool
MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID,unsigned> & Loc,const SourceManager & SM)19425f757f3fSDimitry Andric MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
19430b57cec5SDimitry Andric const SourceManager &SM) {
19440b57cec5SDimitry Andric std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
19455f757f3fSDimitry Andric if (UpperLoc.first.isInvalid() ||
19465f757f3fSDimitry Andric !SM.isInTheSameTranslationUnitImpl(UpperLoc, Loc))
19470b57cec5SDimitry Andric return true; // We reached the top.
19480b57cec5SDimitry Andric
19490b57cec5SDimitry Andric Loc = UpperLoc;
19500b57cec5SDimitry Andric return false;
19510b57cec5SDimitry Andric }
19520b57cec5SDimitry Andric
19530b57cec5SDimitry Andric /// Return the cache entry for comparing the given file IDs
19540b57cec5SDimitry Andric /// for isBeforeInTranslationUnit.
getInBeforeInTUCache(FileID LFID,FileID RFID) const19550b57cec5SDimitry Andric InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
19560b57cec5SDimitry Andric FileID RFID) const {
19570b57cec5SDimitry Andric // This is a magic number for limiting the cache size. It was experimentally
19580b57cec5SDimitry Andric // derived from a small Objective-C project (where the cache filled
19590b57cec5SDimitry Andric // out to ~250 items). We can make it larger if necessary.
1960bdd1243dSDimitry Andric // FIXME: this is almost certainly full these days. Use an LRU cache?
19610b57cec5SDimitry Andric enum { MagicCacheSize = 300 };
19620b57cec5SDimitry Andric IsBeforeInTUCacheKey Key(LFID, RFID);
19630b57cec5SDimitry Andric
19640b57cec5SDimitry Andric // If the cache size isn't too large, do a lookup and if necessary default
19650b57cec5SDimitry Andric // construct an entry. We can then return it to the caller for direct
19660b57cec5SDimitry Andric // use. When they update the value, the cache will get automatically
19670b57cec5SDimitry Andric // updated as well.
19680b57cec5SDimitry Andric if (IBTUCache.size() < MagicCacheSize)
1969bdd1243dSDimitry Andric return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
19700b57cec5SDimitry Andric
19710b57cec5SDimitry Andric // Otherwise, do a lookup that will not construct a new value.
19720b57cec5SDimitry Andric InBeforeInTUCache::iterator I = IBTUCache.find(Key);
19730b57cec5SDimitry Andric if (I != IBTUCache.end())
19740b57cec5SDimitry Andric return I->second;
19750b57cec5SDimitry Andric
19760b57cec5SDimitry Andric // Fall back to the overflow value.
1977bdd1243dSDimitry Andric IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
19780b57cec5SDimitry Andric return IBTUCacheOverflow;
19790b57cec5SDimitry Andric }
19800b57cec5SDimitry Andric
19810b57cec5SDimitry Andric /// Determines the order of 2 source locations in the translation unit.
19820b57cec5SDimitry Andric ///
19830b57cec5SDimitry Andric /// \returns true if LHS source location comes before RHS, false otherwise.
isBeforeInTranslationUnit(SourceLocation LHS,SourceLocation RHS) const19840b57cec5SDimitry Andric bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
19850b57cec5SDimitry Andric SourceLocation RHS) const {
19860b57cec5SDimitry Andric assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
19870b57cec5SDimitry Andric if (LHS == RHS)
19880b57cec5SDimitry Andric return false;
19890b57cec5SDimitry Andric
19900b57cec5SDimitry Andric std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
19910b57cec5SDimitry Andric std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
19920b57cec5SDimitry Andric
19930b57cec5SDimitry Andric // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
19940b57cec5SDimitry Andric // is a serialized one referring to a file that was removed after we loaded
19950b57cec5SDimitry Andric // the PCH.
19960b57cec5SDimitry Andric if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
19970b57cec5SDimitry Andric return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
19980b57cec5SDimitry Andric
19990b57cec5SDimitry Andric std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
20000b57cec5SDimitry Andric if (InSameTU.first)
20010b57cec5SDimitry Andric return InSameTU.second;
20025f757f3fSDimitry Andric // TODO: This should be unreachable, but some clients are calling this
20035f757f3fSDimitry Andric // function before making sure LHS and RHS are in the same TU.
20040b57cec5SDimitry Andric return LOffs.first < ROffs.first;
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric
isInTheSameTranslationUnit(std::pair<FileID,unsigned> & LOffs,std::pair<FileID,unsigned> & ROffs) const20070b57cec5SDimitry Andric std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
20080b57cec5SDimitry Andric std::pair<FileID, unsigned> &LOffs,
20090b57cec5SDimitry Andric std::pair<FileID, unsigned> &ROffs) const {
20105f757f3fSDimitry Andric // If the source locations are not in the same TU, return early.
20115f757f3fSDimitry Andric if (!isInTheSameTranslationUnitImpl(LOffs, ROffs))
20125f757f3fSDimitry Andric return std::make_pair(false, false);
20135f757f3fSDimitry Andric
20140b57cec5SDimitry Andric // If the source locations are in the same file, just compare offsets.
20150b57cec5SDimitry Andric if (LOffs.first == ROffs.first)
20160b57cec5SDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second);
20170b57cec5SDimitry Andric
20180b57cec5SDimitry Andric // If we are comparing a source location with multiple locations in the same
20190b57cec5SDimitry Andric // file, we get a big win by caching the result.
20200b57cec5SDimitry Andric InBeforeInTUCacheEntry &IsBeforeInTUCache =
20210b57cec5SDimitry Andric getInBeforeInTUCache(LOffs.first, ROffs.first);
20220b57cec5SDimitry Andric
20230b57cec5SDimitry Andric // If we are comparing a source location with multiple locations in the same
20240b57cec5SDimitry Andric // file, we get a big win by caching the result.
2025bdd1243dSDimitry Andric if (IsBeforeInTUCache.isCacheValid())
20260b57cec5SDimitry Andric return std::make_pair(
20270b57cec5SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
20280b57cec5SDimitry Andric
2029bdd1243dSDimitry Andric // Okay, we missed in the cache, we'll compute the answer and populate it.
20300b57cec5SDimitry Andric // We need to find the common ancestor. The only way of doing this is to
20310b57cec5SDimitry Andric // build the complete include chain for one and then walking up the chain
20320b57cec5SDimitry Andric // of the other looking for a match.
2033bdd1243dSDimitry Andric
2034bdd1243dSDimitry Andric // A location within a FileID on the path up from LOffs to the main file.
2035bdd1243dSDimitry Andric struct Entry {
20365f757f3fSDimitry Andric std::pair<FileID, unsigned> DecomposedLoc; // FileID redundant, but clearer.
20375f757f3fSDimitry Andric FileID ChildFID; // Used for breaking ties. Invalid for the initial loc.
2038bdd1243dSDimitry Andric };
2039bdd1243dSDimitry Andric llvm::SmallDenseMap<FileID, Entry, 16> LChain;
2040bdd1243dSDimitry Andric
20415f757f3fSDimitry Andric FileID LChild;
20420b57cec5SDimitry Andric do {
20435f757f3fSDimitry Andric LChain.try_emplace(LOffs.first, Entry{LOffs, LChild});
20440b57cec5SDimitry Andric // We catch the case where LOffs is in a file included by ROffs and
20450b57cec5SDimitry Andric // quit early. The other way round unfortunately remains suboptimal.
2046bdd1243dSDimitry Andric if (LOffs.first == ROffs.first)
2047bdd1243dSDimitry Andric break;
20485f757f3fSDimitry Andric LChild = LOffs.first;
20495f757f3fSDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(LOffs, *this));
20500b57cec5SDimitry Andric
20515f757f3fSDimitry Andric FileID RChild;
2052bdd1243dSDimitry Andric do {
20535f757f3fSDimitry Andric auto LIt = LChain.find(ROffs.first);
20545f757f3fSDimitry Andric if (LIt != LChain.end()) {
2055bdd1243dSDimitry Andric // Compare the locations within the common file and cache them.
20565f757f3fSDimitry Andric LOffs = LIt->second.DecomposedLoc;
20575f757f3fSDimitry Andric LChild = LIt->second.ChildFID;
20585f757f3fSDimitry Andric // The relative order of LChild and RChild is a tiebreaker when
2059bdd1243dSDimitry Andric // - locs expand to the same location (occurs in macro arg expansion)
2060bdd1243dSDimitry Andric // - one loc is a parent of the other (we consider the parent as "first")
20615f757f3fSDimitry Andric // For the parent entry to be first, its invalid child file ID must
20625f757f3fSDimitry Andric // compare smaller to the valid child file ID of the other entry.
2063bdd1243dSDimitry Andric // However loaded FileIDs are <0, so we perform *unsigned* comparison!
2064bdd1243dSDimitry Andric // This changes the relative order of local vs loaded FileIDs, but it
2065bdd1243dSDimitry Andric // doesn't matter as these are never mixed in macro expansion.
20665f757f3fSDimitry Andric unsigned LChildID = LChild.ID;
20675f757f3fSDimitry Andric unsigned RChildID = RChild.ID;
2068bdd1243dSDimitry Andric assert(((LOffs.second != ROffs.second) ||
20695f757f3fSDimitry Andric (LChildID == 0 || RChildID == 0) ||
20705f757f3fSDimitry Andric isInSameSLocAddrSpace(getComposedLoc(LChild, 0),
20715f757f3fSDimitry Andric getComposedLoc(RChild, 0), nullptr)) &&
2072bdd1243dSDimitry Andric "Mixed local/loaded FileIDs with same include location?");
2073bdd1243dSDimitry Andric IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
20745f757f3fSDimitry Andric LChildID < RChildID);
20750b57cec5SDimitry Andric return std::make_pair(
20760b57cec5SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
20770b57cec5SDimitry Andric }
20785f757f3fSDimitry Andric RChild = ROffs.first;
20795f757f3fSDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(ROffs, *this));
2080bdd1243dSDimitry Andric
20815f757f3fSDimitry Andric // If we found no match, the location is either in a built-ins buffer or
20825f757f3fSDimitry Andric // associated with global inline asm. PR5662 and PR22576 are examples.
20835f757f3fSDimitry Andric
20845f757f3fSDimitry Andric StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
20855f757f3fSDimitry Andric StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
20865f757f3fSDimitry Andric
20875f757f3fSDimitry Andric bool LIsBuiltins = LB == "<built-in>";
20885f757f3fSDimitry Andric bool RIsBuiltins = RB == "<built-in>";
20895f757f3fSDimitry Andric // Sort built-in before non-built-in.
20905f757f3fSDimitry Andric if (LIsBuiltins || RIsBuiltins) {
20915f757f3fSDimitry Andric if (LIsBuiltins != RIsBuiltins)
20925f757f3fSDimitry Andric return std::make_pair(true, LIsBuiltins);
20935f757f3fSDimitry Andric // Both are in built-in buffers, but from different files. We just claim
20945f757f3fSDimitry Andric // that lower IDs come first.
20955f757f3fSDimitry Andric return std::make_pair(true, LOffs.first < ROffs.first);
20965f757f3fSDimitry Andric }
20975f757f3fSDimitry Andric
20985f757f3fSDimitry Andric bool LIsAsm = LB == "<inline asm>";
20995f757f3fSDimitry Andric bool RIsAsm = RB == "<inline asm>";
21005f757f3fSDimitry Andric // Sort assembler after built-ins, but before the rest.
21015f757f3fSDimitry Andric if (LIsAsm || RIsAsm) {
21025f757f3fSDimitry Andric if (LIsAsm != RIsAsm)
21035f757f3fSDimitry Andric return std::make_pair(true, RIsAsm);
21045f757f3fSDimitry Andric assert(LOffs.first == ROffs.first);
21055f757f3fSDimitry Andric return std::make_pair(true, false);
21065f757f3fSDimitry Andric }
21075f757f3fSDimitry Andric
21085f757f3fSDimitry Andric bool LIsScratch = LB == "<scratch space>";
21095f757f3fSDimitry Andric bool RIsScratch = RB == "<scratch space>";
21105f757f3fSDimitry Andric // Sort scratch after inline asm, but before the rest.
21115f757f3fSDimitry Andric if (LIsScratch || RIsScratch) {
21125f757f3fSDimitry Andric if (LIsScratch != RIsScratch)
21135f757f3fSDimitry Andric return std::make_pair(true, LIsScratch);
21145f757f3fSDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second);
21155f757f3fSDimitry Andric }
21165f757f3fSDimitry Andric
21175f757f3fSDimitry Andric llvm_unreachable("Unsortable locations found");
21180b57cec5SDimitry Andric }
21190b57cec5SDimitry Andric
PrintStats() const21200b57cec5SDimitry Andric void SourceManager::PrintStats() const {
21210b57cec5SDimitry Andric llvm::errs() << "\n*** Source Manager Stats:\n";
21220b57cec5SDimitry Andric llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
21230b57cec5SDimitry Andric << " mem buffers mapped.\n";
21245f757f3fSDimitry Andric llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntries allocated ("
21250b57cec5SDimitry Andric << llvm::capacity_in_bytes(LocalSLocEntryTable)
21265f757f3fSDimitry Andric << " bytes of capacity), " << NextLocalOffset
21275f757f3fSDimitry Andric << "B of SLoc address space used.\n";
21280b57cec5SDimitry Andric llvm::errs() << LoadedSLocEntryTable.size()
21295f757f3fSDimitry Andric << " loaded SLocEntries allocated ("
21305f757f3fSDimitry Andric << llvm::capacity_in_bytes(LoadedSLocEntryTable)
21315f757f3fSDimitry Andric << " bytes of capacity), "
21320b57cec5SDimitry Andric << MaxLoadedOffset - CurrentLoadedOffset
21335f757f3fSDimitry Andric << "B of SLoc address space used.\n";
21340b57cec5SDimitry Andric
21350b57cec5SDimitry Andric unsigned NumLineNumsComputed = 0;
21360b57cec5SDimitry Andric unsigned NumFileBytesMapped = 0;
21370b57cec5SDimitry Andric for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2138e8d8bef9SDimitry Andric NumLineNumsComputed += bool(I->second->SourceLineCache);
21390b57cec5SDimitry Andric NumFileBytesMapped += I->second->getSizeBytesMapped();
21400b57cec5SDimitry Andric }
21410b57cec5SDimitry Andric unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
21420b57cec5SDimitry Andric
21430b57cec5SDimitry Andric llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
21440b57cec5SDimitry Andric << NumLineNumsComputed << " files with line #'s computed, "
21450b57cec5SDimitry Andric << NumMacroArgsComputed << " files with macro args computed.\n";
21460b57cec5SDimitry Andric llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
21470b57cec5SDimitry Andric << NumBinaryProbes << " binary.\n";
21480b57cec5SDimitry Andric }
21490b57cec5SDimitry Andric
dump() const21500b57cec5SDimitry Andric LLVM_DUMP_METHOD void SourceManager::dump() const {
21510b57cec5SDimitry Andric llvm::raw_ostream &out = llvm::errs();
21520b57cec5SDimitry Andric
21530b57cec5SDimitry Andric auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2154bdd1243dSDimitry Andric std::optional<SourceLocation::UIntTy> NextStart) {
21550b57cec5SDimitry Andric out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
21560b57cec5SDimitry Andric << " <SourceLocation " << Entry.getOffset() << ":";
21570b57cec5SDimitry Andric if (NextStart)
21580b57cec5SDimitry Andric out << *NextStart << ">\n";
21590b57cec5SDimitry Andric else
21600b57cec5SDimitry Andric out << "???\?>\n";
21610b57cec5SDimitry Andric if (Entry.isFile()) {
21620b57cec5SDimitry Andric auto &FI = Entry.getFile();
21630b57cec5SDimitry Andric if (FI.NumCreatedFIDs)
21640b57cec5SDimitry Andric out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
21650b57cec5SDimitry Andric << ">\n";
21660b57cec5SDimitry Andric if (FI.getIncludeLoc().isValid())
21670b57cec5SDimitry Andric out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2168e8d8bef9SDimitry Andric auto &CC = FI.getContentCache();
2169e8d8bef9SDimitry Andric out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
21700b57cec5SDimitry Andric << "\n";
2171e8d8bef9SDimitry Andric if (CC.BufferOverridden)
21720b57cec5SDimitry Andric out << " contents overridden\n";
2173e8d8bef9SDimitry Andric if (CC.ContentsEntry != CC.OrigEntry) {
21740b57cec5SDimitry Andric out << " contents from "
2175e8d8bef9SDimitry Andric << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
21760b57cec5SDimitry Andric << "\n";
21770b57cec5SDimitry Andric }
21780b57cec5SDimitry Andric } else {
21790b57cec5SDimitry Andric auto &EI = Entry.getExpansion();
21800b57cec5SDimitry Andric out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
21810b57cec5SDimitry Andric out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
21820b57cec5SDimitry Andric << " range <" << EI.getExpansionLocStart().getOffset() << ":"
21830b57cec5SDimitry Andric << EI.getExpansionLocEnd().getOffset() << ">\n";
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric };
21860b57cec5SDimitry Andric
21870b57cec5SDimitry Andric // Dump local SLocEntries.
21880b57cec5SDimitry Andric for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
21890b57cec5SDimitry Andric DumpSLocEntry(ID, LocalSLocEntryTable[ID],
21900b57cec5SDimitry Andric ID == NumIDs - 1 ? NextLocalOffset
21910b57cec5SDimitry Andric : LocalSLocEntryTable[ID + 1].getOffset());
21920b57cec5SDimitry Andric }
21930b57cec5SDimitry Andric // Dump loaded SLocEntries.
2194bdd1243dSDimitry Andric std::optional<SourceLocation::UIntTy> NextStart;
21950b57cec5SDimitry Andric for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
21960b57cec5SDimitry Andric int ID = -(int)Index - 2;
21970b57cec5SDimitry Andric if (SLocEntryLoaded[Index]) {
21980b57cec5SDimitry Andric DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
21990b57cec5SDimitry Andric NextStart = LoadedSLocEntryTable[Index].getOffset();
22000b57cec5SDimitry Andric } else {
2201bdd1243dSDimitry Andric NextStart = std::nullopt;
22020b57cec5SDimitry Andric }
22030b57cec5SDimitry Andric }
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric
noteSLocAddressSpaceUsage(DiagnosticsEngine & Diag,std::optional<unsigned> MaxNotes) const2206bdd1243dSDimitry Andric void SourceManager::noteSLocAddressSpaceUsage(
2207bdd1243dSDimitry Andric DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {
2208bdd1243dSDimitry Andric struct Info {
2209bdd1243dSDimitry Andric // A location where this file was entered.
2210bdd1243dSDimitry Andric SourceLocation Loc;
2211bdd1243dSDimitry Andric // Number of times this FileEntry was entered.
2212bdd1243dSDimitry Andric unsigned Inclusions = 0;
2213bdd1243dSDimitry Andric // Size usage from the file itself.
2214bdd1243dSDimitry Andric uint64_t DirectSize = 0;
2215bdd1243dSDimitry Andric // Total size usage from the file and its macro expansions.
2216bdd1243dSDimitry Andric uint64_t TotalSize = 0;
2217bdd1243dSDimitry Andric };
2218bdd1243dSDimitry Andric using UsageMap = llvm::MapVector<const FileEntry*, Info>;
2219bdd1243dSDimitry Andric
2220bdd1243dSDimitry Andric UsageMap Usage;
2221bdd1243dSDimitry Andric uint64_t CountedSize = 0;
2222bdd1243dSDimitry Andric
2223bdd1243dSDimitry Andric auto AddUsageForFileID = [&](FileID ID) {
2224bdd1243dSDimitry Andric // The +1 here is because getFileIDSize doesn't include the extra byte for
2225bdd1243dSDimitry Andric // the one-past-the-end location.
2226bdd1243dSDimitry Andric unsigned Size = getFileIDSize(ID) + 1;
2227bdd1243dSDimitry Andric
2228bdd1243dSDimitry Andric // Find the file that used this address space, either directly or by
2229bdd1243dSDimitry Andric // macro expansion.
2230bdd1243dSDimitry Andric SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));
2231bdd1243dSDimitry Andric FileID FileLocID = getFileID(FileStart);
2232bdd1243dSDimitry Andric const FileEntry *Entry = getFileEntryForID(FileLocID);
2233bdd1243dSDimitry Andric
2234bdd1243dSDimitry Andric Info &EntryInfo = Usage[Entry];
2235bdd1243dSDimitry Andric if (EntryInfo.Loc.isInvalid())
2236bdd1243dSDimitry Andric EntryInfo.Loc = FileStart;
2237bdd1243dSDimitry Andric if (ID == FileLocID) {
2238bdd1243dSDimitry Andric ++EntryInfo.Inclusions;
2239bdd1243dSDimitry Andric EntryInfo.DirectSize += Size;
2240bdd1243dSDimitry Andric }
2241bdd1243dSDimitry Andric EntryInfo.TotalSize += Size;
2242bdd1243dSDimitry Andric CountedSize += Size;
2243bdd1243dSDimitry Andric };
2244bdd1243dSDimitry Andric
2245bdd1243dSDimitry Andric // Loaded SLocEntries have indexes counting downwards from -2.
2246bdd1243dSDimitry Andric for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2247bdd1243dSDimitry Andric AddUsageForFileID(FileID::get(-2 - Index));
2248bdd1243dSDimitry Andric }
2249bdd1243dSDimitry Andric // Local SLocEntries have indexes counting upwards from 0.
2250bdd1243dSDimitry Andric for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
2251bdd1243dSDimitry Andric AddUsageForFileID(FileID::get(Index));
2252bdd1243dSDimitry Andric }
2253bdd1243dSDimitry Andric
2254bdd1243dSDimitry Andric // Sort the usage by size from largest to smallest. Break ties by raw source
2255bdd1243dSDimitry Andric // location.
2256bdd1243dSDimitry Andric auto SortedUsage = Usage.takeVector();
2257bdd1243dSDimitry Andric auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {
2258bdd1243dSDimitry Andric return A.second.TotalSize > B.second.TotalSize ||
2259bdd1243dSDimitry Andric (A.second.TotalSize == B.second.TotalSize &&
2260bdd1243dSDimitry Andric A.second.Loc < B.second.Loc);
2261bdd1243dSDimitry Andric };
2262bdd1243dSDimitry Andric auto SortedEnd = SortedUsage.end();
2263bdd1243dSDimitry Andric if (MaxNotes && SortedUsage.size() > *MaxNotes) {
2264bdd1243dSDimitry Andric SortedEnd = SortedUsage.begin() + *MaxNotes;
2265bdd1243dSDimitry Andric std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);
2266bdd1243dSDimitry Andric }
2267bdd1243dSDimitry Andric std::sort(SortedUsage.begin(), SortedEnd, Cmp);
2268bdd1243dSDimitry Andric
2269bdd1243dSDimitry Andric // Produce note on sloc address space usage total.
2270bdd1243dSDimitry Andric uint64_t LocalUsage = NextLocalOffset;
2271bdd1243dSDimitry Andric uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
2272bdd1243dSDimitry Andric int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /
2273bdd1243dSDimitry Andric MaxLoadedOffset);
2274bdd1243dSDimitry Andric Diag.Report(SourceLocation(), diag::note_total_sloc_usage)
2275bdd1243dSDimitry Andric << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;
2276bdd1243dSDimitry Andric
2277bdd1243dSDimitry Andric // Produce notes on sloc address space usage for each file with a high usage.
2278bdd1243dSDimitry Andric uint64_t ReportedSize = 0;
2279bdd1243dSDimitry Andric for (auto &[Entry, FileInfo] :
2280bdd1243dSDimitry Andric llvm::make_range(SortedUsage.begin(), SortedEnd)) {
2281bdd1243dSDimitry Andric Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)
2282bdd1243dSDimitry Andric << FileInfo.Inclusions << FileInfo.DirectSize
2283bdd1243dSDimitry Andric << (FileInfo.TotalSize - FileInfo.DirectSize);
2284bdd1243dSDimitry Andric ReportedSize += FileInfo.TotalSize;
2285bdd1243dSDimitry Andric }
2286bdd1243dSDimitry Andric
2287bdd1243dSDimitry Andric // Describe any remaining usage not reported in the per-file usage.
2288bdd1243dSDimitry Andric if (ReportedSize != CountedSize) {
2289bdd1243dSDimitry Andric Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)
2290bdd1243dSDimitry Andric << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
2291bdd1243dSDimitry Andric }
2292bdd1243dSDimitry Andric }
2293bdd1243dSDimitry Andric
22940b57cec5SDimitry Andric ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
22950b57cec5SDimitry Andric
22960b57cec5SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down
22970b57cec5SDimitry Andric /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes() const22980b57cec5SDimitry Andric SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
22990b57cec5SDimitry Andric size_t malloc_bytes = 0;
23000b57cec5SDimitry Andric size_t mmap_bytes = 0;
23010b57cec5SDimitry Andric
23020b57cec5SDimitry Andric for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
23030b57cec5SDimitry Andric if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
23040b57cec5SDimitry Andric switch (MemBufferInfos[i]->getMemoryBufferKind()) {
23050b57cec5SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_MMap:
23060b57cec5SDimitry Andric mmap_bytes += sized_mapped;
23070b57cec5SDimitry Andric break;
23080b57cec5SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_Malloc:
23090b57cec5SDimitry Andric malloc_bytes += sized_mapped;
23100b57cec5SDimitry Andric break;
23110b57cec5SDimitry Andric }
23120b57cec5SDimitry Andric
23130b57cec5SDimitry Andric return MemoryBufferSizes(malloc_bytes, mmap_bytes);
23140b57cec5SDimitry Andric }
23150b57cec5SDimitry Andric
getDataStructureSizes() const23160b57cec5SDimitry Andric size_t SourceManager::getDataStructureSizes() const {
23175f757f3fSDimitry Andric size_t size = llvm::capacity_in_bytes(MemBufferInfos) +
23185f757f3fSDimitry Andric llvm::capacity_in_bytes(LocalSLocEntryTable) +
23195f757f3fSDimitry Andric llvm::capacity_in_bytes(LoadedSLocEntryTable) +
23205f757f3fSDimitry Andric llvm::capacity_in_bytes(SLocEntryLoaded) +
23215f757f3fSDimitry Andric llvm::capacity_in_bytes(FileInfos);
23220b57cec5SDimitry Andric
23230b57cec5SDimitry Andric if (OverriddenFilesInfo)
23240b57cec5SDimitry Andric size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
23250b57cec5SDimitry Andric
23260b57cec5SDimitry Andric return size;
23270b57cec5SDimitry Andric }
23280b57cec5SDimitry Andric
SourceManagerForFile(StringRef FileName,StringRef Content)23290b57cec5SDimitry Andric SourceManagerForFile::SourceManagerForFile(StringRef FileName,
23300b57cec5SDimitry Andric StringRef Content) {
23310b57cec5SDimitry Andric // This is referenced by `FileMgr` and will be released by `FileMgr` when it
23320b57cec5SDimitry Andric // is deleted.
23330b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
23340b57cec5SDimitry Andric new llvm::vfs::InMemoryFileSystem);
23350b57cec5SDimitry Andric InMemoryFileSystem->addFile(
23360b57cec5SDimitry Andric FileName, 0,
23370b57cec5SDimitry Andric llvm::MemoryBuffer::getMemBuffer(Content, FileName,
23380b57cec5SDimitry Andric /*RequiresNullTerminator=*/false));
23390b57cec5SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced
23400b57cec5SDimitry Andric // in `Environment` so that `FileMgr` can out-live this function scope.
23410b57cec5SDimitry Andric FileMgr =
2342a7dea167SDimitry Andric std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
23430b57cec5SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced
23440b57cec5SDimitry Andric // by `Environment` due to the same reason above.
2345a7dea167SDimitry Andric Diagnostics = std::make_unique<DiagnosticsEngine>(
23460b57cec5SDimitry Andric IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
23470b57cec5SDimitry Andric new DiagnosticOptions);
2348a7dea167SDimitry Andric SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
23495f757f3fSDimitry Andric FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName));
23505f757f3fSDimitry Andric FileID ID =
23515f757f3fSDimitry Andric SourceMgr->createFileID(FE, SourceLocation(), clang::SrcMgr::C_User);
23520b57cec5SDimitry Andric assert(ID.isValid());
23530b57cec5SDimitry Andric SourceMgr->setMainFileID(ID);
23540b57cec5SDimitry Andric }
2355