#include "clang/Serialization/GlobalModuleIndex.h"
#include "ASTReaderInternals.h"
#include "clang/Basic/FileManager.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ModuleFile.h"
#include "clang/Serialization/PCHContainerOperations.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/Bitstream/BitstreamWriter.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/LockFileManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TimeProfiler.h"
#include <cstdio>
using namespace clang;
using namespace serialization;
namespace {
enum {
GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
};
enum IndexRecordTypes {
INDEX_METADATA,
MODULE,
IDENTIFIER_INDEX
};
}
static const char * const IndexFileName = "modules.idx";
static const unsigned CurrentVersion = 1;
namespace {
class IdentifierIndexReaderTrait {
public:
typedef StringRef external_key_type;
typedef StringRef internal_key_type;
typedef SmallVector<unsigned, 2> data_type;
typedef unsigned hash_value_type;
typedef unsigned offset_type;
static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
return a == b;
}
static hash_value_type ComputeHash(const internal_key_type& a) {
return llvm::djbHash(a);
}
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char*& d) {
using namespace llvm::support;
unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
return std::make_pair(KeyLen, DataLen);
}
static const internal_key_type&
GetInternalKey(const external_key_type& x) { return x; }
static const external_key_type&
GetExternalKey(const internal_key_type& x) { return x; }
static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
return StringRef((const char *)d, n);
}
static data_type ReadData(const internal_key_type& k,
const unsigned char* d,
unsigned DataLen) {
using namespace llvm::support;
data_type Result;
while (DataLen > 0) {
unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
Result.push_back(ID);
DataLen -= 4;
}
return Result;
}
};
typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
IdentifierIndexTable;
}
GlobalModuleIndex::GlobalModuleIndex(
std::unique_ptr<llvm::MemoryBuffer> IndexBuffer,
llvm::BitstreamCursor Cursor)
: Buffer(std::move(IndexBuffer)), IdentifierIndex(), NumIdentifierLookups(),
NumIdentifierLookupHits() {
auto Fail = [&](llvm::Error &&Err) {
report_fatal_error("Module index '" + Buffer->getBufferIdentifier() +
"' failed: " + toString(std::move(Err)));
};
llvm::TimeTraceScope TimeScope("Module LoadIndex");
bool InGlobalIndexBlock = false;
bool Done = false;
while (!Done) {
llvm::BitstreamEntry Entry;
if (Expected<llvm::BitstreamEntry> Res = Cursor.advance())
Entry = Res.get();
else
Fail(Res.takeError());
switch (Entry.Kind) {
case llvm::BitstreamEntry::Error:
return;
case llvm::BitstreamEntry::EndBlock:
if (InGlobalIndexBlock) {
InGlobalIndexBlock = false;
Done = true;
continue;
}
return;
case llvm::BitstreamEntry::Record:
if (InGlobalIndexBlock)
break;
return;
case llvm::BitstreamEntry::SubBlock:
if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
if (llvm::Error Err = Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
Fail(std::move(Err));
InGlobalIndexBlock = true;
} else if (llvm::Error Err = Cursor.SkipBlock())
Fail(std::move(Err));
continue;
}
SmallVector<uint64_t, 64> Record;
StringRef Blob;
Expected<unsigned> MaybeIndexRecord =
Cursor.readRecord(Entry.ID, Record, &Blob);
if (!MaybeIndexRecord)
Fail(MaybeIndexRecord.takeError());
IndexRecordTypes IndexRecord =
static_cast<IndexRecordTypes>(MaybeIndexRecord.get());
switch (IndexRecord) {
case INDEX_METADATA:
if (Record.size() < 1 || Record[0] != CurrentVersion)
return;
break;
case MODULE: {
unsigned Idx = 0;
unsigned ID = Record[Idx++];
if (ID == Modules.size())
Modules.push_back(ModuleInfo());
else
Modules.resize(ID + 1);
Modules[ID].Size = Record[Idx++];
Modules[ID].ModTime = Record[Idx++];
unsigned NameLen = Record[Idx++];
Modules[ID].FileName.assign(Record.begin() + Idx,
Record.begin() + Idx + NameLen);
Idx += NameLen;
unsigned NumDeps = Record[Idx++];
Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
Record.begin() + Idx,
Record.begin() + Idx + NumDeps);
Idx += NumDeps;
assert(Idx == Record.size() && "More module info?");
StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
ModuleName = ModuleName.rsplit('-').first;
UnresolvedModules[ModuleName] = ID;
break;
}
case IDENTIFIER_INDEX:
if (Record[0]) {
IdentifierIndex = IdentifierIndexTable::Create(
(const unsigned char *)Blob.data() + Record[0],
(const unsigned char *)Blob.data() + sizeof(uint32_t),
(const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
}
break;
}
}
}
GlobalModuleIndex::~GlobalModuleIndex() {
delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
}
std::pair<GlobalModuleIndex *, llvm::Error>
GlobalModuleIndex::readIndex(StringRef Path) {
llvm::SmallString<128> IndexPath;
IndexPath += Path;
llvm::sys::path::append(IndexPath, IndexFileName);
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
llvm::MemoryBuffer::getFile(IndexPath.c_str());
if (!BufferOrErr)
return std::make_pair(nullptr,
llvm::errorCodeToError(BufferOrErr.getError()));
std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
llvm::BitstreamCursor Cursor(*Buffer);
for (unsigned char C : {'B', 'C', 'G', 'I'}) {
if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Cursor.Read(8)) {
if (Res.get() != C)
return std::make_pair(
nullptr, llvm::createStringError(std::errc::illegal_byte_sequence,
"expected signature BCGI"));
} else
return std::make_pair(nullptr, Res.takeError());
}
return std::make_pair(new GlobalModuleIndex(std::move(Buffer), std::move(Cursor)),
llvm::Error::success());
}
void
GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
ModuleFiles.clear();
for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
if (ModuleFile *MF = Modules[I].File)
ModuleFiles.push_back(MF);
}
}
void GlobalModuleIndex::getModuleDependencies(
ModuleFile *File,
SmallVectorImpl<ModuleFile *> &Dependencies) {
llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
= ModulesByFile.find(File);
if (Known == ModulesByFile.end())
return;
Dependencies.clear();
ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
if (ModuleFile *MF = Modules[I].File)
Dependencies.push_back(MF);
}
}
bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
Hits.clear();
if (!IdentifierIndex)
return false;
++NumIdentifierLookups;
IdentifierIndexTable &Table
= *static_cast<IdentifierIndexTable *>(IdentifierIndex);
IdentifierIndexTable::iterator Known = Table.find(Name);
if (Known == Table.end()) {
return false;
}
SmallVector<unsigned, 2> ModuleIDs = *Known;
for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
Hits.insert(MF);
}
++NumIdentifierLookupHits;
return true;
}
bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
StringRef Name = File->ModuleName;
llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
if (Known == UnresolvedModules.end()) {
return true;
}
ModuleInfo &Info = Modules[Known->second];
bool Failed = true;
if (File->File->getSize() == Info.Size &&
File->File->getModificationTime() == Info.ModTime) {
Info.File = File;
ModulesByFile[File] = Known->second;
Failed = false;
}
UnresolvedModules.erase(Known);
return Failed;
}
void GlobalModuleIndex::printStats() {
std::fprintf(stderr, "*** Global Module Index Statistics:\n");
if (NumIdentifierLookups) {
fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
NumIdentifierLookupHits, NumIdentifierLookups,
(double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
}
std::fprintf(stderr, "\n");
}
LLVM_DUMP_METHOD void GlobalModuleIndex::dump() {
llvm::errs() << "*** Global Module Index Dump:\n";
llvm::errs() << "Module files:\n";
for (auto &MI : Modules) {
llvm::errs() << "** " << MI.FileName << "\n";
if (MI.File)
MI.File->dump();
else
llvm::errs() << "\n";
}
llvm::errs() << "\n";
}
namespace {
struct ModuleFileInfo {
unsigned ID;
SmallVector<unsigned, 4> Dependencies;
ASTFileSignature Signature;
};
struct ImportedModuleFileInfo {
off_t StoredSize;
time_t StoredModTime;
ASTFileSignature StoredSignature;
ImportedModuleFileInfo(off_t Size, time_t ModTime, ASTFileSignature Sig)
: StoredSize(Size), StoredModTime(ModTime), StoredSignature(Sig) {}
};
class GlobalModuleIndexBuilder {
FileManager &FileMgr;
const PCHContainerReader &PCHContainerRdr;
typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
ModuleFilesMap ModuleFiles;
typedef std::multimap<const FileEntry *, ImportedModuleFileInfo>
ImportedModuleFilesMap;
ImportedModuleFilesMap ImportedModuleFiles;
typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
InterestingIdentifierMap InterestingIdentifiers;
void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
= ModuleFiles.find(File);
if (Known != ModuleFiles.end())
return Known->second;
unsigned NewID = ModuleFiles.size();
ModuleFileInfo &Info = ModuleFiles[File];
Info.ID = NewID;
return Info;
}
public:
explicit GlobalModuleIndexBuilder(
FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr)
: FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr) {}
llvm::Error loadModuleFile(const FileEntry *File);
bool writeIndex(llvm::BitstreamWriter &Stream);
};
}
static void emitBlockID(unsigned ID, const char *Name,
llvm::BitstreamWriter &Stream,
SmallVectorImpl<uint64_t> &Record) {
Record.clear();
Record.push_back(ID);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
if (!Name || Name[0] == 0) return;
Record.clear();
while (*Name)
Record.push_back(*Name++);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
}
static void emitRecordID(unsigned ID, const char *Name,
llvm::BitstreamWriter &Stream,
SmallVectorImpl<uint64_t> &Record) {
Record.clear();
Record.push_back(ID);
while (*Name)
Record.push_back(*Name++);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
}
void
GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
SmallVector<uint64_t, 64> Record;
Stream.EnterBlockInfoBlock();
#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
#define RECORD(X) emitRecordID(X, #X, Stream, Record)
BLOCK(GLOBAL_INDEX_BLOCK);
RECORD(INDEX_METADATA);
RECORD(MODULE);
RECORD(IDENTIFIER_INDEX);
#undef RECORD
#undef BLOCK
Stream.ExitBlock();
}
namespace {
class InterestingASTIdentifierLookupTrait
: public serialization::reader::ASTIdentifierLookupTraitBase {
public:
typedef std::pair<StringRef, bool> data_type;
data_type ReadData(const internal_key_type& k,
const unsigned char* d,
unsigned DataLen) {
using namespace llvm::support;
unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
bool IsInteresting = RawID & 0x01;
return std::make_pair(k, IsInteresting);
}
};
}
llvm::Error GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
auto Buffer = FileMgr.getBufferForFile(File, true);
if (!Buffer)
return llvm::createStringError(Buffer.getError(),
"failed getting buffer for module file");
llvm::BitstreamCursor InStream(PCHContainerRdr.ExtractPCH(**Buffer));
for (unsigned char C : {'C', 'P', 'C', 'H'})
if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = InStream.Read(8)) {
if (Res.get() != C)
return llvm::createStringError(std::errc::illegal_byte_sequence,
"expected signature CPCH");
} else
return Res.takeError();
unsigned ID = getModuleFileInfo(File).ID;
enum { Other, ControlBlock, ASTBlock, DiagnosticOptionsBlock } State = Other;
bool Done = false;
while (!Done) {
Expected<llvm::BitstreamEntry> MaybeEntry = InStream.advance();
if (!MaybeEntry)
return MaybeEntry.takeError();
llvm::BitstreamEntry Entry = MaybeEntry.get();
switch (Entry.Kind) {
case llvm::BitstreamEntry::Error:
Done = true;
continue;
case llvm::BitstreamEntry::Record:
if (State == Other) {
if (llvm::Expected<unsigned> Skipped = InStream.skipRecord(Entry.ID))
continue;
else
return Skipped.takeError();
}
break;
case llvm::BitstreamEntry::SubBlock:
if (Entry.ID == CONTROL_BLOCK_ID) {
if (llvm::Error Err = InStream.EnterSubBlock(CONTROL_BLOCK_ID))
return Err;
State = ControlBlock;
continue;
}
if (Entry.ID == AST_BLOCK_ID) {
if (llvm::Error Err = InStream.EnterSubBlock(AST_BLOCK_ID))
return Err;
State = ASTBlock;
continue;
}
if (Entry.ID == UNHASHED_CONTROL_BLOCK_ID) {
if (llvm::Error Err = InStream.EnterSubBlock(UNHASHED_CONTROL_BLOCK_ID))
return Err;
State = DiagnosticOptionsBlock;
continue;
}
if (llvm::Error Err = InStream.SkipBlock())
return Err;
continue;
case llvm::BitstreamEntry::EndBlock:
State = Other;
continue;
}
SmallVector<uint64_t, 64> Record;
StringRef Blob;
Expected<unsigned> MaybeCode = InStream.readRecord(Entry.ID, Record, &Blob);
if (!MaybeCode)
return MaybeCode.takeError();
unsigned Code = MaybeCode.get();
if (State == ControlBlock && Code == IMPORTS) {
unsigned Idx = 0, N = Record.size();
while (Idx < N) {
++Idx;
++Idx;
off_t StoredSize = (off_t)Record[Idx++];
time_t StoredModTime = (time_t)Record[Idx++];
auto FirstSignatureByte = Record.begin() + Idx;
ASTFileSignature StoredSignature = ASTFileSignature::create(
FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
Idx += ASTFileSignature::size;
Idx += Record[Idx] + 1;
unsigned Length = Record[Idx++];
SmallString<128> ImportedFile(Record.begin() + Idx,
Record.begin() + Idx + Length);
Idx += Length;
auto DependsOnFile
= FileMgr.getFile(ImportedFile, false,
false);
if (!DependsOnFile)
return llvm::createStringError(std::errc::bad_file_descriptor,
"imported file \"%s\" not found",
ImportedFile.c_str());
ImportedModuleFiles.insert(std::make_pair(
*DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
StoredSignature)));
unsigned DependsOnID = getModuleFileInfo(*DependsOnFile).ID;
getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
}
continue;
}
if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
typedef llvm::OnDiskIterableChainedHashTable<
InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
std::unique_ptr<InterestingIdentifierTable> Table(
InterestingIdentifierTable::Create(
(const unsigned char *)Blob.data() + Record[0],
(const unsigned char *)Blob.data() + sizeof(uint32_t),
(const unsigned char *)Blob.data()));
for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
DEnd = Table->data_end();
D != DEnd; ++D) {
std::pair<StringRef, bool> Ident = *D;
if (Ident.second)
InterestingIdentifiers[Ident.first].push_back(ID);
else
(void)InterestingIdentifiers[Ident.first];
}
}
if (State == DiagnosticOptionsBlock && Code == SIGNATURE)
getModuleFileInfo(File).Signature = ASTFileSignature::create(
Record.begin(), Record.begin() + ASTFileSignature::size);
}
return llvm::Error::success();
}
namespace {
class IdentifierIndexWriterTrait {
public:
typedef StringRef key_type;
typedef StringRef key_type_ref;
typedef SmallVector<unsigned, 2> data_type;
typedef const SmallVector<unsigned, 2> &data_type_ref;
typedef unsigned hash_value_type;
typedef unsigned offset_type;
static hash_value_type ComputeHash(key_type_ref Key) {
return llvm::djbHash(Key);
}
std::pair<unsigned,unsigned>
EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
using namespace llvm::support;
endian::Writer LE(Out, little);
unsigned KeyLen = Key.size();
unsigned DataLen = Data.size() * 4;
LE.write<uint16_t>(KeyLen);
LE.write<uint16_t>(DataLen);
return std::make_pair(KeyLen, DataLen);
}
void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
Out.write(Key.data(), KeyLen);
}
void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
unsigned DataLen) {
using namespace llvm::support;
for (unsigned I = 0, N = Data.size(); I != N; ++I)
endian::write<uint32_t>(Out, Data[I], little);
}
};
}
bool GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
for (auto MapEntry : ImportedModuleFiles) {
auto *File = MapEntry.first;
ImportedModuleFileInfo &Info = MapEntry.second;
if (getModuleFileInfo(File).Signature) {
if (getModuleFileInfo(File).Signature != Info.StoredSignature)
return true;
} else if (Info.StoredSize != File->getSize() ||
Info.StoredModTime != File->getModificationTime())
return true;
}
using namespace llvm;
llvm::TimeTraceScope TimeScope("Module WriteIndex");
Stream.Emit((unsigned)'B', 8);
Stream.Emit((unsigned)'C', 8);
Stream.Emit((unsigned)'G', 8);
Stream.Emit((unsigned)'I', 8);
emitBlockInfoBlock(Stream);
Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
SmallVector<uint64_t, 2> Record;
Record.push_back(CurrentVersion);
Stream.EmitRecord(INDEX_METADATA, Record);
for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
MEnd = ModuleFiles.end();
M != MEnd; ++M) {
Record.clear();
Record.push_back(M->second.ID);
Record.push_back(M->first->getSize());
Record.push_back(M->first->getModificationTime());
StringRef Name(M->first->getName());
Record.push_back(Name.size());
Record.append(Name.begin(), Name.end());
Record.push_back(M->second.Dependencies.size());
Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
Stream.EmitRecord(MODULE, Record);
}
{
llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
IdentifierIndexWriterTrait Trait;
for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
IEnd = InterestingIdentifiers.end();
I != IEnd; ++I) {
Generator.insert(I->first(), I->second, Trait);
}
SmallString<4096> IdentifierTable;
uint32_t BucketOffset;
{
using namespace llvm::support;
llvm::raw_svector_ostream Out(IdentifierTable);
endian::write<uint32_t>(Out, 0, little);
BucketOffset = Generator.Emit(Out, Trait);
}
auto Abbrev = std::make_shared<BitCodeAbbrev>();
Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
uint64_t Record[] = {IDENTIFIER_INDEX, BucketOffset};
Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
}
Stream.ExitBlock();
return false;
}
llvm::Error
GlobalModuleIndex::writeIndex(FileManager &FileMgr,
const PCHContainerReader &PCHContainerRdr,
StringRef Path) {
llvm::SmallString<128> IndexPath;
IndexPath += Path;
llvm::sys::path::append(IndexPath, IndexFileName);
llvm::LockFileManager Locked(IndexPath);
switch (Locked) {
case llvm::LockFileManager::LFS_Error:
return llvm::createStringError(std::errc::io_error, "LFS error");
case llvm::LockFileManager::LFS_Owned:
break;
case llvm::LockFileManager::LFS_Shared:
return llvm::createStringError(std::errc::device_or_resource_busy,
"someone else is building the index");
}
GlobalModuleIndexBuilder Builder(FileMgr, PCHContainerRdr);
std::error_code EC;
for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
D != DEnd && !EC;
D.increment(EC)) {
if (llvm::sys::path::extension(D->path()) != ".pcm") {
if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
return llvm::createStringError(std::errc::device_or_resource_busy,
"someone else is building the index");
continue;
}
auto ModuleFile = FileMgr.getFile(D->path());
if (!ModuleFile)
continue;
if (llvm::Error Err = Builder.loadModuleFile(*ModuleFile))
return Err;
}
SmallString<16> OutputBuffer;
{
llvm::BitstreamWriter OutputStream(OutputBuffer);
if (Builder.writeIndex(OutputStream))
return llvm::createStringError(std::errc::io_error,
"failed writing index");
}
return llvm::writeFileAtomically((IndexPath + "-%%%%%%%%").str(), IndexPath,
OutputBuffer);
}
namespace {
class GlobalIndexIdentifierIterator : public IdentifierIterator {
IdentifierIndexTable::key_iterator Current;
IdentifierIndexTable::key_iterator End;
public:
explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
Current = Idx.key_begin();
End = Idx.key_end();
}
StringRef Next() override {
if (Current == End)
return StringRef();
StringRef Result = *Current;
++Current;
return Result;
}
};
}
IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
IdentifierIndexTable &Table =
*static_cast<IdentifierIndexTable *>(IdentifierIndex);
return new GlobalIndexIdentifierIterator(Table);
}