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/ExecutionEngine/SectionMemoryManager.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
28 #include "llvm/Support/Debug.h"
33 /// @brief Compile-on-demand layer.
35 /// When a module is added to this layer a stub is created for each of its
36 /// function definitions. The stubs and other global values are immediately
37 /// added to the layer below. When a stub is called it triggers the extraction
38 /// of the function body from the original module. The extracted body is then
39 /// compiled and executed.
40 template <typename BaseLayerT,
41 typename CompileCallbackMgrT = JITCompileCallbackManagerBase,
42 typename IndirectStubsMgrT = IndirectStubsManagerBase>
43 class CompileOnDemandLayer {
46 template <typename MaterializerFtor>
47 class LambdaMaterializer final : public ValueMaterializer {
49 LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
50 Value* materializeValueFor(Value *V) final {
57 template <typename MaterializerFtor>
58 LambdaMaterializer<MaterializerFtor>
59 createLambdaMaterializer(MaterializerFtor M) {
60 return LambdaMaterializer<MaterializerFtor>(std::move(M));
63 typedef typename BaseLayerT::ModuleSetHandleT BaseLayerModuleSetHandleT;
67 ModuleOwner() = default;
68 ModuleOwner(const ModuleOwner&) = delete;
69 ModuleOwner& operator=(const ModuleOwner&) = delete;
70 virtual ~ModuleOwner() { }
71 virtual Module& getModule() const = 0;
74 template <typename ModulePtrT>
75 class ModuleOwnerImpl : public ModuleOwner {
77 ModuleOwnerImpl(ModulePtrT ModulePtr) : ModulePtr(std::move(ModulePtr)) {}
78 Module& getModule() const override { return *ModulePtr; }
83 template <typename ModulePtrT>
84 std::unique_ptr<ModuleOwner> wrapOwnership(ModulePtrT ModulePtr) {
85 return llvm::make_unique<ModuleOwnerImpl<ModulePtrT>>(std::move(ModulePtr));
88 struct LogicalModuleResources {
89 std::unique_ptr<ModuleOwner> SourceModuleOwner;
90 std::set<const Function*> StubsToClone;
91 std::unique_ptr<IndirectStubsMgrT> StubsMgr;
93 LogicalModuleResources() = default;
95 // Explicit move constructor to make MSVC happy.
96 LogicalModuleResources(LogicalModuleResources &&Other)
97 : SourceModuleOwner(std::move(Other.SourceModuleOwner)),
98 StubsToClone(std::move(Other.StubsToClone)),
99 StubsMgr(std::move(Other.StubsMgr)) {}
101 // Explicit move assignment to make MSVC happy.
102 LogicalModuleResources& operator=(LogicalModuleResources &&Other) {
103 SourceModuleOwner = std::move(Other.SourceModuleOwner);
104 StubsToClone = std::move(Other.StubsToClone);
105 StubsMgr = std::move(Other.StubsMgr);
108 JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
109 if (Name.endswith("$stub_ptr") && !ExportedSymbolsOnly) {
110 assert(!ExportedSymbolsOnly && "Stubs are never exported");
111 return StubsMgr->findPointer(Name.drop_back(9));
113 return StubsMgr->findStub(Name, ExportedSymbolsOnly);
120 struct LogicalDylibResources {
121 typedef std::function<RuntimeDyld::SymbolInfo(const std::string&)>
123 SymbolResolverFtor ExternalSymbolResolver;
126 typedef LogicalDylib<BaseLayerT, LogicalModuleResources,
127 LogicalDylibResources> CODLogicalDylib;
129 typedef typename CODLogicalDylib::LogicalModuleHandle LogicalModuleHandle;
130 typedef std::list<CODLogicalDylib> LogicalDylibList;
134 /// @brief Handle to a set of loaded modules.
135 typedef typename LogicalDylibList::iterator ModuleSetHandleT;
137 /// @brief Module partitioning functor.
138 typedef std::function<std::set<Function*>(Function&)> PartitioningFtor;
140 /// @brief Builder for IndirectStubsManagers.
141 typedef std::function<std::unique_ptr<IndirectStubsMgrT>()>
142 IndirectStubsManagerBuilderT;
144 /// @brief Construct a compile-on-demand layer instance.
145 CompileOnDemandLayer(BaseLayerT &BaseLayer, PartitioningFtor Partition,
146 CompileCallbackMgrT &CallbackMgr,
147 IndirectStubsManagerBuilderT CreateIndirectStubsManager,
148 bool CloneStubsIntoPartitions = true)
149 : BaseLayer(BaseLayer), Partition(Partition),
150 CompileCallbackMgr(CallbackMgr),
151 CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
152 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
154 /// @brief Add a module to the compile-on-demand layer.
155 template <typename ModuleSetT, typename MemoryManagerPtrT,
156 typename SymbolResolverPtrT>
157 ModuleSetHandleT addModuleSet(ModuleSetT Ms,
158 MemoryManagerPtrT MemMgr,
159 SymbolResolverPtrT Resolver) {
161 assert(MemMgr == nullptr &&
162 "User supplied memory managers not supported with COD yet.");
164 LogicalDylibs.push_back(CODLogicalDylib(BaseLayer));
165 auto &LDResources = LogicalDylibs.back().getDylibResources();
167 LDResources.ExternalSymbolResolver =
168 [Resolver](const std::string &Name) {
169 return Resolver->findSymbol(Name);
172 // Process each of the modules in this module set.
174 addLogicalModule(LogicalDylibs.back(), std::move(M));
176 return std::prev(LogicalDylibs.end());
179 /// @brief Remove the module represented by the given handle.
181 /// This will remove all modules in the layers below that were derived from
182 /// the module represented by H.
183 void removeModuleSet(ModuleSetHandleT H) {
184 LogicalDylibs.erase(H);
187 /// @brief Search for the given named symbol.
188 /// @param Name The name of the symbol to search for.
189 /// @param ExportedSymbolsOnly If true, search only for exported symbols.
190 /// @return A handle for the given named symbol, if it exists.
191 JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
192 for (auto LDI = LogicalDylibs.begin(), LDE = LogicalDylibs.end();
194 if (auto Symbol = findSymbolIn(LDI, Name, ExportedSymbolsOnly))
196 return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
199 /// @brief Get the address of a symbol provided by this layer, or some layer
201 JITSymbol findSymbolIn(ModuleSetHandleT H, const std::string &Name,
202 bool ExportedSymbolsOnly) {
203 return H->findSymbol(Name, ExportedSymbolsOnly);
208 template <typename ModulePtrT>
209 void addLogicalModule(CODLogicalDylib &LD, ModulePtrT SrcMPtr) {
211 // Bump the linkage and rename any anonymous/privote members in SrcM to
212 // ensure that everything will resolve properly after we partition SrcM.
213 makeAllSymbolsExternallyAccessible(*SrcMPtr);
215 // Create a logical module handle for SrcM within the logical dylib.
216 auto LMH = LD.createLogicalModule();
217 auto &LMResources = LD.getLogicalModuleResources(LMH);
219 LMResources.SourceModuleOwner = wrapOwnership(std::move(SrcMPtr));
221 Module &SrcM = LMResources.SourceModuleOwner->getModule();
223 // Create the GlobalValues module.
224 const DataLayout &DL = SrcM.getDataLayout();
225 auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(),
227 GVsM->setDataLayout(DL);
229 // Create function stubs.
230 ValueToValueMapTy VMap;
232 typename IndirectStubsMgrT::StubInitsMap StubInits;
233 for (auto &F : SrcM) {
234 // Skip declarations.
235 if (F.isDeclaration())
238 // Record all functions defined by this module.
239 if (CloneStubsIntoPartitions)
240 LMResources.StubsToClone.insert(&F);
242 // Create a callback, associate it with the stub for the function,
243 // and set the compile action to compile the partition containing the
245 auto CCInfo = CompileCallbackMgr.getCompileCallback(SrcM.getContext());
246 StubInits[mangle(F.getName(), DL)] =
247 std::make_pair(CCInfo.getAddress(),
248 JITSymbolBase::flagsFromGlobalValue(F));
249 CCInfo.setCompileAction([this, &LD, LMH, &F]() {
250 return this->extractAndCompile(LD, LMH, F);
254 LMResources.StubsMgr = CreateIndirectStubsManager();
255 auto EC = LMResources.StubsMgr->createStubs(StubInits);
257 // FIXME: This should be propagated back to the user. Stub creation may
258 // fail for remote JITs.
259 assert(!EC && "Error generating stubs");
262 // Clone global variable decls.
263 for (auto &GV : SrcM.globals())
264 if (!GV.isDeclaration() && !VMap.count(&GV))
265 cloneGlobalVariableDecl(*GVsM, GV, &VMap);
268 for (auto &A : SrcM.aliases())
270 cloneGlobalAliasDecl(*GVsM, A, VMap);
272 // Now we need to clone the GV and alias initializers.
274 // Initializers may refer to functions declared (but not defined) in this
275 // module. Build a materializer to clone decls on demand.
276 auto Materializer = createLambdaMaterializer(
277 [this, &GVsM, &LMResources](Value *V) -> Value* {
278 if (auto *F = dyn_cast<Function>(V)) {
279 // Decls in the original module just get cloned.
280 if (F->isDeclaration())
281 return cloneFunctionDecl(*GVsM, *F);
283 // Definitions in the original module (which we have emitted stubs
284 // for at this point) get turned into a constant alias to the stub
286 const DataLayout &DL = GVsM->getDataLayout();
287 std::string FName = mangle(F->getName(), DL);
288 auto StubSym = LMResources.StubsMgr->findStub(FName, false);
289 unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType());
290 ConstantInt *StubAddr =
291 ConstantInt::get(GVsM->getContext(),
292 APInt(PtrBitWidth, StubSym.getAddress()));
293 Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr,
294 StubAddr, F->getType());
295 return GlobalAlias::create(F->getFunctionType(),
296 F->getType()->getAddressSpace(),
297 F->getLinkage(), F->getName(),
304 // Clone the global variable initializers.
305 for (auto &GV : SrcM.globals())
306 if (!GV.isDeclaration())
307 moveGlobalVariableInitializer(GV, VMap, &Materializer);
309 // Clone the global alias initializers.
310 for (auto &A : SrcM.aliases()) {
311 auto *NewA = cast<GlobalAlias>(VMap[&A]);
312 assert(NewA && "Alias not cloned?");
313 Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr,
315 NewA->setAliasee(cast<Constant>(Init));
318 // Build a resolver for the globals module and add it to the base layer.
319 auto GVsResolver = createLambdaResolver(
320 [&LD, LMH](const std::string &Name) {
321 auto &LMResources = LD.getLogicalModuleResources(LMH);
322 if (auto Sym = LMResources.StubsMgr->findStub(Name, false))
323 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
324 return LD.getDylibResources().ExternalSymbolResolver(Name);
326 [](const std::string &Name) {
327 return RuntimeDyld::SymbolInfo(nullptr);
330 std::vector<std::unique_ptr<Module>> GVsMSet;
331 GVsMSet.push_back(std::move(GVsM));
333 BaseLayer.addModuleSet(std::move(GVsMSet),
334 llvm::make_unique<SectionMemoryManager>(),
335 std::move(GVsResolver));
336 LD.addToLogicalModule(LMH, GVsH);
339 static std::string mangle(StringRef Name, const DataLayout &DL) {
340 std::string MangledName;
341 Mangler::getNameWithPrefix(raw_string_ostream(MangledName), Name, DL);
345 TargetAddress extractAndCompile(CODLogicalDylib &LD,
346 LogicalModuleHandle LMH,
348 auto &LMResources = LD.getLogicalModuleResources(LMH);
349 Module &SrcM = LMResources.SourceModuleOwner->getModule();
351 // If F is a declaration we must already have compiled it.
352 if (F.isDeclaration())
355 // Grab the name of the function being called here.
356 std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
358 auto Part = Partition(F);
359 auto PartH = emitPartition(LD, LMH, Part);
361 TargetAddress CalledAddr = 0;
362 for (auto *SubF : Part) {
363 std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
364 auto FnBodySym = BaseLayer.findSymbolIn(PartH, FnName, false);
365 assert(FnBodySym && "Couldn't find function body.");
367 TargetAddress FnBodyAddr = FnBodySym.getAddress();
369 // If this is the function we're calling record the address so we can
370 // return it from this function.
372 CalledAddr = FnBodyAddr;
374 // Update the function body pointer for the stub.
375 if (auto EC = LMResources.StubsMgr->updatePointer(FnName, FnBodyAddr))
382 template <typename PartitionT>
383 BaseLayerModuleSetHandleT emitPartition(CODLogicalDylib &LD,
384 LogicalModuleHandle LMH,
385 const PartitionT &Part) {
386 auto &LMResources = LD.getLogicalModuleResources(LMH);
387 Module &SrcM = LMResources.SourceModuleOwner->getModule();
389 // Create the module.
390 std::string NewName = SrcM.getName();
391 for (auto *F : Part) {
393 NewName += F->getName();
396 auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
397 M->setDataLayout(SrcM.getDataLayout());
398 ValueToValueMapTy VMap;
400 auto Materializer = createLambdaMaterializer([this, &LMResources, &M,
401 &VMap](Value *V) -> Value * {
402 if (auto *GV = dyn_cast<GlobalVariable>(V))
403 return cloneGlobalVariableDecl(*M, *GV);
405 if (auto *F = dyn_cast<Function>(V)) {
406 // Check whether we want to clone an available_externally definition.
407 if (!LMResources.StubsToClone.count(F))
408 return cloneFunctionDecl(*M, *F);
410 // Ok - we want an inlinable stub. For that to work we need a decl
411 // for the stub pointer.
412 auto *StubPtr = createImplPointer(*F->getType(), *M,
413 F->getName() + "$stub_ptr", nullptr);
414 auto *ClonedF = cloneFunctionDecl(*M, *F);
415 makeStub(*ClonedF, *StubPtr);
416 ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
417 ClonedF->addFnAttr(Attribute::AlwaysInline);
421 if (auto *A = dyn_cast<GlobalAlias>(V)) {
422 auto *Ty = A->getValueType();
423 if (Ty->isFunctionTy())
424 return Function::Create(cast<FunctionType>(Ty),
425 GlobalValue::ExternalLinkage, A->getName(),
428 return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
429 nullptr, A->getName(), nullptr,
430 GlobalValue::NotThreadLocal,
431 A->getType()->getAddressSpace());
437 // Create decls in the new module.
439 cloneFunctionDecl(*M, *F, &VMap);
441 // Move the function bodies.
443 moveFunctionBody(*F, VMap, &Materializer);
445 // Create memory manager and symbol resolver.
446 auto MemMgr = llvm::make_unique<SectionMemoryManager>();
447 auto Resolver = createLambdaResolver(
448 [this, &LD, LMH](const std::string &Name) {
449 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
450 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
452 return LD.getDylibResources().ExternalSymbolResolver(Name);
454 [this, &LD, LMH](const std::string &Name) {
455 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
456 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
458 return RuntimeDyld::SymbolInfo(nullptr);
460 std::vector<std::unique_ptr<Module>> PartMSet;
461 PartMSet.push_back(std::move(M));
462 return BaseLayer.addModuleSet(std::move(PartMSet), std::move(MemMgr),
463 std::move(Resolver));
466 BaseLayerT &BaseLayer;
467 PartitioningFtor Partition;
468 CompileCallbackMgrT &CompileCallbackMgr;
469 IndirectStubsManagerBuilderT CreateIndirectStubsManager;
471 LogicalDylibList LogicalDylibs;
472 bool CloneStubsIntoPartitions;
475 } // End namespace orc.
476 } // End namespace llvm.
478 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H