#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManagerInternals.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Capacity.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <tuple>
#include <utility>
#include <vector>
using namespace clang;
using namespace SrcMgr;
using llvm::MemoryBuffer;
unsigned ContentCache::getSizeBytesMapped() const {
return Buffer ? Buffer->getBufferSize() : 0;
}
llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
if (Buffer == nullptr) {
assert(0 && "Buffer should never be null");
return llvm::MemoryBuffer::MemoryBuffer_Malloc;
}
return Buffer->getBufferKind();
}
unsigned ContentCache::getSize() const {
return Buffer ? (unsigned)Buffer->getBufferSize()
: (unsigned)ContentsEntry->getSize();
}
const char *ContentCache::getInvalidBOM(StringRef BufStr) {
const char *InvalidBOM =
llvm::StringSwitch<const char *>(BufStr)
.StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
"UTF-32 (BE)")
.StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
"UTF-32 (LE)")
.StartsWith("\xFE\xFF", "UTF-16 (BE)")
.StartsWith("\xFF\xFE", "UTF-16 (LE)")
.StartsWith("\x2B\x2F\x76", "UTF-7")
.StartsWith("\xF7\x64\x4C", "UTF-1")
.StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
.StartsWith("\x0E\xFE\xFF", "SCSU")
.StartsWith("\xFB\xEE\x28", "BOCU-1")
.StartsWith("\x84\x31\x95\x33", "GB-18030")
.Default(nullptr);
return InvalidBOM;
}
llvm::Optional<llvm::MemoryBufferRef>
ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
SourceLocation Loc) const {
if (IsBufferInvalid)
return None;
if (Buffer)
return Buffer->getMemBufferRef();
if (!ContentsEntry)
return None;
IsBufferInvalid = true;
auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
if (!BufferOrError) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
ContentsEntry->getName(),
BufferOrError.getError().message());
else
Diag.Report(Loc, diag::err_cannot_open_file)
<< ContentsEntry->getName() << BufferOrError.getError().message();
return None;
}
Buffer = std::move(*BufferOrError);
if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_file_too_large,
ContentsEntry->getName());
else
Diag.Report(Loc, diag::err_file_too_large)
<< ContentsEntry->getName();
return None;
}
if (!ContentsEntry->isNamedPipe() &&
Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_file_modified,
ContentsEntry->getName());
else
Diag.Report(Loc, diag::err_file_modified)
<< ContentsEntry->getName();
return None;
}
StringRef BufStr = Buffer->getBuffer();
const char *InvalidBOM = getInvalidBOM(BufStr);
if (InvalidBOM) {
Diag.Report(Loc, diag::err_unsupported_bom)
<< InvalidBOM << ContentsEntry->getName();
return None;
}
IsBufferInvalid = false;
return Buffer->getMemBufferRef();
}
unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
if (IterBool.second)
FilenamesByID.push_back(&*IterBool.first);
return IterBool.first->second;
}
void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
int FilenameID, unsigned EntryExit,
SrcMgr::CharacteristicKind FileKind) {
std::vector<LineEntry> &Entries = LineEntries[FID];
assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
"Adding line entries out of order!");
unsigned IncludeOffset = 0;
if (EntryExit == 1) {
IncludeOffset = Offset-1;
} else {
const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
if (EntryExit == 2) {
assert(PrevEntry && PrevEntry->IncludeOffset &&
"PPDirectives should have caught case when popping empty include "
"stack");
PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
}
if (PrevEntry) {
IncludeOffset = PrevEntry->IncludeOffset;
if (FilenameID == -1) {
FilenameID = PrevEntry->FilenameID;
}
}
}
Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
IncludeOffset));
}
const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
unsigned Offset) {
const std::vector<LineEntry> &Entries = LineEntries[FID];
assert(!Entries.empty() && "No #line entries for this FID after all!");
if (Entries.back().FileOffset <= Offset)
return &Entries.back();
std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
if (I == Entries.begin())
return nullptr;
return &*--I;
}
void LineTableInfo::AddEntry(FileID FID,
const std::vector<LineEntry> &Entries) {
LineEntries[FID] = Entries;
}
unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
return getLineTable().getLineTableFilenameID(Name);
}
void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
int FilenameID, bool IsFileEntry,
bool IsFileExit,
SrcMgr::CharacteristicKind FileKind) {
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
bool Invalid = false;
const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
if (!Entry.isFile() || Invalid)
return;
const SrcMgr::FileInfo &FileInfo = Entry.getFile();
const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
(void) getLineTable();
unsigned EntryExit = 0;
if (IsFileEntry)
EntryExit = 1;
else if (IsFileExit)
EntryExit = 2;
LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
EntryExit, FileKind);
}
LineTableInfo &SourceManager::getLineTable() {
if (!LineTable)
LineTable.reset(new LineTableInfo());
return *LineTable;
}
SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
bool UserFilesAreVolatile)
: Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
clearIDTables();
Diag.setSourceManager(this);
}
SourceManager::~SourceManager() {
for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
if (MemBufferInfos[i]) {
MemBufferInfos[i]->~ContentCache();
ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
}
}
for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
if (I->second) {
I->second->~ContentCache();
ContentCacheAlloc.Deallocate(I->second);
}
}
}
void SourceManager::clearIDTables() {
MainFileID = FileID();
LocalSLocEntryTable.clear();
LoadedSLocEntryTable.clear();
SLocEntryLoaded.clear();
LastLineNoFileIDQuery = FileID();
LastLineNoContentCache = nullptr;
LastFileIDLookup = FileID();
if (LineTable)
LineTable->clear();
NextLocalOffset = 0;
CurrentLoadedOffset = MaxLoadedOffset;
createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
}
bool SourceManager::isMainFile(const FileEntry &SourceFile) {
assert(MainFileID.isValid() && "expected initialized SourceManager");
if (auto *FE = getFileEntryForID(MainFileID))
return FE->getUID() == SourceFile.getUID();
return false;
}
void SourceManager::initializeForReplay(const SourceManager &Old) {
assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
Clone->OrigEntry = Cache->OrigEntry;
Clone->ContentsEntry = Cache->ContentsEntry;
Clone->BufferOverridden = Cache->BufferOverridden;
Clone->IsFileVolatile = Cache->IsFileVolatile;
Clone->IsTransient = Cache->IsTransient;
Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
return Clone;
};
for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
if (!Old.SLocEntryLoaded[I])
Old.loadSLocEntry(I, nullptr);
for (auto &FileInfo : Old.FileInfos) {
SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
if (Slot)
continue;
Slot = CloneContentCache(FileInfo.second);
}
}
ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
bool isSystemFile) {
ContentCache *&Entry = FileInfos[FileEnt];
if (Entry)
return *Entry;
Entry = ContentCacheAlloc.Allocate<ContentCache>();
if (OverriddenFilesInfo) {
llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
if (overI == OverriddenFilesInfo->OverriddenFiles.end())
new (Entry) ContentCache(FileEnt);
else
new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
: overI->second,
overI->second);
} else {
new (Entry) ContentCache(FileEnt);
}
Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
Entry->IsTransient = FilesAreTransient;
Entry->BufferOverridden |= FileEnt.isNamedPipe();
return *Entry;
}
ContentCache &SourceManager::createMemBufferContentCache(
std::unique_ptr<llvm::MemoryBuffer> Buffer) {
ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
new (Entry) ContentCache();
MemBufferInfos.push_back(Entry);
Entry->setBuffer(std::move(Buffer));
return *Entry;
}
const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
bool *Invalid) const {
assert(!SLocEntryLoaded[Index]);
if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
if (Invalid)
*Invalid = true;
if (!SLocEntryLoaded[Index]) {
if (!FakeSLocEntryForRecovery)
FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
SrcMgr::C_User, "")));
return *FakeSLocEntryForRecovery;
}
}
return LoadedSLocEntryTable[Index];
}
std::pair<int, SourceLocation::UIntTy>
SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
SourceLocation::UIntTy TotalSize) {
assert(ExternalSLocEntries && "Don't have an external sloc source");
if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
return std::make_pair(0, 0);
LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
CurrentLoadedOffset -= TotalSize;
int ID = LoadedSLocEntryTable.size();
return std::make_pair(-ID - 1, CurrentLoadedOffset);
}
llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
if (!FakeBufferForRecovery)
FakeBufferForRecovery =
llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
return *FakeBufferForRecovery;
}
SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
if (!FakeContentCacheForRecovery) {
FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
}
return *FakeContentCacheForRecovery;
}
FileID SourceManager::getPreviousFileID(FileID FID) const {
if (FID.isInvalid())
return FileID();
int ID = FID.ID;
if (ID == -1)
return FileID();
if (ID > 0) {
if (ID-1 == 0)
return FileID();
} else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
return FileID();
}
return FileID::get(ID-1);
}
FileID SourceManager::getNextFileID(FileID FID) const {
if (FID.isInvalid())
return FileID();
int ID = FID.ID;
if (ID > 0) {
if (unsigned(ID+1) >= local_sloc_entry_size())
return FileID();
} else if (ID+1 >= -1) {
return FileID();
}
return FileID::get(ID+1);
}
FileID SourceManager::createFileID(const FileEntry *SourceFile,
SourceLocation IncludePos,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
return createFileID(SourceFile->getLastRef(), IncludePos, FileCharacter,
LoadedID, LoadedOffset);
}
FileID SourceManager::createFileID(FileEntryRef SourceFile,
SourceLocation IncludePos,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
isSystem(FileCharacter));
if (IR.ContentsEntry->isNamedPipe())
(void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
LoadedID, LoadedOffset);
}
FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset,
SourceLocation IncludeLoc) {
StringRef Name = Buffer->getBufferIdentifier();
return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
}
FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset,
SourceLocation IncludeLoc) {
return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
LoadedID, LoadedOffset, IncludeLoc);
}
FileID
SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
SrcMgr::CharacteristicKind FileCharacter) {
FileID ID = translateFile(SourceFile);
return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
FileCharacter);
}
FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
SourceLocation IncludePos,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
if (LoadedID < 0) {
assert(LoadedID != -1 && "Loading sentinel FileID");
unsigned Index = unsigned(-LoadedID) - 2;
assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
assert(!SLocEntryLoaded[Index] && "FileID already loaded");
LoadedSLocEntryTable[Index] = SLocEntry::get(
LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
SLocEntryLoaded[Index] = true;
return FileID::get(LoadedID);
}
unsigned FileSize = File.getSize();
if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
Diag.Report(IncludePos, diag::err_include_too_large);
return FileID();
}
LocalSLocEntryTable.push_back(
SLocEntry::get(NextLocalOffset,
FileInfo::get(IncludePos, File, FileCharacter, Filename)));
NextLocalOffset += FileSize + 1;
FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
return LastFileIDLookup = FID;
}
SourceLocation SourceManager::createMacroArgExpansionLoc(
SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
ExpansionLoc);
return createExpansionLocImpl(Info, Length);
}
SourceLocation SourceManager::createExpansionLoc(
SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
SourceLocation ExpansionLocEnd, unsigned Length,
bool ExpansionIsTokenRange, int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
ExpansionInfo Info = ExpansionInfo::create(
SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
}
SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
SourceLocation TokenStart,
SourceLocation TokenEnd) {
assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
"token spans multiple files");
return createExpansionLocImpl(
ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
TokenEnd.getOffset() - TokenStart.getOffset());
}
SourceLocation
SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
unsigned Length, int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
if (LoadedID < 0) {
assert(LoadedID != -1 && "Loading sentinel FileID");
unsigned Index = unsigned(-LoadedID) - 2;
assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
assert(!SLocEntryLoaded[Index] && "FileID already loaded");
LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
SLocEntryLoaded[Index] = true;
return SourceLocation::getMacroLoc(LoadedOffset);
}
LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
assert(NextLocalOffset + Length + 1 > NextLocalOffset &&
NextLocalOffset + Length + 1 <= CurrentLoadedOffset &&
"Ran out of source locations!");
NextLocalOffset += Length + 1;
return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
}
llvm::Optional<llvm::MemoryBufferRef>
SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef());
return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
}
void SourceManager::overrideFileContents(
const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile->getLastRef());
IR.setBuffer(std::move(Buffer));
IR.BufferOverridden = true;
getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
}
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
const FileEntry *NewFile) {
assert(SourceFile->getSize() == NewFile->getSize() &&
"Different sizes, use the FileManager to create a virtual file with "
"the correct size");
assert(FileInfos.count(SourceFile) == 0 &&
"This function should be called at the initialization stage, before "
"any parsing occurs.");
getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
}
Optional<FileEntryRef>
SourceManager::bypassFileContentsOverride(FileEntryRef File) {
assert(isFileOverridden(&File.getFileEntry()));
llvm::Optional<FileEntryRef> BypassFile = FileMgr.getBypassFile(File);
if (!BypassFile)
return None;
(void)getOrCreateContentCache(*BypassFile);
return BypassFile;
}
void SourceManager::setFileIsTransient(const FileEntry *File) {
getOrCreateContentCache(File->getLastRef()).IsTransient = true;
}
Optional<StringRef>
SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
if (Entry->getFile().getContentCache().OrigEntry)
return Entry->getFile().getName();
return None;
}
StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
auto B = getBufferDataOrNone(FID);
if (Invalid)
*Invalid = !B;
return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
}
llvm::Optional<StringRef>
SourceManager::getBufferDataIfLoaded(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
return Entry->getFile().getContentCache().getBufferDataIfLoaded();
return None;
}
llvm::Optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
Diag, getFileManager(), SourceLocation()))
return B->getBuffer();
return None;
}
FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
if (!SLocOffset)
return FileID::get(0);
if (SLocOffset < NextLocalOffset)
return getFileIDLocal(SLocOffset);
return getFileIDLoaded(SLocOffset);
}
FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
assert(SLocOffset < NextLocalOffset && "Bad function choice");
const SrcMgr::SLocEntry *I;
if (LastFileIDLookup.ID < 0 ||
LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
I = LocalSLocEntryTable.end();
} else {
I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
}
unsigned NumProbes = 0;
while (true) {
--I;
if (I->getOffset() <= SLocOffset) {
FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
LastFileIDLookup = Res;
NumLinearScans += NumProbes+1;
return Res;
}
if (++NumProbes == 8)
break;
}
unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
unsigned LessIndex = 0;
NumProbes = 0;
while (true) {
unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
SourceLocation::UIntTy MidOffset =
getLocalSLocEntry(MiddleIndex).getOffset();
++NumProbes;
if (MidOffset > SLocOffset) {
GreaterIndex = MiddleIndex;
continue;
}
if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
FileID Res = FileID::get(MiddleIndex);
LastFileIDLookup = Res;
NumBinaryProbes += NumProbes;
return Res;
}
LessIndex = MiddleIndex;
}
}
FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
if (SLocOffset < CurrentLoadedOffset) {
assert(0 && "Invalid SLocOffset or bad function choice");
return FileID();
}
unsigned I;
int LastID = LastFileIDLookup.ID;
if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
I = 0;
else
I = (-LastID - 2) + 1;
unsigned NumProbes;
for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
if (E.getOffset() <= SLocOffset) {
FileID Res = FileID::get(-int(I) - 2);
LastFileIDLookup = Res;
NumLinearScans += NumProbes + 1;
return Res;
}
}
unsigned GreaterIndex = I;
unsigned LessIndex = LoadedSLocEntryTable.size();
NumProbes = 0;
while (true) {
++NumProbes;
unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
if (E.getOffset() == 0)
return FileID();
++NumProbes;
if (E.getOffset() > SLocOffset) {
if (GreaterIndex == MiddleIndex) {
assert(0 && "binary search missed the entry");
return FileID();
}
GreaterIndex = MiddleIndex;
continue;
}
if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
FileID Res = FileID::get(-int(MiddleIndex) - 2);
LastFileIDLookup = Res;
NumBinaryProbes += NumProbes;
return Res;
}
if (LessIndex == MiddleIndex) {
assert(0 && "binary search missed the entry");
return FileID();
}
LessIndex = MiddleIndex;
}
}
SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const {
do {
Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
} while (!Loc.isFileID());
return Loc;
}
SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
do {
std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Loc = Loc.getLocWithOffset(LocInfo.second);
} while (!Loc.isFileID());
return Loc;
}
SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
do {
if (isMacroArgExpansion(Loc))
Loc = getImmediateSpellingLoc(Loc);
else
Loc = getImmediateExpansionRange(Loc).getBegin();
} while (!Loc.isFileID());
return Loc;
}
std::pair<FileID, unsigned>
SourceManager::getDecomposedExpansionLocSlowCase(
const SrcMgr::SLocEntry *E) const {
FileID FID;
SourceLocation Loc;
unsigned Offset;
do {
Loc = E->getExpansion().getExpansionLocStart();
FID = getFileID(Loc);
E = &getSLocEntry(FID);
Offset = Loc.getOffset()-E->getOffset();
} while (!Loc.isFileID());
return std::make_pair(FID, Offset);
}
std::pair<FileID, unsigned>
SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
unsigned Offset) const {
FileID FID;
SourceLocation Loc;
do {
Loc = E->getExpansion().getSpellingLoc();
Loc = Loc.getLocWithOffset(Offset);
FID = getFileID(Loc);
E = &getSLocEntry(FID);
Offset = Loc.getOffset()-E->getOffset();
} while (!Loc.isFileID());
return std::make_pair(FID, Offset);
}
SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
if (Loc.isFileID()) return Loc;
std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
return Loc.getLocWithOffset(LocInfo.second);
}
StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
return F->getName();
return StringRef();
}
CharSourceRange
SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
assert(Loc.isMacroID() && "Not a macro expansion loc!");
const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
return Expansion.getExpansionLocRange();
}
SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
while (isMacroArgExpansion(Loc))
Loc = getImmediateSpellingLoc(Loc);
return Loc;
}
CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
if (Loc.isFileID())
return CharSourceRange(SourceRange(Loc, Loc), true);
CharSourceRange Res = getImmediateExpansionRange(Loc);
while (!Res.getBegin().isFileID())
Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
while (!Res.getEnd().isFileID()) {
CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
Res.setEnd(EndRange.getEnd());
Res.setTokenRange(EndRange.isTokenRange());
}
return Res;
}
bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
SourceLocation *StartLoc) const {
if (!Loc.isMacroID()) return false;
FileID FID = getFileID(Loc);
const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
if (!Expansion.isMacroArgExpansion()) return false;
if (StartLoc)
*StartLoc = Expansion.getExpansionLocStart();
return true;
}
bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
if (!Loc.isMacroID()) return false;
FileID FID = getFileID(Loc);
const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
return Expansion.isMacroBodyExpansion();
}
bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
SourceLocation *MacroBegin) const {
assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
if (DecompLoc.second > 0)
return false;
bool Invalid = false;
const SrcMgr::ExpansionInfo &ExpInfo =
getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
if (Invalid)
return false;
SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
if (ExpInfo.isMacroArgExpansion()) {
FileID PrevFID = getPreviousFileID(DecompLoc.first);
if (!PrevFID.isInvalid()) {
const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
if (Invalid)
return false;
if (PrevEntry.isExpansion() &&
PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
return false;
}
}
if (MacroBegin)
*MacroBegin = ExpLoc;
return true;
}
bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
SourceLocation *MacroEnd) const {
assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
FileID FID = getFileID(Loc);
SourceLocation NextLoc = Loc.getLocWithOffset(1);
if (isInFileID(NextLoc, FID))
return false;
bool Invalid = false;
const SrcMgr::ExpansionInfo &ExpInfo =
getSLocEntry(FID, &Invalid).getExpansion();
if (Invalid)
return false;
if (ExpInfo.isMacroArgExpansion()) {
FileID NextFID = getNextFileID(FID);
if (!NextFID.isInvalid()) {
const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
if (Invalid)
return false;
if (NextEntry.isExpansion() &&
NextEntry.getExpansion().getExpansionLocStart() ==
ExpInfo.getExpansionLocStart())
return false;
}
}
if (MacroEnd)
*MacroEnd = ExpInfo.getExpansionLocEnd();
return true;
}
const char *SourceManager::getCharacterData(SourceLocation SL,
bool *Invalid) const {
std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
bool CharDataInvalid = false;
const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
if (CharDataInvalid || !Entry.isFile()) {
if (Invalid)
*Invalid = true;
return "<<<<INVALID BUFFER>>>>";
}
llvm::Optional<llvm::MemoryBufferRef> Buffer =
Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
SourceLocation());
if (Invalid)
*Invalid = !Buffer;
return Buffer ? Buffer->getBufferStart() + LocInfo.second
: "<<<<INVALID BUFFER>>>>";
}
unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
bool *Invalid) const {
llvm::Optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
if (Invalid)
*Invalid = !MemBuf;
if (!MemBuf)
return 1;
if (FilePos > MemBuf->getBufferSize()) {
if (Invalid)
*Invalid = true;
return 1;
}
const char *Buf = MemBuf->getBufferStart();
if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
const unsigned *SourceLineCache =
LastLineNoContentCache->SourceLineCache.begin();
unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
unsigned LineEnd = SourceLineCache[LastLineNoResult];
if (FilePos >= LineStart && FilePos < LineEnd) {
if (FilePos + 1 == LineEnd && FilePos > LineStart) {
if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
--FilePos;
}
return FilePos - LineStart + 1;
}
}
unsigned LineStart = FilePos;
while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
--LineStart;
return FilePos-LineStart+1;
}
template<typename LocType>
static bool isInvalid(LocType Loc, bool *Invalid) {
bool MyInvalid = Loc.isInvalid();
if (Invalid)
*Invalid = MyInvalid;
return MyInvalid;
}
unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
bool *Invalid) const {
if (isInvalid(Loc, Invalid)) return 0;
std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
}
unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
bool *Invalid) const {
if (isInvalid(Loc, Invalid)) return 0;
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
}
unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
bool *Invalid) const {
PresumedLoc PLoc = getPresumedLoc(Loc);
if (isInvalid(PLoc, Invalid)) return 0;
return PLoc.getColumn();
}
template <class T>
static constexpr inline T likelyhasbetween(T x, unsigned char m,
unsigned char n) {
return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
((x & ~static_cast<T>(0) / 255 * 127) +
(~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
~static_cast<T>(0) / 255 * 128;
}
LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
llvm::BumpPtrAllocator &Alloc) {
SmallVector<unsigned, 256> LineOffsets;
LineOffsets.push_back(0);
const unsigned char *Buf = (const unsigned char *)Buffer.getBufferStart();
const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
const std::size_t BufLen = End - Buf;
unsigned I = 0;
uint64_t Word;
if (BufLen > sizeof(Word)) {
do {
Word = llvm::support::endian::read64(Buf + I, llvm::support::little);
auto Mask = likelyhasbetween(Word, '\n', '\r');
if (!Mask) {
I += sizeof(Word);
continue;
}
unsigned N =
llvm::countTrailingZeros(Mask) - 7; Word >>= N;
I += N / 8 + 1;
unsigned char Byte = Word;
if (Byte == '\n') {
LineOffsets.push_back(I);
} else if (Byte == '\r') {
if (Buf[I] == '\n')
++I;
LineOffsets.push_back(I);
}
} while (I < BufLen - sizeof(Word) - 1);
}
while (I < BufLen) {
if (Buf[I] == '\n') {
LineOffsets.push_back(I + 1);
} else if (Buf[I] == '\r') {
if (I + 1 < BufLen && Buf[I + 1] == '\n')
++I;
LineOffsets.push_back(I + 1);
}
++I;
}
return LineOffsetMapping(LineOffsets, Alloc);
}
LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
llvm::BumpPtrAllocator &Alloc)
: Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
Storage[0] = LineOffsets.size();
std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
}
unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
bool *Invalid) const {
if (FID.isInvalid()) {
if (Invalid)
*Invalid = true;
return 1;
}
const ContentCache *Content;
if (LastLineNoFileIDQuery == FID)
Content = LastLineNoContentCache;
else {
bool MyInvalid = false;
const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
if (MyInvalid || !Entry.isFile()) {
if (Invalid)
*Invalid = true;
return 1;
}
Content = &Entry.getFile().getContentCache();
}
if (!Content->SourceLineCache) {
llvm::Optional<llvm::MemoryBufferRef> Buffer =
Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
if (Invalid)
*Invalid = !Buffer;
if (!Buffer)
return 1;
Content->SourceLineCache =
LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
} else if (Invalid)
*Invalid = false;
const unsigned *SourceLineCache = Content->SourceLineCache.begin();
const unsigned *SourceLineCacheStart = SourceLineCache;
const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
unsigned QueriedFilePos = FilePos+1;
if (LastLineNoFileIDQuery == FID) {
if (QueriedFilePos >= LastLineNoFilePos) {
SourceLineCache = SourceLineCache+LastLineNoResult-1;
if (SourceLineCache+5 < SourceLineCacheEnd) {
if (SourceLineCache[5] > QueriedFilePos)
SourceLineCacheEnd = SourceLineCache+5;
else if (SourceLineCache+10 < SourceLineCacheEnd) {
if (SourceLineCache[10] > QueriedFilePos)
SourceLineCacheEnd = SourceLineCache+10;
else if (SourceLineCache+20 < SourceLineCacheEnd) {
if (SourceLineCache[20] > QueriedFilePos)
SourceLineCacheEnd = SourceLineCache+20;
}
}
}
} else {
if (LastLineNoResult < Content->SourceLineCache.size())
SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
}
}
const unsigned *Pos =
std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
unsigned LineNo = Pos-SourceLineCacheStart;
LastLineNoFileIDQuery = FID;
LastLineNoContentCache = Content;
LastLineNoFilePos = QueriedFilePos;
LastLineNoResult = LineNo;
return LineNo;
}
unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
bool *Invalid) const {
if (isInvalid(Loc, Invalid)) return 0;
std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
return getLineNumber(LocInfo.first, LocInfo.second);
}
unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
bool *Invalid) const {
if (isInvalid(Loc, Invalid)) return 0;
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
return getLineNumber(LocInfo.first, LocInfo.second);
}
unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
bool *Invalid) const {
PresumedLoc PLoc = getPresumedLoc(Loc);
if (isInvalid(PLoc, Invalid)) return 0;
return PLoc.getLine();
}
SrcMgr::CharacteristicKind
SourceManager::getFileCharacteristic(SourceLocation Loc) const {
assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
if (!SEntry)
return C_User;
const SrcMgr::FileInfo &FI = SEntry->getFile();
if (!FI.hasLineDirectives())
return FI.getFileCharacteristic();
assert(LineTable && "Can't have linetable entries without a LineTable!");
const LineEntry *Entry =
LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
if (!Entry)
return FI.getFileCharacteristic();
return Entry->FileKind;
}
StringRef SourceManager::getBufferName(SourceLocation Loc,
bool *Invalid) const {
if (isInvalid(Loc, Invalid)) return "<invalid loc>";
auto B = getBufferOrNone(getFileID(Loc));
if (Invalid)
*Invalid = !B;
return B ? B->getBufferIdentifier() : "<invalid buffer>";
}
PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
bool UseLineDirectives) const {
if (Loc.isInvalid()) return PresumedLoc();
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
bool Invalid = false;
const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
if (Invalid || !Entry.isFile())
return PresumedLoc();
const SrcMgr::FileInfo &FI = Entry.getFile();
const SrcMgr::ContentCache *C = &FI.getContentCache();
FileID FID = LocInfo.first;
StringRef Filename;
if (C->OrigEntry)
Filename = C->OrigEntry->getName();
else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
Filename = Buffer->getBufferIdentifier();
unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
if (Invalid)
return PresumedLoc();
unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
if (Invalid)
return PresumedLoc();
SourceLocation IncludeLoc = FI.getIncludeLoc();
if (UseLineDirectives && FI.hasLineDirectives()) {
assert(LineTable && "Can't have linetable entries without a LineTable!");
if (const LineEntry *Entry =
LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
if (Entry->FilenameID != -1) {
Filename = LineTable->getFilename(Entry->FilenameID);
FID = FileID::get(0);
}
unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
if (Entry->IncludeOffset) {
IncludeLoc = getLocForStartOfFile(LocInfo.first);
IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
}
}
}
return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
}
bool SourceManager::isInMainFile(SourceLocation Loc) const {
if (Loc.isInvalid()) return false;
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
if (!Entry)
return false;
const SrcMgr::FileInfo &FI = Entry->getFile();
if (FI.hasLineDirectives())
if (const LineEntry *Entry =
LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
if (Entry->IncludeOffset)
return false;
return FI.getIncludeLoc().isInvalid();
}
unsigned SourceManager::getFileIDSize(FileID FID) const {
bool Invalid = false;
const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
if (Invalid)
return 0;
int ID = FID.ID;
SourceLocation::UIntTy NextOffset;
if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
NextOffset = getNextLocalOffset();
else if (ID+1 == -1)
NextOffset = MaxLoadedOffset;
else
NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
return NextOffset - Entry.getOffset() - 1;
}
SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
unsigned Line,
unsigned Col) const {
assert(SourceFile && "Null source file!");
assert(Line && Col && "Line and column should start from 1!");
FileID FirstFID = translateFile(SourceFile);
return translateLineCol(FirstFID, Line, Col);
}
FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
assert(SourceFile && "Null source file!");
if (MainFileID.isValid()) {
bool Invalid = false;
const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
if (Invalid)
return FileID();
if (MainSLoc.isFile()) {
if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
return MainFileID;
}
}
for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
const SLocEntry &SLoc = getLocalSLocEntry(I);
if (SLoc.isFile() &&
SLoc.getFile().getContentCache().OrigEntry == SourceFile)
return FileID::get(I);
}
for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
const SLocEntry &SLoc = getLoadedSLocEntry(I);
if (SLoc.isFile() &&
SLoc.getFile().getContentCache().OrigEntry == SourceFile)
return FileID::get(-int(I) - 2);
}
return FileID();
}
SourceLocation SourceManager::translateLineCol(FileID FID,
unsigned Line,
unsigned Col) const {
assert(Line && Col && "Line and column should start from 1!");
if (FID.isInvalid())
return SourceLocation();
bool Invalid = false;
const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
if (Invalid)
return SourceLocation();
if (!Entry.isFile())
return SourceLocation();
SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
if (Line == 1 && Col == 1)
return FileLoc;
const ContentCache *Content = &Entry.getFile().getContentCache();
llvm::Optional<llvm::MemoryBufferRef> Buffer =
Content->getBufferOrNone(Diag, getFileManager());
if (!Buffer)
return SourceLocation();
if (!Content->SourceLineCache)
Content->SourceLineCache =
LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
if (Line > Content->SourceLineCache.size()) {
unsigned Size = Buffer->getBufferSize();
if (Size > 0)
--Size;
return FileLoc.getLocWithOffset(Size);
}
unsigned FilePos = Content->SourceLineCache[Line - 1];
const char *Buf = Buffer->getBufferStart() + FilePos;
unsigned BufLength = Buffer->getBufferSize() - FilePos;
if (BufLength == 0)
return FileLoc.getLocWithOffset(FilePos);
unsigned i = 0;
while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
++i;
return FileLoc.getLocWithOffset(FilePos + i);
}
void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
FileID FID) const {
assert(FID.isValid());
MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
int ID = FID.ID;
while (true) {
++ID;
if (ID > 0) {
if (unsigned(ID) >= local_sloc_entry_size())
return;
} else if (ID == -1) {
return;
}
bool Invalid = false;
const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
if (Invalid)
return;
if (Entry.isFile()) {
auto& File = Entry.getFile();
if (File.getFileCharacteristic() == C_User_ModuleMap ||
File.getFileCharacteristic() == C_System_ModuleMap)
continue;
SourceLocation IncludeLoc = File.getIncludeLoc();
bool IncludedInFID =
(IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
(FID == MainFileID && Entry.getFile().getName() == "<built-in>");
if (IncludedInFID) {
if (Entry.getFile().NumCreatedFIDs)
ID += Entry.getFile().NumCreatedFIDs - 1 ;
continue;
} else if (IncludeLoc.isValid()) {
return;
}
continue;
}
const ExpansionInfo &ExpInfo = Entry.getExpansion();
if (ExpInfo.getExpansionLocStart().isFileID()) {
if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
return; }
if (!ExpInfo.isMacroArgExpansion())
continue;
associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
ExpInfo.getSpellingLoc(),
SourceLocation::getMacroLoc(Entry.getOffset()),
getFileIDSize(FileID::get(ID)));
}
}
void SourceManager::associateFileChunkWithMacroArgExp(
MacroArgsMap &MacroArgsCache,
FileID FID,
SourceLocation SpellLoc,
SourceLocation ExpansionLoc,
unsigned ExpansionLength) const {
if (!SpellLoc.isFileID()) {
SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
FileID SpellFID; unsigned SpellRelativeOffs;
std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
while (true) {
const SLocEntry &Entry = getSLocEntry(SpellFID);
SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
unsigned SpellFIDSize = getFileIDSize(SpellFID);
SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
const ExpansionInfo &Info = Entry.getExpansion();
if (Info.isMacroArgExpansion()) {
unsigned CurrSpellLength;
if (SpellFIDEndOffs < SpellEndOffs)
CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
else
CurrSpellLength = ExpansionLength;
associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
ExpansionLoc, CurrSpellLength);
}
if (SpellFIDEndOffs >= SpellEndOffs)
return;
unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
ExpansionLength -= advance;
++SpellFID.ID;
SpellRelativeOffs = 0;
}
}
assert(SpellLoc.isFileID());
unsigned BeginOffs;
if (!isInFileID(SpellLoc, FID, &BeginOffs))
return;
unsigned EndOffs = BeginOffs + ExpansionLength;
MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
--I;
SourceLocation EndOffsMappedLoc = I->second;
MacroArgsCache[BeginOffs] = ExpansionLoc;
MacroArgsCache[EndOffs] = EndOffsMappedLoc;
}
SourceLocation
SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
if (Loc.isInvalid() || !Loc.isFileID())
return Loc;
FileID FID;
unsigned Offset;
std::tie(FID, Offset) = getDecomposedLoc(Loc);
if (FID.isInvalid())
return Loc;
std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
if (!MacroArgsCache) {
MacroArgsCache = std::make_unique<MacroArgsMap>();
computeMacroArgsCache(*MacroArgsCache, FID);
}
assert(!MacroArgsCache->empty());
MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
if (I == MacroArgsCache->begin())
return Loc;
--I;
SourceLocation::UIntTy MacroArgBeginOffs = I->first;
SourceLocation MacroArgExpandedLoc = I->second;
if (MacroArgExpandedLoc.isValid())
return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
return Loc;
}
std::pair<FileID, unsigned>
SourceManager::getDecomposedIncludedLoc(FileID FID) const {
if (FID.isInvalid())
return std::make_pair(FileID(), 0);
using DecompTy = std::pair<FileID, unsigned>;
auto InsertOp = IncludedLocMap.try_emplace(FID);
DecompTy &DecompLoc = InsertOp.first->second;
if (!InsertOp.second)
return DecompLoc;
SourceLocation UpperLoc;
bool Invalid = false;
const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
if (!Invalid) {
if (Entry.isExpansion())
UpperLoc = Entry.getExpansion().getExpansionLocStart();
else
UpperLoc = Entry.getFile().getIncludeLoc();
}
if (UpperLoc.isValid())
DecompLoc = getDecomposedLoc(UpperLoc);
return DecompLoc;
}
static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
const SourceManager &SM) {
std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
if (UpperLoc.first.isInvalid())
return true;
Loc = UpperLoc;
return false;
}
InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
FileID RFID) const {
enum { MagicCacheSize = 300 };
IsBeforeInTUCacheKey Key(LFID, RFID);
if (IBTUCache.size() < MagicCacheSize)
return IBTUCache[Key];
InBeforeInTUCache::iterator I = IBTUCache.find(Key);
if (I != IBTUCache.end())
return I->second;
return IBTUCacheOverflow;
}
bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
SourceLocation RHS) const {
assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
if (LHS == RHS)
return false;
std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
if (InSameTU.first)
return InSameTU.second;
StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
bool LIsBuiltins = LB == "<built-in>";
bool RIsBuiltins = RB == "<built-in>";
if (LIsBuiltins || RIsBuiltins) {
if (LIsBuiltins != RIsBuiltins)
return LIsBuiltins;
return LOffs.first < ROffs.first;
}
bool LIsAsm = LB == "<inline asm>";
bool RIsAsm = RB == "<inline asm>";
if (LIsAsm || RIsAsm) {
if (LIsAsm != RIsAsm)
return RIsAsm;
assert(LOffs.first == ROffs.first);
return false;
}
bool LIsScratch = LB == "<scratch space>";
bool RIsScratch = RB == "<scratch space>";
if (LIsScratch || RIsScratch) {
if (LIsScratch != RIsScratch)
return LIsScratch;
return LOffs.second < ROffs.second;
}
llvm_unreachable("Unsortable locations found");
}
std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
std::pair<FileID, unsigned> &LOffs,
std::pair<FileID, unsigned> &ROffs) const {
if (LOffs.first == ROffs.first)
return std::make_pair(true, LOffs.second < ROffs.second);
InBeforeInTUCacheEntry &IsBeforeInTUCache =
getInBeforeInTUCache(LOffs.first, ROffs.first);
if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
return std::make_pair(
true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
LOffs.first.ID < ROffs.first.ID);
using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
LocSet LChain;
do {
LChain.insert(LOffs);
} while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
LocSet::iterator I;
while((I = LChain.find(ROffs.first)) == LChain.end()) {
if (MoveUpIncludeHierarchy(ROffs, *this))
break; }
if (I != LChain.end())
LOffs = *I;
if (LOffs.first == ROffs.first) {
IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
return std::make_pair(
true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
}
IsBeforeInTUCache.clear();
return std::make_pair(false, false);
}
void SourceManager::PrintStats() const {
llvm::errs() << "\n*** Source Manager Stats:\n";
llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
<< " mem buffers mapped.\n";
llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
<< llvm::capacity_in_bytes(LocalSLocEntryTable)
<< " bytes of capacity), "
<< NextLocalOffset << "B of Sloc address space used.\n";
llvm::errs() << LoadedSLocEntryTable.size()
<< " loaded SLocEntries allocated, "
<< MaxLoadedOffset - CurrentLoadedOffset
<< "B of Sloc address space used.\n";
unsigned NumLineNumsComputed = 0;
unsigned NumFileBytesMapped = 0;
for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
NumLineNumsComputed += bool(I->second->SourceLineCache);
NumFileBytesMapped += I->second->getSizeBytesMapped();
}
unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
<< NumLineNumsComputed << " files with line #'s computed, "
<< NumMacroArgsComputed << " files with macro args computed.\n";
llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
<< NumBinaryProbes << " binary.\n";
}
LLVM_DUMP_METHOD void SourceManager::dump() const {
llvm::raw_ostream &out = llvm::errs();
auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
llvm::Optional<SourceLocation::UIntTy> NextStart) {
out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
<< " <SourceLocation " << Entry.getOffset() << ":";
if (NextStart)
out << *NextStart << ">\n";
else
out << "???\?>\n";
if (Entry.isFile()) {
auto &FI = Entry.getFile();
if (FI.NumCreatedFIDs)
out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
<< ">\n";
if (FI.getIncludeLoc().isValid())
out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
auto &CC = FI.getContentCache();
out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
<< "\n";
if (CC.BufferOverridden)
out << " contents overridden\n";
if (CC.ContentsEntry != CC.OrigEntry) {
out << " contents from "
<< (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
<< "\n";
}
} else {
auto &EI = Entry.getExpansion();
out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
<< " range <" << EI.getExpansionLocStart().getOffset() << ":"
<< EI.getExpansionLocEnd().getOffset() << ">\n";
}
};
for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
DumpSLocEntry(ID, LocalSLocEntryTable[ID],
ID == NumIDs - 1 ? NextLocalOffset
: LocalSLocEntryTable[ID + 1].getOffset());
}
llvm::Optional<SourceLocation::UIntTy> NextStart;
for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
int ID = -(int)Index - 2;
if (SLocEntryLoaded[Index]) {
DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
NextStart = LoadedSLocEntryTable[Index].getOffset();
} else {
NextStart = None;
}
}
}
ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
size_t malloc_bytes = 0;
size_t mmap_bytes = 0;
for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
switch (MemBufferInfos[i]->getMemoryBufferKind()) {
case llvm::MemoryBuffer::MemoryBuffer_MMap:
mmap_bytes += sized_mapped;
break;
case llvm::MemoryBuffer::MemoryBuffer_Malloc:
malloc_bytes += sized_mapped;
break;
}
return MemoryBufferSizes(malloc_bytes, mmap_bytes);
}
size_t SourceManager::getDataStructureSizes() const {
size_t size = llvm::capacity_in_bytes(MemBufferInfos)
+ llvm::capacity_in_bytes(LocalSLocEntryTable)
+ llvm::capacity_in_bytes(LoadedSLocEntryTable)
+ llvm::capacity_in_bytes(SLocEntryLoaded)
+ llvm::capacity_in_bytes(FileInfos);
if (OverriddenFilesInfo)
size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
return size;
}
SourceManagerForFile::SourceManagerForFile(StringRef FileName,
StringRef Content) {
IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
new llvm::vfs::InMemoryFileSystem);
InMemoryFileSystem->addFile(
FileName, 0,
llvm::MemoryBuffer::getMemBuffer(Content, FileName,
false));
FileMgr =
std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
Diagnostics = std::make_unique<DiagnosticsEngine>(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
SourceLocation(), clang::SrcMgr::C_User);
assert(ID.isValid());
SourceMgr->setMainFileID(ID);
}