1 //===- CompileOnDemandLayer.h - Compile each function on demand -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // JIT layer for breaking up modules and inserting callbacks to allow
11 // individual functions to be compiled on demand.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
16 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
18 #include "IndirectionUtils.h"
19 #include "LambdaResolver.h"
20 #include "LogicalDylib.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Support/Debug.h"
32 /// @brief Compile-on-demand layer.
34 /// When a module is added to this layer a stub is created for each of its
35 /// function definitions. The stubs and other global values are immediately
36 /// added to the layer below. When a stub is called it triggers the extraction
37 /// of the function body from the original module. The extracted body is then
38 /// compiled and executed.
39 template <typename BaseLayerT,
40 typename CompileCallbackMgrT = JITCompileCallbackManager,
41 typename IndirectStubsMgrT = IndirectStubsManager>
42 class CompileOnDemandLayer {
45 template <typename MaterializerFtor>
46 class LambdaMaterializer final : public ValueMaterializer {
48 LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
49 Value *materializeDeclFor(Value *V) final { return M(V); }
55 template <typename MaterializerFtor>
56 LambdaMaterializer<MaterializerFtor>
57 createLambdaMaterializer(MaterializerFtor M) {
58 return LambdaMaterializer<MaterializerFtor>(std::move(M));
61 typedef typename BaseLayerT::ModuleSetHandleT BaseLayerModuleSetHandleT;
63 // Provide type-erasure for the Modules and MemoryManagers.
64 template <typename ResourceT>
67 ResourceOwner() = default;
68 ResourceOwner(const ResourceOwner&) = delete;
69 ResourceOwner& operator=(const ResourceOwner&) = delete;
70 virtual ~ResourceOwner() { }
71 virtual ResourceT& getResource() const = 0;
74 template <typename ResourceT, typename ResourcePtrT>
75 class ResourceOwnerImpl : public ResourceOwner<ResourceT> {
77 ResourceOwnerImpl(ResourcePtrT ResourcePtr)
78 : ResourcePtr(std::move(ResourcePtr)) {}
79 ResourceT& getResource() const override { return *ResourcePtr; }
81 ResourcePtrT ResourcePtr;
84 template <typename ResourceT, typename ResourcePtrT>
85 std::unique_ptr<ResourceOwner<ResourceT>>
86 wrapOwnership(ResourcePtrT ResourcePtr) {
87 typedef ResourceOwnerImpl<ResourceT, ResourcePtrT> RO;
88 return llvm::make_unique<RO>(std::move(ResourcePtr));
91 struct LogicalModuleResources {
92 std::unique_ptr<ResourceOwner<Module>> SourceModule;
93 std::set<const Function*> StubsToClone;
94 std::unique_ptr<IndirectStubsMgrT> StubsMgr;
96 LogicalModuleResources() = default;
98 // Explicit move constructor to make MSVC happy.
99 LogicalModuleResources(LogicalModuleResources &&Other)
100 : SourceModule(std::move(Other.SourceModule)),
101 StubsToClone(std::move(Other.StubsToClone)),
102 StubsMgr(std::move(Other.StubsMgr)) {}
104 // Explicit move assignment to make MSVC happy.
105 LogicalModuleResources& operator=(LogicalModuleResources &&Other) {
106 SourceModule = std::move(Other.SourceModule);
107 StubsToClone = std::move(Other.StubsToClone);
108 StubsMgr = std::move(Other.StubsMgr);
111 JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
112 if (Name.endswith("$stub_ptr") && !ExportedSymbolsOnly) {
113 assert(!ExportedSymbolsOnly && "Stubs are never exported");
114 return StubsMgr->findPointer(Name.drop_back(9));
116 return StubsMgr->findStub(Name, ExportedSymbolsOnly);
121 struct LogicalDylibResources {
122 typedef std::function<RuntimeDyld::SymbolInfo(const std::string&)>
125 typedef std::function<typename BaseLayerT::ModuleSetHandleT(
127 std::unique_ptr<Module>,
128 std::unique_ptr<RuntimeDyld::SymbolResolver>)>
131 LogicalDylibResources() = default;
133 // Explicit move constructor to make MSVC happy.
134 LogicalDylibResources(LogicalDylibResources &&Other)
135 : ExternalSymbolResolver(std::move(Other.ExternalSymbolResolver)),
136 MemMgr(std::move(Other.MemMgr)),
137 ModuleAdder(std::move(Other.ModuleAdder)) {}
139 // Explicit move assignment operator to make MSVC happy.
140 LogicalDylibResources& operator=(LogicalDylibResources &&Other) {
141 ExternalSymbolResolver = std::move(Other.ExternalSymbolResolver);
142 MemMgr = std::move(Other.MemMgr);
143 ModuleAdder = std::move(Other.ModuleAdder);
147 SymbolResolverFtor ExternalSymbolResolver;
148 std::unique_ptr<ResourceOwner<RuntimeDyld::MemoryManager>> MemMgr;
149 ModuleAdderFtor ModuleAdder;
152 typedef LogicalDylib<BaseLayerT, LogicalModuleResources,
153 LogicalDylibResources> CODLogicalDylib;
155 typedef typename CODLogicalDylib::LogicalModuleHandle LogicalModuleHandle;
156 typedef std::list<CODLogicalDylib> LogicalDylibList;
160 /// @brief Handle to a set of loaded modules.
161 typedef typename LogicalDylibList::iterator ModuleSetHandleT;
163 /// @brief Module partitioning functor.
164 typedef std::function<std::set<Function*>(Function&)> PartitioningFtor;
166 /// @brief Builder for IndirectStubsManagers.
167 typedef std::function<std::unique_ptr<IndirectStubsMgrT>()>
168 IndirectStubsManagerBuilderT;
170 /// @brief Construct a compile-on-demand layer instance.
171 CompileOnDemandLayer(BaseLayerT &BaseLayer, PartitioningFtor Partition,
172 CompileCallbackMgrT &CallbackMgr,
173 IndirectStubsManagerBuilderT CreateIndirectStubsManager,
174 bool CloneStubsIntoPartitions = true)
175 : BaseLayer(BaseLayer), Partition(Partition),
176 CompileCallbackMgr(CallbackMgr),
177 CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
178 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
180 /// @brief Add a module to the compile-on-demand layer.
181 template <typename ModuleSetT, typename MemoryManagerPtrT,
182 typename SymbolResolverPtrT>
183 ModuleSetHandleT addModuleSet(ModuleSetT Ms,
184 MemoryManagerPtrT MemMgr,
185 SymbolResolverPtrT Resolver) {
187 LogicalDylibs.push_back(CODLogicalDylib(BaseLayer));
188 auto &LDResources = LogicalDylibs.back().getDylibResources();
190 LDResources.ExternalSymbolResolver =
191 [Resolver](const std::string &Name) {
192 return Resolver->findSymbol(Name);
195 auto &MemMgrRef = *MemMgr;
197 wrapOwnership<RuntimeDyld::MemoryManager>(std::move(MemMgr));
199 LDResources.ModuleAdder =
200 [&MemMgrRef](BaseLayerT &B, std::unique_ptr<Module> M,
201 std::unique_ptr<RuntimeDyld::SymbolResolver> R) {
202 std::vector<std::unique_ptr<Module>> Ms;
203 Ms.push_back(std::move(M));
204 return B.addModuleSet(std::move(Ms), &MemMgrRef, std::move(R));
207 // Process each of the modules in this module set.
209 addLogicalModule(LogicalDylibs.back(), std::move(M));
211 return std::prev(LogicalDylibs.end());
214 /// @brief Remove the module represented by the given handle.
216 /// This will remove all modules in the layers below that were derived from
217 /// the module represented by H.
218 void removeModuleSet(ModuleSetHandleT H) {
219 LogicalDylibs.erase(H);
222 /// @brief Search for the given named symbol.
223 /// @param Name The name of the symbol to search for.
224 /// @param ExportedSymbolsOnly If true, search only for exported symbols.
225 /// @return A handle for the given named symbol, if it exists.
226 JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
227 for (auto LDI = LogicalDylibs.begin(), LDE = LogicalDylibs.end();
229 if (auto Symbol = findSymbolIn(LDI, Name, ExportedSymbolsOnly))
231 return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
234 /// @brief Get the address of a symbol provided by this layer, or some layer
236 JITSymbol findSymbolIn(ModuleSetHandleT H, const std::string &Name,
237 bool ExportedSymbolsOnly) {
238 return H->findSymbol(Name, ExportedSymbolsOnly);
243 template <typename ModulePtrT>
244 void addLogicalModule(CODLogicalDylib &LD, ModulePtrT SrcMPtr) {
246 // Bump the linkage and rename any anonymous/privote members in SrcM to
247 // ensure that everything will resolve properly after we partition SrcM.
248 makeAllSymbolsExternallyAccessible(*SrcMPtr);
250 // Create a logical module handle for SrcM within the logical dylib.
251 auto LMH = LD.createLogicalModule();
252 auto &LMResources = LD.getLogicalModuleResources(LMH);
254 LMResources.SourceModule = wrapOwnership<Module>(std::move(SrcMPtr));
256 Module &SrcM = LMResources.SourceModule->getResource();
258 // Create the GlobalValues module.
259 const DataLayout &DL = SrcM.getDataLayout();
260 auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(),
262 GVsM->setDataLayout(DL);
264 // Create function stubs.
265 ValueToValueMapTy VMap;
267 typename IndirectStubsMgrT::StubInitsMap StubInits;
268 for (auto &F : SrcM) {
269 // Skip declarations.
270 if (F.isDeclaration())
273 // Record all functions defined by this module.
274 if (CloneStubsIntoPartitions)
275 LMResources.StubsToClone.insert(&F);
277 // Create a callback, associate it with the stub for the function,
278 // and set the compile action to compile the partition containing the
280 auto CCInfo = CompileCallbackMgr.getCompileCallback();
281 StubInits[mangle(F.getName(), DL)] =
282 std::make_pair(CCInfo.getAddress(),
283 JITSymbolBase::flagsFromGlobalValue(F));
284 CCInfo.setCompileAction([this, &LD, LMH, &F]() {
285 return this->extractAndCompile(LD, LMH, F);
289 LMResources.StubsMgr = CreateIndirectStubsManager();
290 auto EC = LMResources.StubsMgr->createStubs(StubInits);
292 // FIXME: This should be propagated back to the user. Stub creation may
293 // fail for remote JITs.
294 assert(!EC && "Error generating stubs");
297 // Clone global variable decls.
298 for (auto &GV : SrcM.globals())
299 if (!GV.isDeclaration() && !VMap.count(&GV))
300 cloneGlobalVariableDecl(*GVsM, GV, &VMap);
303 for (auto &A : SrcM.aliases())
305 cloneGlobalAliasDecl(*GVsM, A, VMap);
307 // Now we need to clone the GV and alias initializers.
309 // Initializers may refer to functions declared (but not defined) in this
310 // module. Build a materializer to clone decls on demand.
311 auto Materializer = createLambdaMaterializer(
312 [this, &GVsM, &LMResources](Value *V) -> Value* {
313 if (auto *F = dyn_cast<Function>(V)) {
314 // Decls in the original module just get cloned.
315 if (F->isDeclaration())
316 return cloneFunctionDecl(*GVsM, *F);
318 // Definitions in the original module (which we have emitted stubs
319 // for at this point) get turned into a constant alias to the stub
321 const DataLayout &DL = GVsM->getDataLayout();
322 std::string FName = mangle(F->getName(), DL);
323 auto StubSym = LMResources.StubsMgr->findStub(FName, false);
324 unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType());
325 ConstantInt *StubAddr =
326 ConstantInt::get(GVsM->getContext(),
327 APInt(PtrBitWidth, StubSym.getAddress()));
328 Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr,
329 StubAddr, F->getType());
330 return GlobalAlias::create(F->getFunctionType(),
331 F->getType()->getAddressSpace(),
332 F->getLinkage(), F->getName(),
339 // Clone the global variable initializers.
340 for (auto &GV : SrcM.globals())
341 if (!GV.isDeclaration())
342 moveGlobalVariableInitializer(GV, VMap, &Materializer);
344 // Clone the global alias initializers.
345 for (auto &A : SrcM.aliases()) {
346 auto *NewA = cast<GlobalAlias>(VMap[&A]);
347 assert(NewA && "Alias not cloned?");
348 Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr,
350 NewA->setAliasee(cast<Constant>(Init));
353 // Build a resolver for the globals module and add it to the base layer.
354 auto GVsResolver = createLambdaResolver(
355 [&LD, LMH](const std::string &Name) {
356 auto &LMResources = LD.getLogicalModuleResources(LMH);
357 if (auto Sym = LMResources.StubsMgr->findStub(Name, false))
358 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
359 return LD.getDylibResources().ExternalSymbolResolver(Name);
361 [](const std::string &Name) {
362 return RuntimeDyld::SymbolInfo(nullptr);
366 LD.getDylibResources().ModuleAdder(BaseLayer, std::move(GVsM),
367 std::move(GVsResolver));
368 LD.addToLogicalModule(LMH, GVsH);
371 static std::string mangle(StringRef Name, const DataLayout &DL) {
372 std::string MangledName;
374 raw_string_ostream MangledNameStream(MangledName);
375 Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
380 TargetAddress extractAndCompile(CODLogicalDylib &LD,
381 LogicalModuleHandle LMH,
383 auto &LMResources = LD.getLogicalModuleResources(LMH);
384 Module &SrcM = LMResources.SourceModule->getResource();
386 // If F is a declaration we must already have compiled it.
387 if (F.isDeclaration())
390 // Grab the name of the function being called here.
391 std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
393 auto Part = Partition(F);
394 auto PartH = emitPartition(LD, LMH, Part);
396 TargetAddress CalledAddr = 0;
397 for (auto *SubF : Part) {
398 std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
399 auto FnBodySym = BaseLayer.findSymbolIn(PartH, FnName, false);
400 assert(FnBodySym && "Couldn't find function body.");
402 TargetAddress FnBodyAddr = FnBodySym.getAddress();
404 // If this is the function we're calling record the address so we can
405 // return it from this function.
407 CalledAddr = FnBodyAddr;
409 // Update the function body pointer for the stub.
410 if (auto EC = LMResources.StubsMgr->updatePointer(FnName, FnBodyAddr))
417 template <typename PartitionT>
418 BaseLayerModuleSetHandleT emitPartition(CODLogicalDylib &LD,
419 LogicalModuleHandle LMH,
420 const PartitionT &Part) {
421 auto &LMResources = LD.getLogicalModuleResources(LMH);
422 Module &SrcM = LMResources.SourceModule->getResource();
424 // Create the module.
425 std::string NewName = SrcM.getName();
426 for (auto *F : Part) {
428 NewName += F->getName();
431 auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
432 M->setDataLayout(SrcM.getDataLayout());
433 ValueToValueMapTy VMap;
435 auto Materializer = createLambdaMaterializer([this, &LMResources, &M,
436 &VMap](Value *V) -> Value * {
437 if (auto *GV = dyn_cast<GlobalVariable>(V))
438 return cloneGlobalVariableDecl(*M, *GV);
440 if (auto *F = dyn_cast<Function>(V)) {
441 // Check whether we want to clone an available_externally definition.
442 if (!LMResources.StubsToClone.count(F))
443 return cloneFunctionDecl(*M, *F);
445 // Ok - we want an inlinable stub. For that to work we need a decl
446 // for the stub pointer.
447 auto *StubPtr = createImplPointer(*F->getType(), *M,
448 F->getName() + "$stub_ptr", nullptr);
449 auto *ClonedF = cloneFunctionDecl(*M, *F);
450 makeStub(*ClonedF, *StubPtr);
451 ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
452 ClonedF->addFnAttr(Attribute::AlwaysInline);
456 if (auto *A = dyn_cast<GlobalAlias>(V)) {
457 auto *Ty = A->getValueType();
458 if (Ty->isFunctionTy())
459 return Function::Create(cast<FunctionType>(Ty),
460 GlobalValue::ExternalLinkage, A->getName(),
463 return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
464 nullptr, A->getName(), nullptr,
465 GlobalValue::NotThreadLocal,
466 A->getType()->getAddressSpace());
472 // Create decls in the new module.
474 cloneFunctionDecl(*M, *F, &VMap);
476 // Move the function bodies.
478 moveFunctionBody(*F, VMap, &Materializer);
480 // Create memory manager and symbol resolver.
481 auto Resolver = createLambdaResolver(
482 [this, &LD, LMH](const std::string &Name) {
483 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
484 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
486 return LD.getDylibResources().ExternalSymbolResolver(Name);
488 [this, &LD, LMH](const std::string &Name) {
489 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
490 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
492 return RuntimeDyld::SymbolInfo(nullptr);
495 return LD.getDylibResources().ModuleAdder(BaseLayer, std::move(M),
496 std::move(Resolver));
499 BaseLayerT &BaseLayer;
500 PartitioningFtor Partition;
501 CompileCallbackMgrT &CompileCallbackMgr;
502 IndirectStubsManagerBuilderT CreateIndirectStubsManager;
504 LogicalDylibList LogicalDylibs;
505 bool CloneStubsIntoPartitions;
508 } // End namespace orc.
509 } // End namespace llvm.
511 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H