#include "clang/Serialization/ModuleManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LLVM.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Serialization/GlobalModuleIndex.h"
#include "clang/Serialization/InMemoryModuleCache.h"
#include "clang/Serialization/ModuleFile.h"
#include "clang/Serialization/PCHContainerOperations.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/DOTGraphTraits.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <algorithm>
#include <cassert>
#include <memory>
#include <string>
#include <system_error>
using namespace clang;
using namespace serialization;
ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
auto Entry = FileMgr.getFile(Name, false,
false);
if (Entry)
return lookup(*Entry);
return nullptr;
}
ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
if (const FileEntry *File = Mod->getASTFile())
return lookup(File);
return nullptr;
}
ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
auto Known = Modules.find(File);
if (Known == Modules.end())
return nullptr;
return Known->second;
}
std::unique_ptr<llvm::MemoryBuffer>
ModuleManager::lookupBuffer(StringRef Name) {
auto Entry = FileMgr.getFile(Name, false,
false);
if (!Entry)
return nullptr;
return std::move(InMemoryBuffers[*Entry]);
}
static bool checkSignature(ASTFileSignature Signature,
ASTFileSignature ExpectedSignature,
std::string &ErrorStr) {
if (!ExpectedSignature || Signature == ExpectedSignature)
return false;
ErrorStr =
Signature ? "signature mismatch" : "could not read module signature";
return true;
}
static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
SourceLocation ImportLoc) {
if (ImportedBy) {
MF.ImportedBy.insert(ImportedBy);
ImportedBy->Imports.insert(&MF);
} else {
if (!MF.DirectlyImported)
MF.ImportLoc = ImportLoc;
MF.DirectlyImported = true;
}
}
ModuleManager::AddModuleResult
ModuleManager::addModule(StringRef FileName, ModuleKind Type,
SourceLocation ImportLoc, ModuleFile *ImportedBy,
unsigned Generation,
off_t ExpectedSize, time_t ExpectedModTime,
ASTFileSignature ExpectedSignature,
ASTFileSignatureReader ReadSignature,
ModuleFile *&Module,
std::string &ErrorStr) {
Module = nullptr;
OptionalFileEntryRefDegradesToFileEntryPtr Entry;
if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
ExpectedModTime = 0;
}
if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
ErrorStr = "module file out of date";
return OutOfDate;
}
if (!Entry && FileName != "-") {
ErrorStr = "module file not found";
return Missing;
}
auto implicitModuleNamesMatch = [](ModuleKind Kind, const ModuleFile *MF,
const FileEntry *Entry) -> bool {
if (Kind != MK_ImplicitModule)
return true;
return Entry->getName() == MF->FileName;
};
if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
if (implicitModuleNamesMatch(Type, ModuleEntry, Entry)) {
if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
return OutOfDate;
Module = ModuleEntry;
updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
return AlreadyLoaded;
}
}
auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
NewModule->Index = Chain.size();
NewModule->FileName = FileName.str();
NewModule->File = Entry;
NewModule->ImportLoc = ImportLoc;
NewModule->InputFilesValidationTimestamp = 0;
if (NewModule->Kind == MK_ImplicitModule) {
std::string TimestampFilename = NewModule->getTimestampFilename();
llvm::vfs::Status Status;
if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
NewModule->InputFilesValidationTimestamp =
llvm::sys::toTimeT(Status.getLastModificationTime());
}
if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
Entry->closeFile();
} else if (llvm::MemoryBuffer *Buffer =
getModuleCache().lookupPCM(FileName)) {
NewModule->Buffer = Buffer;
Entry->closeFile();
} else if (getModuleCache().shouldBuildPCM(FileName)) {
Entry->closeFile();
return OutOfDate;
} else {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
if (FileName == "-") {
Buf = llvm::MemoryBuffer::getSTDIN();
} else {
Buf = FileMgr.getBufferForFile(NewModule->File,
true,
false);
}
if (!Buf) {
ErrorStr = Buf.getError().message();
return Missing;
}
NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
}
NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
ExpectedSignature, ErrorStr))
return OutOfDate;
Module = Modules[Entry] = NewModule.get();
updateModuleImports(*NewModule, ImportedBy, ImportLoc);
if (!NewModule->isModule())
PCHChain.push_back(NewModule.get());
if (!ImportedBy)
Roots.push_back(NewModule.get());
Chain.push_back(std::move(NewModule));
return NewlyLoaded;
}
void ModuleManager::removeModules(ModuleIterator First, ModuleMap *modMap) {
auto Last = end();
if (First == Last)
return;
VisitOrder.clear();
llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
(llvm::pointer_iterator<ModuleIterator>(First)),
(llvm::pointer_iterator<ModuleIterator>(Last)));
auto IsVictim = [&](ModuleFile *MF) {
return victimSet.count(MF);
};
for (auto I = begin(); I != First; ++I) {
I->Imports.remove_if(IsVictim);
I->ImportedBy.remove_if(IsVictim);
}
llvm::erase_if(Roots, IsVictim);
for (auto I = First; I != Last; ++I) {
if (!I->isModule()) {
PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
break;
}
}
for (ModuleIterator victim = First; victim != Last; ++victim) {
Modules.erase(victim->File);
if (modMap) {
StringRef ModuleName = victim->ModuleName;
if (Module *mod = modMap->findModule(ModuleName)) {
mod->setASTFile(None);
}
}
}
Chain.erase(Chain.begin() + (First - begin()), Chain.end());
}
void
ModuleManager::addInMemoryBuffer(StringRef FileName,
std::unique_ptr<llvm::MemoryBuffer> Buffer) {
const FileEntry *Entry =
FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
InMemoryBuffers[Entry] = std::move(Buffer);
}
std::unique_ptr<ModuleManager::VisitState> ModuleManager::allocateVisitState() {
if (FirstVisitState) {
auto Result = std::move(FirstVisitState);
FirstVisitState = std::move(Result->NextState);
return Result;
}
return std::make_unique<VisitState>(size());
}
void ModuleManager::returnVisitState(std::unique_ptr<VisitState> State) {
assert(State->NextState == nullptr && "Visited state is in list?");
State->NextState = std::move(FirstVisitState);
FirstVisitState = std::move(State);
}
void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
GlobalIndex = Index;
if (!GlobalIndex) {
ModulesInCommonWithGlobalIndex.clear();
return;
}
for (ModuleFile &M : *this)
if (!GlobalIndex->loadedModuleFile(&M))
ModulesInCommonWithGlobalIndex.push_back(&M);
}
void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
return;
ModulesInCommonWithGlobalIndex.push_back(MF);
}
ModuleManager::ModuleManager(FileManager &FileMgr,
InMemoryModuleCache &ModuleCache,
const PCHContainerReader &PCHContainerRdr,
const HeaderSearch &HeaderSearchInfo)
: FileMgr(FileMgr), ModuleCache(&ModuleCache),
PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
if (VisitOrder.size() != Chain.size()) {
unsigned N = size();
VisitOrder.clear();
VisitOrder.reserve(N);
SmallVector<ModuleFile *, 4> Queue;
Queue.reserve(N);
llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
UnusedIncomingEdges.resize(size());
for (ModuleFile &M : llvm::reverse(*this)) {
unsigned Size = M.ImportedBy.size();
UnusedIncomingEdges[M.Index] = Size;
if (!Size)
Queue.push_back(&M);
}
while (!Queue.empty()) {
ModuleFile *CurrentModule = Queue.pop_back_val();
VisitOrder.push_back(CurrentModule);
for (ModuleFile *M : llvm::reverse(CurrentModule->Imports)) {
unsigned &NumUnusedEdges = UnusedIncomingEdges[M->Index];
if (NumUnusedEdges && (--NumUnusedEdges == 0))
Queue.push_back(M);
}
}
assert(VisitOrder.size() == N && "Visitation order is wrong?");
FirstVisitState = nullptr;
}
auto State = allocateVisitState();
unsigned VisitNumber = State->NextVisitNumber++;
if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
{
ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
if (!ModuleFilesHit->count(M))
State->VisitNumber[M->Index] = VisitNumber;
}
}
for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
ModuleFile *CurrentModule = VisitOrder[I];
if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
continue;
assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
State->VisitNumber[CurrentModule->Index] = VisitNumber;
if (!Visitor(*CurrentModule))
continue;
ModuleFile *NextModule = CurrentModule;
do {
for (llvm::SetVector<ModuleFile *>::iterator
M = NextModule->Imports.begin(),
MEnd = NextModule->Imports.end();
M != MEnd; ++M) {
if (State->VisitNumber[(*M)->Index] != VisitNumber) {
State->Stack.push_back(*M);
State->VisitNumber[(*M)->Index] = VisitNumber;
}
}
if (State->Stack.empty())
break;
NextModule = State->Stack.pop_back_val();
} while (true);
}
returnVisitState(std::move(State));
}
bool ModuleManager::lookupModuleFile(StringRef FileName, off_t ExpectedSize,
time_t ExpectedModTime,
Optional<FileEntryRef> &File) {
File = None;
if (FileName == "-")
return false;
Optional<FileEntryRef> FileOrErr =
expectedToOptional(FileMgr.getFileRef(FileName, true,
false));
if (!FileOrErr)
return false;
File = *FileOrErr;
if ((ExpectedSize && ExpectedSize != File->getSize()) ||
(ExpectedModTime && ExpectedModTime != File->getModificationTime()))
return true;
return false;
}
#ifndef NDEBUG
namespace llvm {
template<>
struct GraphTraits<ModuleManager> {
using NodeRef = ModuleFile *;
using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
static ChildIteratorType child_begin(NodeRef Node) {
return Node->Imports.begin();
}
static ChildIteratorType child_end(NodeRef Node) {
return Node->Imports.end();
}
static nodes_iterator nodes_begin(const ModuleManager &Manager) {
return nodes_iterator(Manager.begin());
}
static nodes_iterator nodes_end(const ModuleManager &Manager) {
return nodes_iterator(Manager.end());
}
};
template<>
struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
explicit DOTGraphTraits(bool IsSimple = false)
: DefaultDOTGraphTraits(IsSimple) {}
static bool renderGraphFromBottomUp() { return true; }
std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
return M->ModuleName;
}
};
}
void ModuleManager::viewGraph() {
llvm::ViewGraph(*this, "Modules");
}
#endif