19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/Support/Allocator.h"
27#include "llvm/Support/AutoConvert.h"
28#include "llvm/Support/Capacity.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/Endian.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/VirtualFileSystem.h"
34#include "llvm/Support/raw_ostream.h"
47using llvm::MemoryBuffer;
49#define DEBUG_TYPE "source-manager"
55 Clone->ContentsEntry =
Other.ContentsEntry;
56 Clone->Filename =
Other.Filename;
57 Clone->BufferOverridden =
Other.BufferOverridden;
58 Clone->IsFileVolatile =
Other.IsFileVolatile;
59 Clone->IsTransient =
Other.IsTransient;
60 Clone->IsBufferInvalid =
Other.IsBufferInvalid;
61 Clone->setUnownedBuffer(
Other.getBufferIfLoaded());
67STATISTIC(MaxUsedSLocBytes,
"Maximum number of bytes used by source locations "
68 "(both loaded and local).");
77 return Buffer ? Buffer->getBufferSize() : 0;
83 if (Buffer ==
nullptr) {
84 assert(0 &&
"Buffer should never be null");
85 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
87 return Buffer->getBufferKind();
95 return Buffer ? (unsigned)Buffer->getBufferSize()
103 const char *InvalidBOM =
104 llvm::StringSwitch<const char *>(BufStr)
105 .StartsWith(llvm::StringLiteral::withInnerNUL(
"\x00\x00\xFE\xFF"),
107 .StartsWith(llvm::StringLiteral::withInnerNUL(
"\xFF\xFE\x00\x00"),
109 .StartsWith(
"\xFE\xFF",
"UTF-16 (BE)")
110 .StartsWith(
"\xFF\xFE",
"UTF-16 (LE)")
111 .StartsWith(
"\x2B\x2F\x76",
"UTF-7")
112 .StartsWith(
"\xF7\x64\x4C",
"UTF-1")
113 .StartsWith(
"\xDD\x73\x66\x73",
"UTF-EBCDIC")
114 .StartsWith(
"\x0E\xFE\xFF",
"SCSU")
115 .StartsWith(
"\xFB\xEE\x28",
"BOCU-1")
116 .StartsWith(
"\x84\x31\x95\x33",
"GB-18030")
122std::optional<llvm::MemoryBufferRef>
130 return Buffer->getMemBufferRef();
145 if (!BufferOrError) {
146 Diag.Report(Loc, diag::err_cannot_open_file)
147 <<
ContentsEntry->getName() << BufferOrError.getError().message();
152 Buffer = std::move(*BufferOrError);
163 if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
174 assert(Buffer->getBufferSize() >= (
size_t)
ContentsEntry->getSize());
176 Buffer->getBufferSize() < (
size_t)
ContentsEntry->getSize()) {
185 StringRef BufStr = Buffer->getBuffer();
189 Diag.Report(Loc, diag::err_unsupported_bom)
196 return Buffer->getMemBufferRef();
200 auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
202 FilenamesByID.push_back(&*IterBool.first);
203 return IterBool.first->second;
213 int FilenameID,
unsigned EntryExit,
215 std::vector<LineEntry> &Entries = LineEntries[FID];
217 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
218 "Adding line entries out of order!");
220 unsigned IncludeOffset = 0;
221 if (EntryExit == 1) {
223 IncludeOffset = Offset-1;
225 const auto *PrevEntry = Entries.empty() ?
nullptr : &Entries.back();
226 if (EntryExit == 2) {
228 assert(PrevEntry && PrevEntry->IncludeOffset &&
229 "PPDirectives should have caught case when popping empty include "
234 IncludeOffset = PrevEntry->IncludeOffset;
235 if (FilenameID == -1) {
238 FilenameID = PrevEntry->FilenameID;
243 Entries.push_back(
LineEntry::get(Offset, LineNo, FilenameID, FileKind,
251 const std::vector<LineEntry> &Entries = LineEntries[FID];
252 assert(!Entries.empty() &&
"No #line entries for this FID after all!");
256 if (Entries.back().FileOffset <= Offset)
257 return &Entries.back();
260 std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
261 if (I == Entries.begin())
269 const std::vector<LineEntry> &Entries) {
270 LineEntries[FID] = Entries;
282 int FilenameID,
bool IsFileEntry,
299 unsigned EntryExit = 0;
305 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
306 EntryExit, FileKind);
320 bool UserFilesAreVolatile)
321 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
323 Diag.setSourceManager(
this);
330 for (
unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
331 if (MemBufferInfos[i]) {
332 MemBufferInfos[i]->~ContentCache();
333 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
336 for (
auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
338 I->second->~ContentCache();
339 ContentCacheAlloc.Deallocate(I->second);
342 for (
unsigned i = 0, e = FileIDContentCaches.size(); i != e; ++i) {
343 if (FileIDContentCaches[i]) {
344 FileIDContentCaches[i]->~ContentCache();
345 ContentCacheAlloc.Deallocate(FileIDContentCaches[i]);
351 for (
unsigned i = 0, e = FileIDContentCaches.size(); i != e; ++i) {
352 if (FileIDContentCaches[i]) {
353 FileIDContentCaches[i]->~ContentCache();
354 ContentCacheAlloc.Deallocate(FileIDContentCaches[i]);
357 FileIDContentCaches.clear();
360 LocalSLocEntryTable.clear();
361 LocalLocOffsetTable.clear();
362 LoadedSLocEntryTable.clear();
363 SLocEntryLoaded.clear();
364 SLocEntryOffsetLoaded.clear();
365 LastLineNoFileIDQuery =
FileID();
366 LastLineNoContentCache =
nullptr;
367 LastFileIDLookup =
FileID();
368 LastLookupStartOffset = LastLookupEndOffset = 0;
370 IncludedLocMap.clear();
376 CurrentLoadedOffset = MaxLoadedOffset;
384 assert(MainFileID.isValid() &&
"expected initialized SourceManager");
386 return FE->getUID() == SourceFile.
getUID();
391 assert(MainFileID.isInvalid() &&
"expected uninitialized SourceManager");
394 for (
unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
395 if (!Old.SLocEntryLoaded[I])
396 Old.loadSLocEntry(I,
nullptr);
399 for (
auto &
FileInfo : Old.FileInfos) {
417 if (OverriddenFilesInfo) {
420 auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
421 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
424 new (Entry)
ContentCache(OverridenFilesKeepOriginalName ? FileEnt
440ContentCache &SourceManager::createMemBufferContentCache(
441 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
443 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
444 new (Entry) ContentCache();
445 MemBufferInfos.push_back(Entry);
456 assert(!SLocEntryLoaded[Index]);
457 if (ExternalSLocEntries->ReadSLocEntry(-(
static_cast<int>(Index) + 2))) {
461 if (!SLocEntryLoaded[Index]) {
463 if (!FakeSLocEntryForRecovery)
464 FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(
SLocEntry::get(
465 0,
FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
467 return *FakeSLocEntryForRecovery;
471 return LoadedSLocEntryTable[Index];
474std::pair<int, SourceLocation::UIntTy>
477 assert(ExternalSLocEntries &&
"Don't have an external sloc source");
479 if (CurrentLoadedOffset < TotalSize ||
480 CurrentLoadedOffset - TotalSize < NextLocalOffset) {
481 return std::make_pair(0, 0);
483 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
484 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
485 SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());
486 CurrentLoadedOffset -= TotalSize;
487 updateSlocUsageStats();
488 int BaseID = -
int(LoadedSLocEntryTable.size()) - 1;
489 LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));
490 return std::make_pair(BaseID, CurrentLoadedOffset);
495llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery()
const {
496 if (!FakeBufferForRecovery)
497 FakeBufferForRecovery =
498 llvm::MemoryBuffer::getMemBuffer(
"<<<INVALID BUFFER>>");
500 return *FakeBufferForRecovery;
506 if (!FakeContentCacheForRecovery) {
507 FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
508 FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
510 return *FakeContentCacheForRecovery;
515FileID SourceManager::getPreviousFileID(
FileID FID)
const {
526 }
else if (
unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
530 return FileID::get(ID-1);
543 }
else if (ID+1 >= -1) {
547 return FileID::get(ID+1);
564 StringRef Filename = SourceFile.
getName();
568 Cache->OrigEntry = SourceFile;
569 FileIDContentCaches.push_back(
Cache);
574 if (
Cache->ContentsEntry->isNamedPipe())
577 return createFileIDImpl(*
Cache, Filename, IncludePos, FileCharacter, LoadedID,
590 StringRef Name = Buffer->getBufferIdentifier();
591 return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
592 IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
604 return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
605 LoadedID, LoadedOffset, IncludeLoc);
627 assert(LoadedID != -1 &&
"Loading sentinel FileID");
628 unsigned Index =
unsigned(-LoadedID) - 2;
629 assert(Index < LoadedSLocEntryTable.size() &&
"FileID out of range");
630 assert(!SLocEntryLoaded[Index] &&
"FileID already loaded");
633 SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] =
true;
634 return FileID::get(LoadedID);
636 unsigned FileSize =
File.getSize();
637 llvm::ErrorOr<bool> NeedConversion = llvm::needConversion(Filename);
638 if (NeedConversion && *NeedConversion) {
641 if (std::optional<llvm::MemoryBufferRef> Buffer =
643 unsigned BufSize = Buffer->getBufferSize();
644 if (BufSize > FileSize) {
645 if (
File.ContentsEntry.has_value())
646 File.ContentsEntry->updateFileEntryBufferSize(BufSize);
651 if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
652 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
653 Diag.Report(IncludePos, diag::err_sloc_space_too_large);
657 assert(LocalSLocEntryTable.size() == LocalLocOffsetTable.size());
658 LocalSLocEntryTable.push_back(
661 LocalLocOffsetTable.push_back(NextLocalOffset);
662 LastLookupStartOffset = NextLocalOffset;
665 NextLocalOffset += FileSize + 1;
666 LastLookupEndOffset = NextLocalOffset;
667 updateSlocUsageStats();
671 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
672 return LastFileIDLookup = FID;
679 return createExpansionLocImpl(Info, Length);
685 bool ExpansionIsTokenRange,
int LoadedID,
688 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
689 return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
696 "token spans multiple files");
697 return createExpansionLocImpl(
699 TokenEnd.getOffset() - TokenStart.getOffset());
703SourceManager::createExpansionLocImpl(
const ExpansionInfo &Info,
704 unsigned Length,
int LoadedID,
707 assert(LoadedID != -1 &&
"Loading sentinel FileID");
708 unsigned Index =
unsigned(-LoadedID) - 2;
709 assert(Index < LoadedSLocEntryTable.size() &&
"FileID out of range");
710 assert(!SLocEntryLoaded[Index] &&
"FileID already loaded");
712 SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] =
true;
713 return SourceLocation::getMacroLoc(LoadedOffset);
715 assert(LocalSLocEntryTable.size() == LocalLocOffsetTable.size());
716 LocalSLocEntryTable.push_back(
SLocEntry::get(NextLocalOffset, Info));
717 LocalLocOffsetTable.push_back(NextLocalOffset);
718 if (NextLocalOffset + Length + 1 <= NextLocalOffset ||
719 NextLocalOffset + Length + 1 > CurrentLoadedOffset) {
720 Diag.Report(diag::err_sloc_space_too_large);
726 llvm::report_fatal_error(
"ran out of source locations");
729 NextLocalOffset += Length + 1;
730 updateSlocUsageStats();
731 return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
734std::optional<llvm::MemoryBufferRef>
741 FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
747 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
753 "Different sizes, use the FileManager to create a virtual file with "
755 assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&
756 "This function should be called at the initialization stage, before "
757 "any parsing occurs.");
759 auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
760 std::make_pair(SourceFile, NewFile));
762 Pair.first->second = NewFile;
774 (void)getOrCreateContentCache(*BypassFile);
779 getOrCreateContentCache(
File).IsTransient =
true;
782std::optional<StringRef>
785 if (Entry->getFile().getContentCache().
OrigEntry)
786 return Entry->getFile().getName();
794 return B ? *B :
"<<<<<INVALID SOURCE LOCATION>>>>>";
797std::optional<StringRef>
808 return B->getBuffer();
823 return FileID::get(0);
827 if (SLocOffset < NextLocalOffset)
828 return getFileIDLocal(SLocOffset);
829 return getFileIDLoaded(SLocOffset);
837 assert(SLocOffset < NextLocalOffset &&
"Bad function choice");
838 assert(SLocOffset >= LocalSLocEntryTable[0].getOffset() && SLocOffset > 0 &&
839 "Invalid SLocOffset");
840 assert(LocalSLocEntryTable.size() == LocalLocOffsetTable.size());
841 assert(LastFileIDLookup.ID >= 0 &&
"Only cache local file sloc entry");
858 unsigned LessIndex = 0;
860 unsigned GreaterIndex = LocalLocOffsetTable.size();
862 if (LastLookupStartOffset < SLocOffset)
863 LessIndex = LastFileIDLookup.ID;
865 GreaterIndex = LastFileIDLookup.ID;
868 unsigned NumProbes = 0;
871 assert(GreaterIndex < LocalLocOffsetTable.size());
872 if (LocalLocOffsetTable[GreaterIndex] <= SLocOffset) {
873 FileID Res = FileID::get(
int(GreaterIndex));
875 LastFileIDLookup = Res;
876 LastLookupStartOffset = LocalLocOffsetTable[GreaterIndex];
877 LastLookupEndOffset =
878 GreaterIndex + 1 >= LocalLocOffsetTable.size()
880 : LocalLocOffsetTable[GreaterIndex + 1];
881 NumLinearScans += NumProbes + 1;
884 if (++NumProbes == 8)
888 while (LessIndex < GreaterIndex) {
891 unsigned MiddleIndex = LessIndex + (GreaterIndex - LessIndex) / 2;
892 if (LocalLocOffsetTable[MiddleIndex] <= SLocOffset)
893 LessIndex = MiddleIndex + 1;
895 GreaterIndex = MiddleIndex;
901 LastLookupStartOffset = LocalLocOffsetTable[LessIndex - 1];
902 LastLookupEndOffset = LocalLocOffsetTable[LessIndex];
903 return LastFileIDLookup = FileID::get(LessIndex - 1);
911 if (SLocOffset < CurrentLoadedOffset) {
912 assert(0 &&
"Invalid SLocOffset or bad function choice");
916 return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));
944 unsigned MaxDepth)
const {
947 if (Depth++ == MaxDepth)
948 return SourceLocation();
983 assert(Loc.
isMacroID() &&
"Not a macro expansion loc!");
1040 if (DecompLoc.second > 0)
1054 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1066 *MacroBegin = ExpLoc;
1089 FileID NextFID = getNextFileID(FID);
1119 bool CharDataInvalid =
false;
1121 if (CharDataInvalid || !Entry.
isFile()) {
1125 return "<<<<INVALID BUFFER>>>>";
1127 std::optional<llvm::MemoryBufferRef> Buffer =
1132 return Buffer ? Buffer->getBufferStart() + LocInfo.second
1133 :
"<<<<INVALID BUFFER>>>>";
1148 if (FilePos > MemBuf->getBufferSize()) {
1154 const char *Buf = MemBuf->getBufferStart();
1157 if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1158 LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1159 const unsigned *SourceLineCache =
1160 LastLineNoContentCache->SourceLineCache.begin();
1161 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1162 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1163 if (FilePos >= LineStart && FilePos < LineEnd) {
1168 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1169 if (Buf[FilePos - 1] ==
'\r' || Buf[FilePos - 1] ==
'\n')
1172 return (FilePos - LineStart) + 1;
1176 unsigned LineStart = FilePos;
1177 while (LineStart && Buf[LineStart-1] !=
'\n' && Buf[LineStart-1] !=
'\r')
1179 return (FilePos - LineStart) + 1;
1184template<
typename LocType>
1186 bool MyInvalid = Loc.isInvalid();
1214 return ((x - ~
static_cast<T
>(0) / 255 * (n + 1)) & ~x &
1215 ((x & ~
static_cast<T
>(0) / 255 * 127) +
1216 (~
static_cast<T
>(0) / 255 * (127 - (m - 1))))) &
1217 ~static_cast<T>(0) / 255 * 128;
1221 llvm::BumpPtrAllocator &Alloc) {
1228 LineOffsets.push_back(0);
1230 const unsigned char *Start = (
const unsigned char *)Buffer.getBufferStart();
1231 const unsigned char *End = (
const unsigned char *)Buffer.getBufferEnd();
1232 const unsigned char *Buf = Start;
1238 if ((
unsigned long)(End - Start) >
sizeof(Word)) {
1240 Word = llvm::support::endian::read64(Buf, llvm::endianness::little);
1244 Buf +=
sizeof(Word);
1252 unsigned N = llvm::countr_zero(Mask) - 7;
1255 unsigned char Byte = Word;
1264 LineOffsets.push_back(Buf - Start);
1266 }
while (Buf < End -
sizeof(Word) - 1);
1272 LineOffsets.push_back(Buf - Start + 1);
1273 }
else if (*Buf ==
'\r') {
1275 if (Buf + 1 < End && Buf[1] ==
'\n') {
1278 LineOffsets.push_back(Buf - Start + 1);
1287 llvm::BumpPtrAllocator &Alloc)
1288 : Storage(Alloc.Allocate<unsigned>(LineOffsets.
size() + 1)) {
1289 Storage[0] = LineOffsets.size();
1290 std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1306 if (LastLineNoFileIDQuery == FID)
1307 Content = LastLineNoContentCache;
1309 bool MyInvalid =
false;
1311 if (MyInvalid || !Entry.
isFile()) {
1323 std::optional<llvm::MemoryBufferRef> Buffer =
1338 const unsigned *SourceLineCacheStart = SourceLineCache;
1341 unsigned QueriedFilePos = FilePos+1;
1356 if (LastLineNoFileIDQuery == FID) {
1357 if (QueriedFilePos >= LastLineNoFilePos) {
1359 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1365 if (SourceLineCache+5 < SourceLineCacheEnd) {
1366 if (SourceLineCache[5] > QueriedFilePos)
1367 SourceLineCacheEnd = SourceLineCache+5;
1368 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1369 if (SourceLineCache[10] > QueriedFilePos)
1370 SourceLineCacheEnd = SourceLineCache+10;
1371 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1372 if (SourceLineCache[20] > QueriedFilePos)
1373 SourceLineCacheEnd = SourceLineCache+20;
1378 if (LastLineNoResult < Content->SourceLineCache.size())
1379 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1383 const unsigned *Pos =
1384 std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1385 unsigned LineNo = Pos-SourceLineCacheStart;
1387 LastLineNoFileIDQuery = FID;
1388 LastLineNoContentCache = Content;
1389 LastLineNoFilePos = QueriedFilePos;
1390 LastLineNoResult = LineNo;
1418 assert(Loc.
isValid() &&
"Can't get file characteristic of invalid loc!");
1420 const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1431 assert(LineTable &&
"Can't have linetable entries without a LineTable!");
1434 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1453 return B ? B->getBufferIdentifier() :
"<invalid buffer>";
1464 bool UseLineDirectives)
const {
1481 FileID FID = LocInfo.first;
1484 Filename =
C->OrigEntry->getName();
1486 Filename = Buffer->getBufferIdentifier();
1500 assert(LineTable &&
"Can't have linetable entries without a LineTable!");
1503 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1505 if (Entry->FilenameID != -1) {
1506 Filename = LineTable->getFilename(Entry->FilenameID);
1509 FID = FileID::get(0);
1516 unsigned MarkerLineNo =
getLineNumber(LocInfo.first, Entry->FileOffset);
1517 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1522 if (Entry->IncludeOffset) {
1529 return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1545 const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1554 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1555 if (Entry->IncludeOffset)
1572 else if (ID+1 == -1)
1573 NextOffset = MaxLoadedOffset;
1575 NextOffset =
getSLocEntry(FileID::get(ID+1)).getOffset();
1577 return NextOffset - Entry.
getOffset() - 1;
1590 unsigned Col)
const {
1591 assert(SourceFile &&
"Null source file!");
1592 assert(
Line && Col &&
"Line and column should start from 1!");
1603 assert(SourceFile &&
"Null source file!");
1607 if (MainFileID.isValid()) {
1625 return FileID::get(I);
1633 return FileID::get(-
int(I) - 2);
1643 unsigned Col)
const {
1646 assert(
Line && Col &&
"Line and column should start from 1!");
1661 if (
Line == 1 && Col == 1)
1668 std::optional<llvm::MemoryBufferRef> Buffer =
1677 unsigned Size = Buffer->getBufferSize();
1684 const char *Buf = Buffer->getBufferStart() + FilePos;
1685 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1692 while (i < BufLength-1 && i < Col-1 && Buf[i] !=
'\n' && Buf[i] !=
'\r')
1704void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1709 MacroArgsCache.try_emplace(0);
1715 MacroArgFileChunksMap ChunksByFileID;
1722 if (
unsigned(ID) >= local_sloc_entry_size())
1724 }
else if (ID == -1) {
1729 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &
Invalid);
1739 bool IncludedInFID =
1740 (IncludeLoc.
isValid() && isInFileID(IncludeLoc, FID)) ||
1744 (FID == MainFileID && Entry.
getFile().
getName() ==
"<built-in>");
1745 if (IncludedInFID) {
1748 if (Entry.
getFile().NumCreatedFIDs)
1749 ID += Entry.
getFile().NumCreatedFIDs - 1 ;
1769 SourceLocation ExpansionLoc =
1770 SourceLocation::getMacroLoc(Entry.
getOffset());
1771 for (
const MacroArgFileChunk &Chunk :
1772 getMacroArgFileChunks(ChunksByFileID, FID, FileID::get(ID))) {
1773 unsigned BeginOffs = Chunk.FileOffset;
1774 unsigned EndOffs = BeginOffs + Chunk.Length;
1792 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1794 SourceLocation EndOffsMappedLoc = I->second;
1795 MacroArgsCache[BeginOffs] =
1797 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1802const SourceManager::MacroArgFileChunks &
1803SourceManager::getMacroArgFileChunks(MacroArgFileChunksMap &ChunksByFileID,
1804 FileID FID, FileID MacroArgFID)
const {
1805 auto It = ChunksByFileID.find(MacroArgFID.ID);
1806 if (It != ChunksByFileID.end())
1810 MacroArgFileChunks Chunks = computeMacroArgFileChunks(
1811 ChunksByFileID, FID,
1812 getSLocEntry(MacroArgFID).getExpansion().getSpellingLoc(),
1813 getFileIDSize(MacroArgFID));
1814 return ChunksByFileID.try_emplace(MacroArgFID.ID, std::move(Chunks))
1818SourceManager::MacroArgFileChunks
1819SourceManager::computeMacroArgFileChunks(MacroArgFileChunksMap &ChunksByFileID,
1820 FileID FID, SourceLocation SpellLoc,
1821 unsigned Length)
const {
1822 MacroArgFileChunks Chunks;
1824 unsigned FileOffset;
1825 if (isInFileID(SpellLoc, FID, &FileOffset))
1826 Chunks.push_back({0, FileOffset, Length});
1839 auto [SpellFID, SpellRelativeOffs] = getDecomposedLoc(SpellLoc);
1840 unsigned ExpansionOffset = 0;
1842 const SLocEntry &Entry = getSLocEntry(SpellFID);
1844 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1847 unsigned CurrSpellLength;
1848 if (SpellFIDEndOffs < SpellEndOffs)
1849 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1851 CurrSpellLength = Length;
1852 unsigned RangeBegin = SpellRelativeOffs;
1853 unsigned RangeEnd = SpellRelativeOffs + CurrSpellLength;
1854 for (
const MacroArgFileChunk &Chunk :
1855 getMacroArgFileChunks(ChunksByFileID, FID, SpellFID)) {
1856 unsigned Begin = std::max(Chunk.ExpansionOffset, RangeBegin);
1857 unsigned End = std::min(Chunk.ExpansionOffset + Chunk.Length, RangeEnd);
1860 Chunks.push_back({ExpansionOffset + (Begin - RangeBegin),
1861 Chunk.FileOffset + (Begin - Chunk.ExpansionOffset),
1866 if (SpellFIDEndOffs >= SpellEndOffs)
1870 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1874 SpellRelativeOffs = 0;
1878void SourceManager::updateSlocUsageStats()
const {
1880 NextLocalOffset + (MaxLoadedOffset - CurrentLoadedOffset);
1881 MaxUsedSLocBytes.updateMax(UsedBytes);
1902 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1903 if (!MacroArgsCache) {
1904 MacroArgsCache = std::make_unique<MacroArgsMap>();
1905 computeMacroArgsCache(*MacroArgsCache, FID);
1908 assert(!MacroArgsCache->empty());
1909 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1912 if (I == MacroArgsCache->begin())
1919 if (MacroArgExpandedLoc.
isValid())
1927 return std::make_pair(
FileID(), 0);
1932 auto InsertOp = IncludedLocMap.try_emplace(FID);
1933 DecompTy &DecompLoc = InsertOp.first->second;
1934 if (!InsertOp.second)
1955 "Must be a source location in a loaded PCH/Module file");
1963 llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, std::greater<FileID>{});
1966 "The failure to find the first FileID of a "
1967 "loaded AST from a loaded source location was unexpected.");
1978 auto FindSLocEntryAlloc = [
this](
FileID FID) {
1981 return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID,
1982 std::greater<FileID>{});
1986 if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first))
2000 if (UpperLoc.first.isInvalid() ||
2010InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2011 FileID RFID)
const {
2016 enum { MagicCacheSize = 300 };
2017 IsBeforeInTUCacheKey Key(LFID, RFID);
2023 if (IBTUCache.size() < MagicCacheSize)
2024 return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
2027 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2028 if (I != IBTUCache.end())
2032 IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
2033 return IBTUCacheOverflow;
2041 assert(LHS.
isValid() && RHS.
isValid() &&
"Passed invalid source location!");
2051 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2052 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2056 return InSameTU.second;
2058 return LOffs.first < ROffs.first;
2061std::pair<bool, bool>
2066 return std::make_pair(
false,
false);
2069 if (LOffs.first == ROffs.first)
2070 return std::make_pair(
true, LOffs.second < ROffs.second);
2075 getInBeforeInTUCache(LOffs.first, ROffs.first);
2080 return std::make_pair(
2093 llvm::SmallDenseMap<FileID, Entry, 16> LChain;
2097 LChain.try_emplace(LOffs.first, Entry{LOffs, LChild});
2100 if (LOffs.first == ROffs.first)
2102 LChild = LOffs.first;
2107 auto LIt = LChain.find(ROffs.first);
2108 if (LIt != LChain.end()) {
2110 LOffs = LIt->second.DecomposedLoc;
2111 LChild = LIt->second.ChildFID;
2120 unsigned LChildID = LChild.ID;
2121 unsigned RChildID = RChild.ID;
2122 assert(((LOffs.second != ROffs.second) ||
2123 (LChildID == 0 || RChildID == 0) ||
2126 "Mixed local/loaded FileIDs with same include location?");
2127 IsBeforeInTUCache.
setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
2128 LChildID < RChildID);
2129 return std::make_pair(
2132 RChild = ROffs.first;
2141 bool LIsBuiltins = LB ==
"<built-in>";
2142 bool RIsBuiltins = RB ==
"<built-in>";
2144 if (LIsBuiltins || RIsBuiltins) {
2145 if (LIsBuiltins != RIsBuiltins)
2146 return std::make_pair(
true, LIsBuiltins);
2149 return std::make_pair(
true, LOffs.first < ROffs.first);
2152 bool LIsAsm = LB ==
"<inline asm>";
2153 bool RIsAsm = RB ==
"<inline asm>";
2155 if (LIsAsm || RIsAsm) {
2156 if (LIsAsm != RIsAsm)
2157 return std::make_pair(
true, RIsAsm);
2158 assert(LOffs.first == ROffs.first);
2159 return std::make_pair(
true,
false);
2162 bool LIsScratch = LB ==
"<scratch space>";
2163 bool RIsScratch = RB ==
"<scratch space>";
2165 if (LIsScratch || RIsScratch) {
2166 if (LIsScratch != RIsScratch)
2167 return std::make_pair(
true, LIsScratch);
2168 return std::make_pair(
true, LOffs.second < ROffs.second);
2171 llvm_unreachable(
"Unsortable locations found");
2175 llvm::errs() <<
"\n*** Source Manager Stats:\n";
2176 llvm::errs() << FileInfos.size() <<
" files mapped, " << MemBufferInfos.size()
2177 <<
" mem buffers mapped.\n";
2178 llvm::errs() << LocalSLocEntryTable.size() <<
" local SLocEntries allocated ("
2179 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2180 <<
" bytes of capacity), " << NextLocalOffset
2181 <<
"B of SLoc address space used.\n";
2182 llvm::errs() << LoadedSLocEntryTable.size()
2183 <<
" loaded SLocEntries allocated ("
2184 << llvm::capacity_in_bytes(LoadedSLocEntryTable)
2185 <<
" bytes of capacity), "
2186 << MaxLoadedOffset - CurrentLoadedOffset
2187 <<
"B of SLoc address space used.\n";
2189 unsigned NumLineNumsComputed = 0;
2190 unsigned NumFileBytesMapped = 0;
2192 NumLineNumsComputed +=
bool(I->second->SourceLineCache);
2193 NumFileBytesMapped += I->second->getSizeBytesMapped();
2195 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2197 llvm::errs() << NumFileBytesMapped <<
" bytes of files mapped, "
2198 << NumLineNumsComputed <<
" files with line #'s computed, "
2199 << NumMacroArgsComputed <<
" files with macro args computed.\n";
2200 llvm::errs() <<
"FileID scans: " << NumLinearScans <<
" linear, "
2201 << NumBinaryProbes <<
" binary.\n";
2205 llvm::raw_ostream &
out = llvm::errs();
2208 std::optional<SourceLocation::UIntTy> NextStart) {
2209 out <<
"SLocEntry <FileID " << ID <<
"> " << (Entry.isFile() ?
"file" :
"expansion")
2210 <<
" <SourceLocation " << Entry.getOffset() <<
":";
2212 out << *NextStart <<
">\n";
2215 if (Entry.isFile()) {
2216 auto &FI = Entry.getFile();
2217 if (FI.NumCreatedFIDs)
2218 out <<
" covers <FileID " << ID <<
":" <<
int(ID + FI.NumCreatedFIDs)
2220 if (FI.getIncludeLoc().isValid())
2221 out <<
" included from " << FI.getIncludeLoc().getOffset() <<
"\n";
2222 auto &CC = FI.getContentCache();
2223 out <<
" for " << (CC.OrigEntry ? CC.OrigEntry->getName() :
"<none>")
2225 if (CC.BufferOverridden)
2226 out <<
" contents overridden\n";
2227 if (CC.ContentsEntry != CC.OrigEntry) {
2228 out <<
" contents from "
2229 << (CC.ContentsEntry ? CC.ContentsEntry->getName() :
"<none>")
2233 auto &EI = Entry.getExpansion();
2234 out <<
" spelling from " << EI.getSpellingLoc().getOffset() <<
"\n";
2235 out <<
" macro " << (EI.isMacroArgExpansion() ?
"arg" :
"body")
2236 <<
" range <" << EI.getExpansionLocStart().getOffset() <<
":"
2237 << EI.getExpansionLocEnd().getOffset() <<
">\n";
2242 for (
unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2243 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2244 ID == NumIDs - 1 ? NextLocalOffset
2245 : LocalSLocEntryTable[ID + 1].getOffset());
2248 std::optional<SourceLocation::UIntTy> NextStart;
2249 for (
unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2250 int ID = -(int)Index - 2;
2251 if (SLocEntryLoaded[Index]) {
2252 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2253 NextStart = LoadedSLocEntryTable[Index].getOffset();
2255 NextStart = std::nullopt;
2266 unsigned Inclusions = 0;
2268 uint64_t DirectSize = 0;
2270 uint64_t TotalSize = 0;
2272 using UsageMap = llvm::MapVector<const FileEntry*, Info>;
2275 uint64_t CountedSize = 0;
2277 auto AddUsageForFileID = [&](
FileID ID) {
2288 Info &EntryInfo = Usage[Entry];
2289 if (EntryInfo.Loc.isInvalid())
2290 EntryInfo.Loc = FileStart;
2291 if (ID == FileLocID) {
2292 ++EntryInfo.Inclusions;
2293 EntryInfo.DirectSize += Size;
2295 EntryInfo.TotalSize += Size;
2296 CountedSize += Size;
2300 for (
size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2301 AddUsageForFileID(FileID::get(-2 - Index));
2304 for (
size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
2305 AddUsageForFileID(FileID::get(Index));
2310 auto SortedUsage = Usage.takeVector();
2311 auto Cmp = [](
const UsageMap::value_type &A,
const UsageMap::value_type &B) {
2312 return A.second.TotalSize > B.second.TotalSize ||
2313 (A.second.TotalSize == B.second.TotalSize &&
2314 A.second.Loc < B.second.Loc);
2316 auto SortedEnd = SortedUsage.end();
2317 if (MaxNotes && SortedUsage.size() > *MaxNotes) {
2318 SortedEnd = SortedUsage.begin() + *MaxNotes;
2319 std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(),
Cmp);
2321 std::sort(SortedUsage.begin(), SortedEnd,
Cmp);
2324 uint64_t LocalUsage = NextLocalOffset;
2325 uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
2326 int UsagePercent =
static_cast<int>(100.0 *
double(LocalUsage + LoadedUsage) /
2328 Diag.Report(diag::note_total_sloc_usage)
2329 << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage)
2333 uint64_t ReportedSize = 0;
2335 llvm::make_range(SortedUsage.begin(), SortedEnd)) {
2336 Diag.Report(
FileInfo.Loc, diag::note_file_sloc_usage)
2339 ReportedSize +=
FileInfo.TotalSize;
2343 if (ReportedSize != CountedSize) {
2344 Diag.Report(diag::note_file_misc_sloc_usage)
2345 << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
2354 size_t malloc_bytes = 0;
2355 size_t mmap_bytes = 0;
2357 for (
unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2358 if (
size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2359 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2360 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2361 mmap_bytes += sized_mapped;
2363 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2364 malloc_bytes += sized_mapped;
2372 size_t size = llvm::capacity_in_bytes(MemBufferInfos) +
2373 llvm::capacity_in_bytes(FileIDContentCaches) +
2374 llvm::capacity_in_bytes(LocalSLocEntryTable) +
2375 llvm::capacity_in_bytes(LoadedSLocEntryTable) +
2376 llvm::capacity_in_bytes(SLocEntryLoaded) +
2377 llvm::capacity_in_bytes(FileInfos);
2379 if (OverriddenFilesInfo)
2380 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2386 StringRef Content) {
2387 auto InMemoryFileSystem =
2388 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
2389 InMemoryFileSystem->addFile(
2391 llvm::MemoryBuffer::getMemBuffer(Content,
FileName,
2396 std::move(InMemoryFileSystem));
2397 DiagOpts = std::make_unique<DiagnosticOptions>();
2402 SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2406 assert(ID.isValid());
2407 SourceMgr->setMainFileID(ID);
Defines the Diagnostic-related interfaces.
Defines the clang::FileManager interface and associated types.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static ParseState advance(ParseState S, size_t N)
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
static constexpr T likelyhasbetween(T x, unsigned char m, unsigned char n)
static bool isInvalid(LocType Loc, bool *Invalid)
STATISTIC(MaxUsedSLocBytes, "Maximum number of bytes used by source locations " "(both loaded and local).")
static bool MoveUpTranslationUnitIncludeHierarchy(FileIDAndOffset &Loc, const SourceManager &SM)
Given a decomposed source location, move it up the include/expansion stack to the parent source locat...
static SrcMgr::ContentCache * cloneContentCache(llvm::BumpPtrAllocator &Alloc, const ContentCache &Other)
Defines the SourceManager interface.
Represents a byte-granular source range.
void setEnd(SourceLocation e)
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
void setBegin(SourceLocation b)
SourceLocation getEnd() const
SourceLocation getBegin() const
void setTokenRange(bool TR)
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Concrete class used by the front-end to report problems and issues.
virtual ~ExternalSLocEntrySource()
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
bool isSameRef(const FileEntryRef &RHS) const
Check if RHS referenced the file in exactly the same way.
StringRef getName() const
The name of this FileEntry.
Cached information about one file (either on disk or in the virtual file system).
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Keeps track of options that affect how file operations are performed.
Holds the cache used by isBeforeInTranslationUnit.
void setCommonLoc(FileID commonFID, unsigned lCommonOffset, unsigned rCommonOffset, bool LParentBeforeRParent)
bool getCachedResult(unsigned LOffset, unsigned ROffset) const
If the cache is valid, compute the result given the specified offsets in the LHS/RHS FileID's.
bool isCacheValid() const
Return true if the currently cached values match up with the specified LHS/RHS query.
Used to hold and unique data used to represent #line information.
const LineEntry * FindNearestLineEntry(FileID FID, unsigned Offset)
Find the line entry nearest to FID that is before it.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
void AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, int FilenameID, unsigned EntryExit, SrcMgr::CharacteristicKind FileKind)
Add a line note to the line table that indicates that there is a #line or GNU line marker at the spec...
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
unsigned getLine() const
Return the presumed line number of this location.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
SourceManagerForFile(StringRef FileName, StringRef Content)
Creates SourceManager and necessary dependencies (e.g.
This class handles loading and caching of source files into memory.
std::optional< StringRef > getNonBuiltinFilenameForID(FileID FID) const
Returns the filename for the provided FileID, unless it's a built-in buffer that's not represented by...
FileIDAndOffset getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
bool isAtEndOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroEnd=nullptr) const
Returns true if the given MacroID location points at the character end of the immediate macro expansi...
SourceLocation::UIntTy getNextLocalOffset() const
unsigned getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Return the column # for the specified file position.
void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag, std::optional< unsigned > MaxNotes=32) const
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, bool IsFileEntry, bool IsFileExit, SrcMgr::CharacteristicKind FileKind)
Add a line note to the line table for the FileID and offset specified by Loc.
SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr, bool UserFilesAreVolatile=false)
SourceLocation createTokenSplitLoc(SourceLocation SpellingLoc, SourceLocation TokenStart, SourceLocation TokenEnd)
Return a new SourceLocation that encodes that the token starting at TokenStart ends prematurely at To...
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
bool isInTheSameTranslationUnitImpl(const FileIDAndOffset &LOffs, const FileIDAndOffset &ROffs) const
Determines whether the two decomposed source location is in the same TU.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
void setFileIsTransient(FileEntryRef SourceFile)
Specify that a file is transient.
bool isFileOverridden(const FileEntry *File) const
Returns true if the file contents have been overridden.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation translateLineCol(FileID FID, unsigned Line, unsigned Col) const
Get the source location in FID for the given line:col.
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
std::optional< StringRef > getBufferDataOrNone(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning std::nullopt if inva...
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
void PrintStats() const
Print statistics to stderr.
FileID getUniqueLoadedASTFileID(SourceLocation Loc) const
bool isMainFile(const FileEntry &SourceFile)
Returns true when the given FileEntry corresponds to the main file.
size_t getDataStructureSizes() const
Return the amount of memory used for various side tables and data structures in the SourceManager.
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
const SrcMgr::SLocEntry & getLocalSLocEntry(unsigned Index) const
Get a local SLocEntry. This is exposed for indexing.
SourceLocation getComposedLoc(FileID FID, unsigned Offset) const
Form a SourceLocation from a FileID and Offset pair.
OptionalFileEntryRef bypassFileContentsOverride(FileEntryRef File)
Bypass the overridden contents of a file.
const SrcMgr::SLocEntry & getLoadedSLocEntry(unsigned Index, bool *Invalid=nullptr) const
Get a loaded SLocEntry. This is exposed for indexing.
llvm::DenseMap< FileEntryRef, SrcMgr::ContentCache * >::const_iterator fileinfo_iterator
FileManager & getFileManager() const
fileinfo_iterator fileinfo_end() const
unsigned local_sloc_entry_size() const
Get the number of local SLocEntries we have.
std::optional< StringRef > getBufferDataIfLoaded(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning std::nullopt if it's...
FileIDAndOffset getDecomposedSpellingLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
std::pair< int, SourceLocation::UIntTy > AllocateLoadedSLocEntries(unsigned NumSLocEntries, SourceLocation::UIntTy TotalSize)
Allocate a number of loaded SLocEntries, which will be actually loaded on demand from the external so...
void overrideFileContents(FileEntryRef SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
llvm::MemoryBufferRef getBufferOrFake(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
unsigned getFileIDSize(FileID FID) const
The size of the SLocEntry that FID represents.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
bool isInFileID(SourceLocation Loc, FileID FID, unsigned *RelativeOffset=nullptr) const
Given a specific FileID, returns true if Loc is inside that FileID chunk and sets relative offset (of...
unsigned getLineTableFilenameID(StringRef Str)
Return the uniqued ID for the specified filename.
void initializeForReplay(const SourceManager &Old)
Initialize this source manager suitably to replay the compilation described by Old.
FileIDAndOffset getDecomposedIncludedLoc(FileID FID) const
Returns the "included/expanded in" decomposed location of the given FileID.
bool isLoadedSourceLocation(SourceLocation Loc) const
Returns true if Loc came from a PCH/Module.
unsigned loaded_sloc_entry_size() const
Get the number of loaded SLocEntries we have.
FileID getOrCreateFileID(FileEntryRef SourceFile, SrcMgr::CharacteristicKind FileCharacter)
Get the FileID for SourceFile if it exists.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS, SourceLocation::IntTy *RelativeOffset) const
Return true if both LHS and RHS are in the local source location address space or the loaded one.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const
Return the file characteristic of the specified source location, indicating whether this is a normal ...
SourceLocation createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned Length, bool ExpansionIsTokenRange=true, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Creates an expansion SLocEntry for a macro use.
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
std::pair< bool, bool > isInTheSameTranslationUnit(FileIDAndOffset &LOffs, FileIDAndOffset &ROffs) const
Determines whether the two decomposed source location is in the same translation unit.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
SourceLocation getFileLoc(SourceLocation Loc, unsigned MaxDepth=std::numeric_limits< unsigned >::max()) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
fileinfo_iterator fileinfo_begin() const
LineTableInfo & getLineTable()
Retrieve the stored line table.
SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
std::optional< llvm::MemoryBufferRef > getMemoryBufferForFileOrNone(FileEntryRef File)
Retrieve the memory buffer associated with the given file.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
SourceLocation createMacroArgExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length)
Creates an expansion SLocEntry for the substitution of an argument into a function-like macro's body.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
void setBuffer(std::unique_ptr< llvm::MemoryBuffer > B)
Set the buffer.
std::optional< StringRef > getBufferDataIfLoaded() const
Return a StringRef to the source buffer data, only if it has already been loaded.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
unsigned getSizeBytesMapped() const
Returns the number of bytes actually mapped for this ContentCache.
unsigned IsTransient
True if this file may be transient, that is, if it might not exist at some later point in time when t...
unsigned getSize() const
Returns the size of the content encapsulated by this ContentCache.
llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const
Returns the kind of memory used to back the memory buffer for this content cache.
unsigned IsFileVolatile
True if this content cache was initially created for a source file considered to be volatile (likely ...
LineOffsetMapping SourceLineCache
A bump pointer allocated array of offsets for each source line.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc=SourceLocation()) const
Returns the memory buffer for the associated content.
static const char * getInvalidBOM(StringRef BufStr)
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
static ExpansionInfo create(SourceLocation SpellingLoc, SourceLocation Start, SourceLocation End, bool ExpansionIsTokenRange=true)
Return a ExpansionInfo for an expansion.
bool isMacroBodyExpansion() const
SourceLocation getSpellingLoc() const
CharSourceRange getExpansionLocRange() const
bool isMacroArgExpansion() const
static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc, SourceLocation ExpansionLoc)
Return a special ExpansionInfo for the expansion of a macro argument into a function-like macro's bod...
static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc, SourceLocation Start, SourceLocation End)
Return a special ExpansionInfo representing a token that ends prematurely.
SourceLocation getExpansionLocEnd() const
Information about a FileID, basically just the logical file that it represents and include stack info...
const ContentCache & getContentCache() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
static FileInfo get(SourceLocation IL, ContentCache &Con, CharacteristicKind FileCharacter, StringRef Filename)
Return a FileInfo object.
bool hasLineDirectives() const
Return true if this FileID has #line directives in it.
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
SourceLocation getIncludeLoc() const
const unsigned * begin() const
LineOffsetMapping()=default
const unsigned * end() const
static LineOffsetMapping get(llvm::MemoryBufferRef Buffer, llvm::BumpPtrAllocator &Alloc)
This is a discriminated union of FileInfo and ExpansionInfo.
SourceLocation::UIntTy getOffset() const
static SLocEntry get(SourceLocation::UIntTy Offset, const FileInfo &FI)
const FileInfo & getFile() const
const ExpansionInfo & getExpansion() const
Public enums and private classes that are part of the SourceManager implementation.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
StringRef getName(const HeaderType T)
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
std::pair< FileID, unsigned > FileIDAndOffset
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
SrcMgr::CharacteristicKind FileKind
Set the 0 if no flags, 1 if a system header,.
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)