1 //===-- IndirectionUtils.h - Utilities for adding indirections --*- 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 // Contains utilities for adding indirections and breaking up modules.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
15 #define LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
17 #include "JITSymbol.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
27 /// @brief Base class for JITLayer independent aspects of
28 /// JITCompileCallbackManager.
29 template <typename TargetT>
30 class JITCompileCallbackManagerBase {
33 /// @brief Construct a JITCompileCallbackManagerBase.
34 /// @param ErrorHandlerAddress The address of an error handler in the target
35 /// process to be used if a compile callback fails.
36 /// @param NumTrampolinesPerBlock Number of trampolines to emit if there is no
37 /// available trampoline when getCompileCallback is
39 JITCompileCallbackManagerBase(TargetAddress ErrorHandlerAddress,
40 unsigned NumTrampolinesPerBlock)
41 : ErrorHandlerAddress(ErrorHandlerAddress),
42 NumTrampolinesPerBlock(NumTrampolinesPerBlock) {}
44 /// @brief Execute the callback for the given trampoline id. Called by the JIT
45 /// to compile functions on demand.
46 TargetAddress executeCompileCallback(TargetAddress TrampolineID) {
47 typename TrampolineMapT::iterator I = ActiveTrampolines.find(TrampolineID);
48 // FIXME: Also raise an error in the Orc error-handler when we finally have
50 if (I == ActiveTrampolines.end())
51 return ErrorHandlerAddress;
53 // Found a callback handler. Yank this trampoline out of the active list and
54 // put it back in the available trampolines list, then try to run the
55 // handler's compile and update actions.
56 // Moving the trampoline ID back to the available list first means there's at
57 // least one available trampoline if the compile action triggers a request for
59 AvailableTrampolines.push_back(I->first);
60 auto CallbackHandler = std::move(I->second);
61 ActiveTrampolines.erase(I);
63 if (auto Addr = CallbackHandler.Compile()) {
64 CallbackHandler.Update(Addr);
67 return ErrorHandlerAddress;
72 typedef std::function<TargetAddress()> CompileFtorT;
73 typedef std::function<void(TargetAddress)> UpdateFtorT;
75 struct CallbackHandler {
80 TargetAddress ErrorHandlerAddress;
81 unsigned NumTrampolinesPerBlock;
83 typedef std::map<TargetAddress, CallbackHandler> TrampolineMapT;
84 TrampolineMapT ActiveTrampolines;
85 std::vector<TargetAddress> AvailableTrampolines;
88 /// @brief Manage compile callbacks.
89 template <typename JITLayerT, typename TargetT>
90 class JITCompileCallbackManager :
91 public JITCompileCallbackManagerBase<TargetT> {
94 typedef typename JITCompileCallbackManagerBase<TargetT>::CompileFtorT
96 typedef typename JITCompileCallbackManagerBase<TargetT>::UpdateFtorT
99 /// @brief Construct a JITCompileCallbackManager.
100 /// @param JIT JIT layer to emit callback trampolines, etc. into.
101 /// @param Context LLVMContext to use for trampoline & resolve block modules.
102 /// @param ErrorHandlerAddress The address of an error handler in the target
103 /// process to be used if a compile callback fails.
104 /// @param NumTrampolinesPerBlock Number of trampolines to allocate whenever
105 /// there is no existing callback trampoline.
106 /// (Trampolines are allocated in blocks for
108 JITCompileCallbackManager(JITLayerT &JIT, LLVMContext &Context,
109 TargetAddress ErrorHandlerAddress,
110 unsigned NumTrampolinesPerBlock)
111 : JITCompileCallbackManagerBase<TargetT>(ErrorHandlerAddress,
112 NumTrampolinesPerBlock),
114 emitResolverBlock(Context);
117 /// @brief Handle to a newly created compile callback. Can be used to get an
118 /// IR constant representing the address of the trampoline, and to set
119 /// the compile and update actions for the callback.
120 class CompileCallbackInfo {
122 CompileCallbackInfo(Constant *Addr, CompileFtorT &Compile,
124 : Addr(Addr), Compile(Compile), Update(Update) {}
126 Constant* getAddress() const { return Addr; }
127 void setCompileAction(CompileFtorT Compile) {
128 this->Compile = std::move(Compile);
130 void setUpdateAction(UpdateFtorT Update) {
131 this->Update = std::move(Update);
135 CompileFtorT &Compile;
139 /// @brief Get/create a compile callback with the given signature.
140 CompileCallbackInfo getCompileCallback(FunctionType &FT) {
141 TargetAddress TrampolineAddr = getAvailableTrampolineAddr(FT.getContext());
142 auto &CallbackHandler =
143 this->ActiveTrampolines[TrampolineAddr];
144 Constant *AddrIntVal =
145 ConstantInt::get(Type::getInt64Ty(FT.getContext()), TrampolineAddr);
146 Constant *AddrPtrVal =
147 ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
148 PointerType::get(&FT, 0));
150 return CompileCallbackInfo(AddrPtrVal, CallbackHandler.Compile,
151 CallbackHandler.Update);
154 /// @brief Get a functor for updating the value of a named function pointer.
155 UpdateFtorT getLocalFPUpdater(typename JITLayerT::ModuleSetHandleT H,
157 // FIXME: Move-capture Name once we can use C++14.
158 return [=](TargetAddress Addr) {
159 auto FPSym = JIT.findSymbolIn(H, Name, true);
160 assert(FPSym && "Cannot find function pointer to update.");
161 void *FPAddr = reinterpret_cast<void*>(
162 static_cast<uintptr_t>(FPSym.getAddress()));
163 memcpy(FPAddr, &Addr, sizeof(uintptr_t));
169 std::vector<std::unique_ptr<Module>>
170 SingletonSet(std::unique_ptr<Module> M) {
171 std::vector<std::unique_ptr<Module>> Ms;
172 Ms.push_back(std::move(M));
176 void emitResolverBlock(LLVMContext &Context) {
177 std::unique_ptr<Module> M(new Module("resolver_block_module",
179 TargetT::insertResolverBlock(*M, *this);
180 auto H = JIT.addModuleSet(SingletonSet(std::move(M)), nullptr);
181 JIT.emitAndFinalize(H);
182 auto ResolverBlockSymbol =
183 JIT.findSymbolIn(H, TargetT::ResolverBlockName, false);
184 assert(ResolverBlockSymbol && "Failed to insert resolver block");
185 ResolverBlockAddr = ResolverBlockSymbol.getAddress();
188 TargetAddress getAvailableTrampolineAddr(LLVMContext &Context) {
189 if (this->AvailableTrampolines.empty())
191 assert(!this->AvailableTrampolines.empty() &&
192 "Failed to grow available trampolines.");
193 TargetAddress TrampolineAddr = this->AvailableTrampolines.back();
194 this->AvailableTrampolines.pop_back();
195 return TrampolineAddr;
198 void grow(LLVMContext &Context) {
199 assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
200 std::unique_ptr<Module> M(new Module("trampoline_block", Context));
202 TargetT::insertCompileCallbackTrampolines(*M, ResolverBlockAddr,
203 this->NumTrampolinesPerBlock,
204 this->ActiveTrampolines.size());
205 auto H = JIT.addModuleSet(SingletonSet(std::move(M)), nullptr);
206 JIT.emitAndFinalize(H);
207 for (unsigned I = 0; I < this->NumTrampolinesPerBlock; ++I) {
208 std::string Name = GetLabelName(I);
209 auto TrampolineSymbol = JIT.findSymbolIn(H, Name, false);
210 assert(TrampolineSymbol && "Failed to emit trampoline.");
211 this->AvailableTrampolines.push_back(TrampolineSymbol.getAddress());
216 TargetAddress ResolverBlockAddr;
219 GlobalVariable* createImplPointer(Function &F, const Twine &Name,
220 Constant *Initializer);
222 void makeStub(Function &F, GlobalVariable &ImplPointer);
224 typedef std::map<Module*, DenseSet<const GlobalValue*>> ModulePartitionMap;
226 void partition(Module &M, const ModulePartitionMap &PMap);
228 /// @brief Struct for trivial "complete" partitioning of a module.
229 class FullyPartitionedModule {
231 std::unique_ptr<Module> GlobalVars;
232 std::unique_ptr<Module> Commons;
233 std::vector<std::unique_ptr<Module>> Functions;
235 FullyPartitionedModule() = default;
236 FullyPartitionedModule(FullyPartitionedModule &&S)
237 : GlobalVars(std::move(S.GlobalVars)), Commons(std::move(S.Commons)),
238 Functions(std::move(S.Functions)) {}
241 FullyPartitionedModule fullyPartition(Module &M);
243 } // End namespace orc.
244 } // End namespace llvm.
246 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H