6168684950ad8a743d1f5fcd4f9a3fc2e6fe9aa5
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / IndirectionUtils.h
1 //===-- IndirectionUtils.h - Utilities for adding indirections --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Contains utilities for adding indirections and breaking up modules.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
15 #define LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
16
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"
22 #include <sstream>
23
24 namespace llvm {
25 namespace orc {
26
27 /// @brief Base class for JITLayer independent aspects of
28 ///        JITCompileCallbackManager.
29 template <typename TargetT>
30 class JITCompileCallbackManagerBase {
31 public:
32
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
38   ///                             called.
39   JITCompileCallbackManagerBase(TargetAddress ErrorHandlerAddress,
40                                 unsigned NumTrampolinesPerBlock)
41     : ErrorHandlerAddress(ErrorHandlerAddress),
42       NumTrampolinesPerBlock(NumTrampolinesPerBlock) {}
43
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
49     //        one.
50     if (I == ActiveTrampolines.end())
51       return ErrorHandlerAddress;
52
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
58     // a new one.
59     AvailableTrampolines.push_back(I->first);
60     auto CallbackHandler = std::move(I->second);
61     ActiveTrampolines.erase(I);
62
63     if (auto Addr = CallbackHandler.Compile()) {
64       CallbackHandler.Update(Addr);
65       return Addr;
66     }
67     return ErrorHandlerAddress;
68   }
69
70 protected:
71
72   typedef std::function<TargetAddress()> CompileFtorT;
73   typedef std::function<void(TargetAddress)> UpdateFtorT;
74
75   struct CallbackHandler {
76     CompileFtorT Compile;
77     UpdateFtorT Update;
78   };
79
80   TargetAddress ErrorHandlerAddress;
81   unsigned NumTrampolinesPerBlock;
82
83   typedef std::map<TargetAddress, CallbackHandler> TrampolineMapT;
84   TrampolineMapT ActiveTrampolines;
85   std::vector<TargetAddress> AvailableTrampolines;
86 };
87
88 /// @brief Manage compile callbacks.
89 template <typename JITLayerT, typename TargetT>
90 class JITCompileCallbackManager :
91     public JITCompileCallbackManagerBase<TargetT> {
92 public:
93
94   typedef typename JITCompileCallbackManagerBase<TargetT>::CompileFtorT
95     CompileFtorT;
96   typedef typename JITCompileCallbackManagerBase<TargetT>::UpdateFtorT
97     UpdateFtorT;
98
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
107   ///                               efficiency.)
108   JITCompileCallbackManager(JITLayerT &JIT, LLVMContext &Context,
109                             TargetAddress ErrorHandlerAddress,
110                             unsigned NumTrampolinesPerBlock)
111     : JITCompileCallbackManagerBase<TargetT>(ErrorHandlerAddress,
112                                              NumTrampolinesPerBlock),
113       JIT(JIT) {
114     emitResolverBlock(Context);
115   }
116
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 {
121   public:
122     CompileCallbackInfo(Constant *Addr, CompileFtorT &Compile,
123                         UpdateFtorT &Update)
124       : Addr(Addr), Compile(Compile), Update(Update) {}
125
126     Constant* getAddress() const { return Addr; }
127     void setCompileAction(CompileFtorT Compile) {
128       this->Compile = std::move(Compile);
129     }
130     void setUpdateAction(UpdateFtorT Update) {
131       this->Update = std::move(Update);
132     }
133   private:
134     Constant *Addr;
135     CompileFtorT &Compile;
136     UpdateFtorT &Update;
137   };
138
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));
149
150     return CompileCallbackInfo(AddrPtrVal, CallbackHandler.Compile,
151                                CallbackHandler.Update);
152   }
153
154   /// @brief Get a functor for updating the value of a named function pointer.
155   UpdateFtorT getLocalFPUpdater(typename JITLayerT::ModuleSetHandleT H,
156                                 std::string Name) {
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));
164     };
165   }
166
167 private:
168
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));
173     return Ms;
174   }
175
176   void emitResolverBlock(LLVMContext &Context) {
177     std::unique_ptr<Module> M(new Module("resolver_block_module",
178                                          Context));
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();
186   }
187
188   TargetAddress getAvailableTrampolineAddr(LLVMContext &Context) {
189     if (this->AvailableTrampolines.empty())
190       grow(Context);
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;
196   }
197
198   void grow(LLVMContext &Context) {
199     assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
200     std::unique_ptr<Module> M(new Module("trampoline_block", Context));
201     auto GetLabelName =
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());
212     }
213   }
214
215   JITLayerT &JIT;
216   TargetAddress ResolverBlockAddr;
217 };
218
219 GlobalVariable* createImplPointer(Function &F, const Twine &Name,
220                                   Constant *Initializer);
221
222 void makeStub(Function &F, GlobalVariable &ImplPointer);
223
224 typedef std::map<Module*, DenseSet<const GlobalValue*>> ModulePartitionMap;
225
226 void partition(Module &M, const ModulePartitionMap &PMap);
227
228 /// @brief Struct for trivial "complete" partitioning of a module.
229 class FullyPartitionedModule {
230 public:
231   std::unique_ptr<Module> GlobalVars;
232   std::unique_ptr<Module> Commons;
233   std::vector<std::unique_ptr<Module>> Functions;
234
235   FullyPartitionedModule() = default;
236   FullyPartitionedModule(FullyPartitionedModule &&S)
237       : GlobalVars(std::move(S.GlobalVars)), Commons(std::move(S.Commons)),
238         Functions(std::move(S.Functions)) {}
239 };
240
241 FullyPartitionedModule fullyPartition(Module &M);
242
243 } // End namespace orc.
244 } // End namespace llvm.
245
246 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H