Revert "[Orc] Directly emit machine code for the x86 resolver block and trampolines."
[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 "LambdaResolver.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ExecutionEngine/RuntimeDyld.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Transforms/Utils/ValueMapper.h"
25 #include <sstream>
26
27 namespace llvm {
28 namespace orc {
29
30 /// @brief Base class for JITLayer independent aspects of
31 ///        JITCompileCallbackManager.
32 class JITCompileCallbackManagerBase {
33 public:
34
35   typedef std::function<TargetAddress()> CompileFtor;
36
37   /// @brief Handle to a newly created compile callback. Can be used to get an
38   ///        IR constant representing the address of the trampoline, and to set
39   ///        the compile action for the callback.
40   class CompileCallbackInfo {
41   public:
42     CompileCallbackInfo(TargetAddress Addr, CompileFtor &Compile)
43       : Addr(Addr), Compile(Compile) {}
44
45     TargetAddress getAddress() const { return Addr; }
46     void setCompileAction(CompileFtor Compile) {
47       this->Compile = std::move(Compile);
48     }
49   private:
50     TargetAddress Addr;
51     CompileFtor &Compile;
52   };
53
54   /// @brief Construct a JITCompileCallbackManagerBase.
55   /// @param ErrorHandlerAddress The address of an error handler in the target
56   ///                            process to be used if a compile callback fails.
57   /// @param NumTrampolinesPerBlock Number of trampolines to emit if there is no
58   ///                             available trampoline when getCompileCallback is
59   ///                             called.
60   JITCompileCallbackManagerBase(TargetAddress ErrorHandlerAddress,
61                                 unsigned NumTrampolinesPerBlock)
62     : ErrorHandlerAddress(ErrorHandlerAddress),
63       NumTrampolinesPerBlock(NumTrampolinesPerBlock) {}
64
65   virtual ~JITCompileCallbackManagerBase() {}
66
67   /// @brief Execute the callback for the given trampoline id. Called by the JIT
68   ///        to compile functions on demand.
69   TargetAddress executeCompileCallback(TargetAddress TrampolineAddr) {
70     auto I = ActiveTrampolines.find(TrampolineAddr);
71     // FIXME: Also raise an error in the Orc error-handler when we finally have
72     //        one.
73     if (I == ActiveTrampolines.end())
74       return ErrorHandlerAddress;
75
76     // Found a callback handler. Yank this trampoline out of the active list and
77     // put it back in the available trampolines list, then try to run the
78     // handler's compile and update actions.
79     // Moving the trampoline ID back to the available list first means there's at
80     // least one available trampoline if the compile action triggers a request for
81     // a new one.
82     auto Compile = std::move(I->second);
83     ActiveTrampolines.erase(I);
84     AvailableTrampolines.push_back(TrampolineAddr);
85
86     if (auto Addr = Compile())
87       return Addr;
88
89     return ErrorHandlerAddress;
90   }
91
92   /// @brief Reserve a compile callback.
93   virtual CompileCallbackInfo getCompileCallback(LLVMContext &Context) = 0;
94
95   /// @brief Get a CompileCallbackInfo for an existing callback.
96   CompileCallbackInfo getCompileCallbackInfo(TargetAddress TrampolineAddr) {
97     auto I = ActiveTrampolines.find(TrampolineAddr);
98     assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
99     return CompileCallbackInfo(I->first, I->second);
100   }
101
102   /// @brief Release a compile callback.
103   ///
104   ///   Note: Callbacks are auto-released after they execute. This method should
105   /// only be called to manually release a callback that is not going to
106   /// execute.
107   void releaseCompileCallback(TargetAddress TrampolineAddr) {
108     auto I = ActiveTrampolines.find(TrampolineAddr);
109     assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
110     ActiveTrampolines.erase(I);
111     AvailableTrampolines.push_back(TrampolineAddr);
112   }
113
114 protected:
115   TargetAddress ErrorHandlerAddress;
116   unsigned NumTrampolinesPerBlock;
117
118   typedef std::map<TargetAddress, CompileFtor> TrampolineMapT;
119   TrampolineMapT ActiveTrampolines;
120   std::vector<TargetAddress> AvailableTrampolines;
121
122 private:
123   virtual void anchor();
124 };
125
126 /// @brief Manage compile callbacks.
127 template <typename JITLayerT, typename TargetT>
128 class JITCompileCallbackManager : public JITCompileCallbackManagerBase {
129 public:
130
131   /// @brief Construct a JITCompileCallbackManager.
132   /// @param JIT JIT layer to emit callback trampolines, etc. into.
133   /// @param Context LLVMContext to use for trampoline & resolve block modules.
134   /// @param ErrorHandlerAddress The address of an error handler in the target
135   ///                            process to be used if a compile callback fails.
136   /// @param NumTrampolinesPerBlock Number of trampolines to allocate whenever
137   ///                               there is no existing callback trampoline.
138   ///                               (Trampolines are allocated in blocks for
139   ///                               efficiency.)
140   JITCompileCallbackManager(JITLayerT &JIT, RuntimeDyld::MemoryManager &MemMgr,
141                             LLVMContext &Context,
142                             TargetAddress ErrorHandlerAddress,
143                             unsigned NumTrampolinesPerBlock)
144     : JITCompileCallbackManagerBase(ErrorHandlerAddress,
145                                     NumTrampolinesPerBlock),
146       JIT(JIT), MemMgr(MemMgr) {
147     emitResolverBlock(Context);
148   }
149
150   /// @brief Get/create a compile callback with the given signature.
151   CompileCallbackInfo getCompileCallback(LLVMContext &Context) final {
152     TargetAddress TrampolineAddr = getAvailableTrampolineAddr(Context);
153     auto &Compile = this->ActiveTrampolines[TrampolineAddr];
154     return CompileCallbackInfo(TrampolineAddr, Compile);
155   }
156
157 private:
158
159   std::vector<std::unique_ptr<Module>>
160   SingletonSet(std::unique_ptr<Module> M) {
161     std::vector<std::unique_ptr<Module>> Ms;
162     Ms.push_back(std::move(M));
163     return Ms;
164   }
165
166   void emitResolverBlock(LLVMContext &Context) {
167     std::unique_ptr<Module> M(new Module("resolver_block_module",
168                                          Context));
169     TargetT::insertResolverBlock(*M, *this);
170     auto NonResolver =
171       createLambdaResolver(
172           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
173             llvm_unreachable("External symbols in resolver block?");
174           },
175           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
176             llvm_unreachable("Dylib symbols in resolver block?");
177           });
178     auto H = JIT.addModuleSet(SingletonSet(std::move(M)), &MemMgr,
179                               std::move(NonResolver));
180     JIT.emitAndFinalize(H);
181     auto ResolverBlockSymbol =
182       JIT.findSymbolIn(H, TargetT::ResolverBlockName, false);
183     assert(ResolverBlockSymbol && "Failed to insert resolver block");
184     ResolverBlockAddr = ResolverBlockSymbol.getAddress();
185   }
186
187   TargetAddress getAvailableTrampolineAddr(LLVMContext &Context) {
188     if (this->AvailableTrampolines.empty())
189       grow(Context);
190     assert(!this->AvailableTrampolines.empty() &&
191            "Failed to grow available trampolines.");
192     TargetAddress TrampolineAddr = this->AvailableTrampolines.back();
193     this->AvailableTrampolines.pop_back();
194     return TrampolineAddr;
195   }
196
197   void grow(LLVMContext &Context) {
198     assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
199     std::unique_ptr<Module> M(new Module("trampoline_block", Context));
200     auto GetLabelName =
201       TargetT::insertCompileCallbackTrampolines(*M, ResolverBlockAddr,
202                                                 this->NumTrampolinesPerBlock,
203                                                 this->ActiveTrampolines.size());
204     auto NonResolver =
205       createLambdaResolver(
206           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
207             llvm_unreachable("External symbols in trampoline block?");
208           },
209           [](const std::string &Name) -> RuntimeDyld::SymbolInfo {
210             llvm_unreachable("Dylib symbols in trampoline block?");
211           });
212     auto H = JIT.addModuleSet(SingletonSet(std::move(M)), &MemMgr,
213                               std::move(NonResolver));
214     JIT.emitAndFinalize(H);
215     for (unsigned I = 0; I < this->NumTrampolinesPerBlock; ++I) {
216       std::string Name = GetLabelName(I);
217       auto TrampolineSymbol = JIT.findSymbolIn(H, Name, false);
218       assert(TrampolineSymbol && "Failed to emit trampoline.");
219       this->AvailableTrampolines.push_back(TrampolineSymbol.getAddress());
220     }
221   }
222
223   JITLayerT &JIT;
224   RuntimeDyld::MemoryManager &MemMgr;
225   TargetAddress ResolverBlockAddr;
226 };
227
228 /// @brief Base class for managing collections of named indirect stubs.
229 class IndirectStubsManagerBase {
230 public:
231
232   /// @brief Map type for initializing the manager. See init.
233   typedef StringMap<std::pair<TargetAddress, JITSymbolFlags>> StubInitsMap;
234
235   virtual ~IndirectStubsManagerBase() {}
236
237   /// @brief Create a single stub with the given name, target address and flags.
238   virtual std::error_code createStub(StringRef StubName, TargetAddress StubAddr,
239                                      JITSymbolFlags StubFlags) = 0;
240
241   /// @brief Create StubInits.size() stubs with the given names, target
242   ///        addresses, and flags.
243   virtual std::error_code createStubs(const StubInitsMap &StubInits) = 0;
244
245   /// @brief Find the stub with the given name. If ExportedStubsOnly is true,
246   ///        this will only return a result if the stub's flags indicate that it
247   ///        is exported.
248   virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) = 0;
249
250   /// @brief Find the implementation-pointer for the stub.
251   virtual JITSymbol findPointer(StringRef Name) = 0;
252
253   /// @brief Change the value of the implementation pointer for the stub.
254   virtual std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) = 0;
255 private:
256   virtual void anchor();
257 };
258
259 /// @brief IndirectStubsManager implementation for a concrete target, e.g.
260 ///        OrcX86_64. (See OrcTargetSupport.h).
261 template <typename TargetT>
262 class IndirectStubsManager : public IndirectStubsManagerBase {
263 public:
264
265   std::error_code createStub(StringRef StubName, TargetAddress StubAddr,
266                              JITSymbolFlags StubFlags) override {
267     if (auto EC = reserveStubs(1))
268       return EC;
269
270     createStubInternal(StubName, StubAddr, StubFlags);
271
272     return std::error_code();
273   }
274
275   std::error_code createStubs(const StubInitsMap &StubInits) override {
276     if (auto EC = reserveStubs(StubInits.size()))
277       return EC;
278
279     for (auto &Entry : StubInits)
280       createStubInternal(Entry.first(), Entry.second.first,
281                          Entry.second.second);
282
283     return std::error_code();
284   }
285
286   JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
287     auto I = StubIndexes.find(Name);
288     if (I == StubIndexes.end())
289       return nullptr;
290     auto Key = I->second.first;
291     void *StubAddr = IndirectStubsInfos[Key.first].getStub(Key.second);
292     assert(StubAddr && "Missing stub address");
293     auto StubTargetAddr =
294       static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(StubAddr));
295     auto StubSymbol = JITSymbol(StubTargetAddr, I->second.second);
296     if (ExportedStubsOnly && !StubSymbol.isExported())
297       return nullptr;
298     return StubSymbol;
299   }
300
301   JITSymbol findPointer(StringRef Name) override {
302     auto I = StubIndexes.find(Name);
303     if (I == StubIndexes.end())
304       return nullptr;
305     auto Key = I->second.first;
306     void *PtrAddr = IndirectStubsInfos[Key.first].getPtr(Key.second);
307     assert(PtrAddr && "Missing pointer address");
308     auto PtrTargetAddr =
309       static_cast<TargetAddress>(reinterpret_cast<uintptr_t>(PtrAddr));
310     return JITSymbol(PtrTargetAddr, I->second.second);
311   }
312
313   std::error_code updatePointer(StringRef Name, TargetAddress NewAddr) override {
314     auto I = StubIndexes.find(Name);
315     assert(I != StubIndexes.end() && "No stub pointer for symbol");
316     auto Key = I->second.first;
317     *IndirectStubsInfos[Key.first].getPtr(Key.second) =
318       reinterpret_cast<void*>(static_cast<uintptr_t>(NewAddr));
319     return std::error_code();
320   }
321
322 private:
323
324   std::error_code reserveStubs(unsigned NumStubs) {
325     if (NumStubs <= FreeStubs.size())
326       return std::error_code();
327
328     unsigned NewStubsRequired = NumStubs - FreeStubs.size();
329     unsigned NewBlockId = IndirectStubsInfos.size();
330     typename TargetT::IndirectStubsInfo ISI;
331     if (auto EC = TargetT::emitIndirectStubsBlock(ISI, NewStubsRequired,
332                                                   nullptr))
333       return EC;
334     for (unsigned I = 0; I < ISI.getNumStubs(); ++I)
335       FreeStubs.push_back(std::make_pair(NewBlockId, I));
336     IndirectStubsInfos.push_back(std::move(ISI));
337     return std::error_code();
338   }
339
340   void createStubInternal(StringRef StubName, TargetAddress InitAddr,
341                           JITSymbolFlags StubFlags) {
342     auto Key = FreeStubs.back();
343     FreeStubs.pop_back();
344     *IndirectStubsInfos[Key.first].getPtr(Key.second) =
345       reinterpret_cast<void*>(static_cast<uintptr_t>(InitAddr));
346     StubIndexes[StubName] = std::make_pair(Key, StubFlags);
347   }
348
349   std::vector<typename TargetT::IndirectStubsInfo> IndirectStubsInfos;
350   typedef std::pair<uint16_t, uint16_t> StubKey;
351   std::vector<StubKey> FreeStubs;
352   StringMap<std::pair<StubKey, JITSymbolFlags>> StubIndexes;
353 };
354
355 /// @brief Build a function pointer of FunctionType with the given constant
356 ///        address.
357 ///
358 ///   Usage example: Turn a trampoline address into a function pointer constant
359 /// for use in a stub.
360 Constant* createIRTypedAddress(FunctionType &FT, TargetAddress Addr);
361
362 /// @brief Create a function pointer with the given type, name, and initializer
363 ///        in the given Module.
364 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
365                                   const Twine &Name, Constant *Initializer);
366
367 /// @brief Turn a function declaration into a stub function that makes an
368 ///        indirect call using the given function pointer.
369 void makeStub(Function &F, Value &ImplPointer);
370
371 /// @brief Raise linkage types and rename as necessary to ensure that all
372 ///        symbols are accessible for other modules.
373 ///
374 ///   This should be called before partitioning a module to ensure that the
375 /// partitions retain access to each other's symbols.
376 void makeAllSymbolsExternallyAccessible(Module &M);
377
378 /// @brief Clone a function declaration into a new module.
379 ///
380 ///   This function can be used as the first step towards creating a callback
381 /// stub (see makeStub), or moving a function body (see moveFunctionBody).
382 ///
383 ///   If the VMap argument is non-null, a mapping will be added between F and
384 /// the new declaration, and between each of F's arguments and the new
385 /// declaration's arguments. This map can then be passed in to moveFunction to
386 /// move the function body if required. Note: When moving functions between
387 /// modules with these utilities, all decls should be cloned (and added to a
388 /// single VMap) before any bodies are moved. This will ensure that references
389 /// between functions all refer to the versions in the new module.
390 Function* cloneFunctionDecl(Module &Dst, const Function &F,
391                             ValueToValueMapTy *VMap = nullptr);
392
393 /// @brief Move the body of function 'F' to a cloned function declaration in a
394 ///        different module (See related cloneFunctionDecl).
395 ///
396 ///   If the target function declaration is not supplied via the NewF parameter
397 /// then it will be looked up via the VMap.
398 ///
399 ///   This will delete the body of function 'F' from its original parent module,
400 /// but leave its declaration.
401 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
402                       ValueMaterializer *Materializer = nullptr,
403                       Function *NewF = nullptr);
404
405 /// @brief Clone a global variable declaration into a new module.
406 GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
407                                         ValueToValueMapTy *VMap = nullptr);
408
409 /// @brief Move global variable GV from its parent module to cloned global
410 ///        declaration in a different module.
411 ///
412 ///   If the target global declaration is not supplied via the NewGV parameter
413 /// then it will be looked up via the VMap.
414 ///
415 ///   This will delete the initializer of GV from its original parent module,
416 /// but leave its declaration.
417 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
418                                    ValueToValueMapTy &VMap,
419                                    ValueMaterializer *Materializer = nullptr,
420                                    GlobalVariable *NewGV = nullptr);
421
422 /// @brief Clone 
423 GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
424                                   ValueToValueMapTy &VMap);
425
426 } // End namespace orc.
427 } // End namespace llvm.
428
429 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H