Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp
35266 views
//===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"9#include "llvm/ADT/Hashing.h"10#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"11#include "llvm/IR/Mangler.h"12#include "llvm/IR/Module.h"13#include "llvm/Support/FormatVariadic.h"14#include <string>1516using namespace llvm;17using namespace llvm::orc;1819static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,20StringRef Suffix,21GVPredicate ShouldExtract) {2223auto DeleteExtractedDefs = [](GlobalValue &GV) {24// Bump the linkage: this global will be provided by the external module.25GV.setLinkage(GlobalValue::ExternalLinkage);2627// Delete the definition in the source module.28if (isa<Function>(GV)) {29auto &F = cast<Function>(GV);30F.deleteBody();31F.setPersonalityFn(nullptr);32} else if (isa<GlobalVariable>(GV)) {33cast<GlobalVariable>(GV).setInitializer(nullptr);34} else if (isa<GlobalAlias>(GV)) {35// We need to turn deleted aliases into function or variable decls based36// on the type of their aliasee.37auto &A = cast<GlobalAlias>(GV);38Constant *Aliasee = A.getAliasee();39assert(A.hasName() && "Anonymous alias?");40assert(Aliasee->hasName() && "Anonymous aliasee");41std::string AliasName = std::string(A.getName());4243if (isa<Function>(Aliasee)) {44auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));45A.replaceAllUsesWith(F);46A.eraseFromParent();47F->setName(AliasName);48} else if (isa<GlobalVariable>(Aliasee)) {49auto *G = cloneGlobalVariableDecl(*A.getParent(),50*cast<GlobalVariable>(Aliasee));51A.replaceAllUsesWith(G);52A.eraseFromParent();53G->setName(AliasName);54} else55llvm_unreachable("Alias to unsupported type");56} else57llvm_unreachable("Unsupported global type");58};5960auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);61NewTSM.withModuleDo([&](Module &M) {62M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());63});6465return NewTSM;66}6768namespace llvm {69namespace orc {7071class PartitioningIRMaterializationUnit : public IRMaterializationUnit {72public:73PartitioningIRMaterializationUnit(ExecutionSession &ES,74const IRSymbolMapper::ManglingOptions &MO,75ThreadSafeModule TSM,76CompileOnDemandLayer &Parent)77: IRMaterializationUnit(ES, MO, std::move(TSM)), Parent(Parent) {}7879PartitioningIRMaterializationUnit(80ThreadSafeModule TSM, Interface I,81SymbolNameToDefinitionMap SymbolToDefinition,82CompileOnDemandLayer &Parent)83: IRMaterializationUnit(std::move(TSM), std::move(I),84std::move(SymbolToDefinition)),85Parent(Parent) {}8687private:88void materialize(std::unique_ptr<MaterializationResponsibility> R) override {89Parent.emitPartition(std::move(R), std::move(TSM),90std::move(SymbolToDefinition));91}9293void discard(const JITDylib &V, const SymbolStringPtr &Name) override {94// All original symbols were materialized by the CODLayer and should be95// final. The function bodies provided by M should never be overridden.96llvm_unreachable("Discard should never be called on an "97"ExtractingIRMaterializationUnit");98}99100mutable std::mutex SourceModuleMutex;101CompileOnDemandLayer &Parent;102};103104std::optional<CompileOnDemandLayer::GlobalValueSet>105CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {106return std::move(Requested);107}108109std::optional<CompileOnDemandLayer::GlobalValueSet>110CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {111return std::nullopt;112}113114CompileOnDemandLayer::CompileOnDemandLayer(115ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,116IndirectStubsManagerBuilder BuildIndirectStubsManager)117: IRLayer(ES, BaseLayer.getManglingOptions()), BaseLayer(BaseLayer),118LCTMgr(LCTMgr),119BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}120121void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {122this->Partition = std::move(Partition);123}124125void CompileOnDemandLayer::setImplMap(ImplSymbolMap *Imp) {126this->AliaseeImpls = Imp;127}128void CompileOnDemandLayer::emit(129std::unique_ptr<MaterializationResponsibility> R, ThreadSafeModule TSM) {130assert(TSM && "Null module");131132auto &ES = getExecutionSession();133134// Sort the callables and non-callables, build re-exports and lodge the135// actual module with the implementation dylib.136auto &PDR = getPerDylibResources(R->getTargetJITDylib());137138SymbolAliasMap NonCallables;139SymbolAliasMap Callables;140TSM.withModuleDo([&](Module &M) {141// First, do some cleanup on the module:142cleanUpModule(M);143});144145for (auto &KV : R->getSymbols()) {146auto &Name = KV.first;147auto &Flags = KV.second;148if (Flags.isCallable())149Callables[Name] = SymbolAliasMapEntry(Name, Flags);150else151NonCallables[Name] = SymbolAliasMapEntry(Name, Flags);152}153154// Create a partitioning materialization unit and lodge it with the155// implementation dylib.156if (auto Err = PDR.getImplDylib().define(157std::make_unique<PartitioningIRMaterializationUnit>(158ES, *getManglingOptions(), std::move(TSM), *this))) {159ES.reportError(std::move(Err));160R->failMaterialization();161return;162}163164if (!NonCallables.empty())165if (auto Err =166R->replace(reexports(PDR.getImplDylib(), std::move(NonCallables),167JITDylibLookupFlags::MatchAllSymbols))) {168getExecutionSession().reportError(std::move(Err));169R->failMaterialization();170return;171}172if (!Callables.empty()) {173if (auto Err = R->replace(174lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(),175std::move(Callables), AliaseeImpls))) {176getExecutionSession().reportError(std::move(Err));177R->failMaterialization();178return;179}180}181}182183CompileOnDemandLayer::PerDylibResources &184CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {185std::lock_guard<std::mutex> Lock(CODLayerMutex);186187auto I = DylibResources.find(&TargetD);188if (I == DylibResources.end()) {189auto &ImplD =190getExecutionSession().createBareJITDylib(TargetD.getName() + ".impl");191JITDylibSearchOrder NewLinkOrder;192TargetD.withLinkOrderDo([&](const JITDylibSearchOrder &TargetLinkOrder) {193NewLinkOrder = TargetLinkOrder;194});195196assert(!NewLinkOrder.empty() && NewLinkOrder.front().first == &TargetD &&197NewLinkOrder.front().second ==198JITDylibLookupFlags::MatchAllSymbols &&199"TargetD must be at the front of its own search order and match "200"non-exported symbol");201NewLinkOrder.insert(std::next(NewLinkOrder.begin()),202{&ImplD, JITDylibLookupFlags::MatchAllSymbols});203ImplD.setLinkOrder(NewLinkOrder, false);204TargetD.setLinkOrder(std::move(NewLinkOrder), false);205206PerDylibResources PDR(ImplD, BuildIndirectStubsManager());207I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first;208}209210return I->second;211}212213void CompileOnDemandLayer::cleanUpModule(Module &M) {214for (auto &F : M.functions()) {215if (F.isDeclaration())216continue;217218if (F.hasAvailableExternallyLinkage()) {219F.deleteBody();220F.setPersonalityFn(nullptr);221continue;222}223}224}225226void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {227// Expands the partition to ensure the following rules hold:228// (1) If any alias is in the partition, its aliasee is also in the partition.229// (2) If any aliasee is in the partition, its aliases are also in the230// partiton.231// (3) If any global variable is in the partition then all global variables232// are in the partition.233assert(!Partition.empty() && "Unexpected empty partition");234235const Module &M = *(*Partition.begin())->getParent();236bool ContainsGlobalVariables = false;237std::vector<const GlobalValue *> GVsToAdd;238239for (const auto *GV : Partition)240if (isa<GlobalAlias>(GV))241GVsToAdd.push_back(242cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));243else if (isa<GlobalVariable>(GV))244ContainsGlobalVariables = true;245246for (auto &A : M.aliases())247if (Partition.count(cast<GlobalValue>(A.getAliasee())))248GVsToAdd.push_back(&A);249250if (ContainsGlobalVariables)251for (auto &G : M.globals())252GVsToAdd.push_back(&G);253254for (const auto *GV : GVsToAdd)255Partition.insert(GV);256}257258void CompileOnDemandLayer::emitPartition(259std::unique_ptr<MaterializationResponsibility> R, ThreadSafeModule TSM,260IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {261262// FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the263// extracted module key, extracted module, and source module key264// together. This could be used, for example, to provide a specific265// memory manager instance to the linking layer.266267auto &ES = getExecutionSession();268GlobalValueSet RequestedGVs;269for (auto &Name : R->getRequestedSymbols()) {270if (Name == R->getInitializerSymbol())271TSM.withModuleDo([&](Module &M) {272for (auto &GV : getStaticInitGVs(M))273RequestedGVs.insert(&GV);274});275else {276assert(Defs.count(Name) && "No definition for symbol");277RequestedGVs.insert(Defs[Name]);278}279}280281/// Perform partitioning with the context lock held, since the partition282/// function is allowed to access the globals to compute the partition.283auto GVsToExtract =284TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); });285286// Take a 'None' partition to mean the whole module (as opposed to an empty287// partition, which means "materialize nothing"). Emit the whole module288// unmodified to the base layer.289if (GVsToExtract == std::nullopt) {290Defs.clear();291BaseLayer.emit(std::move(R), std::move(TSM));292return;293}294295// If the partition is empty, return the whole module to the symbol table.296if (GVsToExtract->empty()) {297if (auto Err =298R->replace(std::make_unique<PartitioningIRMaterializationUnit>(299std::move(TSM),300MaterializationUnit::Interface(R->getSymbols(),301R->getInitializerSymbol()),302std::move(Defs), *this))) {303getExecutionSession().reportError(std::move(Err));304R->failMaterialization();305return;306}307return;308}309310// Ok -- we actually need to partition the symbols. Promote the symbol311// linkages/names, expand the partition to include any required symbols312// (i.e. symbols that can't be separated from our partition), and313// then extract the partition.314//315// FIXME: We apply this promotion once per partitioning. It's safe, but316// overkill.317auto ExtractedTSM =318TSM.withModuleDo([&](Module &M) -> Expected<ThreadSafeModule> {319auto PromotedGlobals = PromoteSymbols(M);320if (!PromotedGlobals.empty()) {321322MangleAndInterner Mangle(ES, M.getDataLayout());323SymbolFlagsMap SymbolFlags;324IRSymbolMapper::add(ES, *getManglingOptions(),325PromotedGlobals, SymbolFlags);326327if (auto Err = R->defineMaterializing(SymbolFlags))328return std::move(Err);329}330331expandPartition(*GVsToExtract);332333// Submodule name is given by hashing the names of the globals.334std::string SubModuleName;335{336std::vector<const GlobalValue*> HashGVs;337HashGVs.reserve(GVsToExtract->size());338for (const auto *GV : *GVsToExtract)339HashGVs.push_back(GV);340llvm::sort(HashGVs, [](const GlobalValue *LHS, const GlobalValue *RHS) {341return LHS->getName() < RHS->getName();342});343hash_code HC(0);344for (const auto *GV : HashGVs) {345assert(GV->hasName() && "All GVs to extract should be named by now");346auto GVName = GV->getName();347HC = hash_combine(HC, hash_combine_range(GVName.begin(), GVName.end()));348}349raw_string_ostream(SubModuleName)350<< ".submodule."351<< formatv(sizeof(size_t) == 8 ? "{0:x16}" : "{0:x8}",352static_cast<size_t>(HC))353<< ".ll";354}355356// Extract the requested partiton (plus any necessary aliases) and357// put the rest back into the impl dylib.358auto ShouldExtract = [&](const GlobalValue &GV) -> bool {359return GVsToExtract->count(&GV);360};361362return extractSubModule(TSM, SubModuleName , ShouldExtract);363});364365if (!ExtractedTSM) {366ES.reportError(ExtractedTSM.takeError());367R->failMaterialization();368return;369}370371if (auto Err = R->replace(std::make_unique<PartitioningIRMaterializationUnit>(372ES, *getManglingOptions(), std::move(TSM), *this))) {373ES.reportError(std::move(Err));374R->failMaterialization();375return;376}377BaseLayer.emit(std::move(R), std::move(*ExtractedTSM));378}379380} // end namespace orc381} // end namespace llvm382383384