LLVM  5.0.0
IndirectionUtils.h
Go to the documentation of this file.
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 "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Error.h"
22 #include "llvm/Support/Memory.h"
23 #include "llvm/Support/Process.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28 #include <functional>
29 #include <map>
30 #include <memory>
31 #include <system_error>
32 #include <utility>
33 #include <vector>
34 
35 namespace llvm {
36 
37 class Constant;
38 class Function;
39 class FunctionType;
40 class GlobalAlias;
41 class GlobalVariable;
42 class Module;
43 class PointerType;
44 class Triple;
45 class Value;
46 
47 namespace orc {
48 
49 /// @brief Target-independent base class for compile callback management.
51 public:
52  using CompileFtor = std::function<JITTargetAddress()>;
53 
54  /// @brief Handle to a newly created compile callback. Can be used to get an
55  /// IR constant representing the address of the trampoline, and to set
56  /// the compile action for the callback.
58  public:
60  : Addr(Addr), Compile(Compile) {}
61 
62  JITTargetAddress getAddress() const { return Addr; }
63  void setCompileAction(CompileFtor Compile) {
64  this->Compile = std::move(Compile);
65  }
66 
67  private:
68  JITTargetAddress Addr;
69  CompileFtor &Compile;
70  };
71 
72  /// @brief Construct a JITCompileCallbackManager.
73  /// @param ErrorHandlerAddress The address of an error handler in the target
74  /// process to be used if a compile callback fails.
76  : ErrorHandlerAddress(ErrorHandlerAddress) {}
77 
78  virtual ~JITCompileCallbackManager() = default;
79 
80  /// @brief Execute the callback for the given trampoline id. Called by the JIT
81  /// to compile functions on demand.
83  auto I = ActiveTrampolines.find(TrampolineAddr);
84  // FIXME: Also raise an error in the Orc error-handler when we finally have
85  // one.
86  if (I == ActiveTrampolines.end())
87  return ErrorHandlerAddress;
88 
89  // Found a callback handler. Yank this trampoline out of the active list and
90  // put it back in the available trampolines list, then try to run the
91  // handler's compile and update actions.
92  // Moving the trampoline ID back to the available list first means there's
93  // at
94  // least one available trampoline if the compile action triggers a request
95  // for
96  // a new one.
97  auto Compile = std::move(I->second);
98  ActiveTrampolines.erase(I);
99  AvailableTrampolines.push_back(TrampolineAddr);
100 
101  if (auto Addr = Compile())
102  return Addr;
103 
104  return ErrorHandlerAddress;
105  }
106 
107  /// @brief Reserve a compile callback.
109  JITTargetAddress TrampolineAddr = getAvailableTrampolineAddr();
110  auto &Compile = this->ActiveTrampolines[TrampolineAddr];
111  return CompileCallbackInfo(TrampolineAddr, Compile);
112  }
113 
114  /// @brief Get a CompileCallbackInfo for an existing callback.
116  auto I = ActiveTrampolines.find(TrampolineAddr);
117  assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
118  return CompileCallbackInfo(I->first, I->second);
119  }
120 
121  /// @brief Release a compile callback.
122  ///
123  /// Note: Callbacks are auto-released after they execute. This method should
124  /// only be called to manually release a callback that is not going to
125  /// execute.
127  auto I = ActiveTrampolines.find(TrampolineAddr);
128  assert(I != ActiveTrampolines.end() && "Not an active trampoline.");
129  ActiveTrampolines.erase(I);
130  AvailableTrampolines.push_back(TrampolineAddr);
131  }
132 
133 protected:
135 
136  using TrampolineMapT = std::map<JITTargetAddress, CompileFtor>;
138  std::vector<JITTargetAddress> AvailableTrampolines;
139 
140 private:
141  JITTargetAddress getAvailableTrampolineAddr() {
142  if (this->AvailableTrampolines.empty())
143  grow();
144  assert(!this->AvailableTrampolines.empty() &&
145  "Failed to grow available trampolines.");
146  JITTargetAddress TrampolineAddr = this->AvailableTrampolines.back();
147  this->AvailableTrampolines.pop_back();
148  return TrampolineAddr;
149  }
150 
151  // Create new trampolines - to be implemented in subclasses.
152  virtual void grow() = 0;
153 
154  virtual void anchor();
155 };
156 
157 /// @brief Manage compile callbacks for in-process JITs.
158 template <typename TargetT>
160 public:
161  /// @brief Construct a InProcessJITCompileCallbackManager.
162  /// @param ErrorHandlerAddress The address of an error handler in the target
163  /// process to be used if a compile callback fails.
165  : JITCompileCallbackManager(ErrorHandlerAddress) {
166  /// Set up the resolver block.
167  std::error_code EC;
169  TargetT::ResolverCodeSize, nullptr,
171  assert(!EC && "Failed to allocate resolver block");
172 
173  TargetT::writeResolverCode(static_cast<uint8_t *>(ResolverBlock.base()),
174  &reenter, this);
175 
179  assert(!EC && "Failed to mprotect resolver block");
180  }
181 
182 private:
183  static JITTargetAddress reenter(void *CCMgr, void *TrampolineId) {
185  static_cast<JITCompileCallbackManager *>(CCMgr);
186  return Mgr->executeCompileCallback(
187  static_cast<JITTargetAddress>(
188  reinterpret_cast<uintptr_t>(TrampolineId)));
189  }
190 
191  void grow() override {
192  assert(this->AvailableTrampolines.empty() && "Growing prematurely?");
193 
194  std::error_code EC;
195  auto TrampolineBlock =
197  sys::Process::getPageSize(), nullptr,
199  assert(!EC && "Failed to allocate trampoline block");
200 
201  unsigned NumTrampolines =
202  (sys::Process::getPageSize() - TargetT::PointerSize) /
203  TargetT::TrampolineSize;
204 
205  uint8_t *TrampolineMem = static_cast<uint8_t *>(TrampolineBlock.base());
206  TargetT::writeTrampolines(TrampolineMem, ResolverBlock.base(),
207  NumTrampolines);
208 
209  for (unsigned I = 0; I < NumTrampolines; ++I)
210  this->AvailableTrampolines.push_back(
211  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(
212  TrampolineMem + (I * TargetT::TrampolineSize))));
213 
214  EC = sys::Memory::protectMappedMemory(TrampolineBlock.getMemoryBlock(),
217  assert(!EC && "Failed to mprotect trampoline block");
218 
219  TrampolineBlocks.push_back(std::move(TrampolineBlock));
220  }
221 
222  sys::OwningMemoryBlock ResolverBlock;
223  std::vector<sys::OwningMemoryBlock> TrampolineBlocks;
224 };
225 
226 /// @brief Base class for managing collections of named indirect stubs.
228 public:
229  /// @brief Map type for initializing the manager. See init.
231 
232  virtual ~IndirectStubsManager() = default;
233 
234  /// @brief Create a single stub with the given name, target address and flags.
235  virtual Error createStub(StringRef StubName, JITTargetAddress StubAddr,
236  JITSymbolFlags StubFlags) = 0;
237 
238  /// @brief Create StubInits.size() stubs with the given names, target
239  /// addresses, and flags.
240  virtual Error createStubs(const StubInitsMap &StubInits) = 0;
241 
242  /// @brief Find the stub with the given name. If ExportedStubsOnly is true,
243  /// this will only return a result if the stub's flags indicate that it
244  /// is exported.
245  virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) = 0;
246 
247  /// @brief Find the implementation-pointer for the stub.
248  virtual JITSymbol findPointer(StringRef Name) = 0;
249 
250  /// @brief Change the value of the implementation pointer for the stub.
251  virtual Error updatePointer(StringRef Name, JITTargetAddress NewAddr) = 0;
252 
253 private:
254  virtual void anchor();
255 };
256 
257 /// @brief IndirectStubsManager implementation for the host architecture, e.g.
258 /// OrcX86_64. (See OrcArchitectureSupport.h).
259 template <typename TargetT>
261 public:
263  JITSymbolFlags StubFlags) override {
264  if (auto Err = reserveStubs(1))
265  return Err;
266 
267  createStubInternal(StubName, StubAddr, StubFlags);
268 
269  return Error::success();
270  }
271 
272  Error createStubs(const StubInitsMap &StubInits) override {
273  if (auto Err = reserveStubs(StubInits.size()))
274  return Err;
275 
276  for (auto &Entry : StubInits)
277  createStubInternal(Entry.first(), Entry.second.first,
278  Entry.second.second);
279 
280  return Error::success();
281  }
282 
283  JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
284  auto I = StubIndexes.find(Name);
285  if (I == StubIndexes.end())
286  return nullptr;
287  auto Key = I->second.first;
288  void *StubAddr = IndirectStubsInfos[Key.first].getStub(Key.second);
289  assert(StubAddr && "Missing stub address");
290  auto StubTargetAddr =
291  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(StubAddr));
292  auto StubSymbol = JITSymbol(StubTargetAddr, I->second.second);
293  if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
294  return nullptr;
295  return StubSymbol;
296  }
297 
299  auto I = StubIndexes.find(Name);
300  if (I == StubIndexes.end())
301  return nullptr;
302  auto Key = I->second.first;
303  void *PtrAddr = IndirectStubsInfos[Key.first].getPtr(Key.second);
304  assert(PtrAddr && "Missing pointer address");
305  auto PtrTargetAddr =
306  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(PtrAddr));
307  return JITSymbol(PtrTargetAddr, I->second.second);
308  }
309 
311  auto I = StubIndexes.find(Name);
312  assert(I != StubIndexes.end() && "No stub pointer for symbol");
313  auto Key = I->second.first;
314  *IndirectStubsInfos[Key.first].getPtr(Key.second) =
315  reinterpret_cast<void *>(static_cast<uintptr_t>(NewAddr));
316  return Error::success();
317  }
318 
319 private:
320  Error reserveStubs(unsigned NumStubs) {
321  if (NumStubs <= FreeStubs.size())
322  return Error::success();
323 
324  unsigned NewStubsRequired = NumStubs - FreeStubs.size();
325  unsigned NewBlockId = IndirectStubsInfos.size();
326  typename TargetT::IndirectStubsInfo ISI;
327  if (auto Err =
328  TargetT::emitIndirectStubsBlock(ISI, NewStubsRequired, nullptr))
329  return Err;
330  for (unsigned I = 0; I < ISI.getNumStubs(); ++I)
331  FreeStubs.push_back(std::make_pair(NewBlockId, I));
332  IndirectStubsInfos.push_back(std::move(ISI));
333  return Error::success();
334  }
335 
336  void createStubInternal(StringRef StubName, JITTargetAddress InitAddr,
337  JITSymbolFlags StubFlags) {
338  auto Key = FreeStubs.back();
339  FreeStubs.pop_back();
340  *IndirectStubsInfos[Key.first].getPtr(Key.second) =
341  reinterpret_cast<void *>(static_cast<uintptr_t>(InitAddr));
342  StubIndexes[StubName] = std::make_pair(Key, StubFlags);
343  }
344 
345  std::vector<typename TargetT::IndirectStubsInfo> IndirectStubsInfos;
346  using StubKey = std::pair<uint16_t, uint16_t>;
347  std::vector<StubKey> FreeStubs;
348  StringMap<std::pair<StubKey, JITSymbolFlags>> StubIndexes;
349 };
350 
351 /// @brief Create a local compile callback manager.
352 ///
353 /// The given target triple will determine the ABI, and the given
354 /// ErrorHandlerAddress will be used by the resulting compile callback
355 /// manager if a compile callback fails.
356 std::unique_ptr<JITCompileCallbackManager>
358  JITTargetAddress ErrorHandlerAddress);
359 
360 /// @brief Create a local indriect stubs manager builder.
361 ///
362 /// The given target triple will determine the ABI.
363 std::function<std::unique_ptr<IndirectStubsManager>()>
365 
366 /// @brief Build a function pointer of FunctionType with the given constant
367 /// address.
368 ///
369 /// Usage example: Turn a trampoline address into a function pointer constant
370 /// for use in a stub.
371 Constant *createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr);
372 
373 /// @brief Create a function pointer with the given type, name, and initializer
374 /// in the given Module.
375 GlobalVariable *createImplPointer(PointerType &PT, Module &M, const Twine &Name,
376  Constant *Initializer);
377 
378 /// @brief Turn a function declaration into a stub function that makes an
379 /// indirect call using the given function pointer.
380 void makeStub(Function &F, Value &ImplPointer);
381 
382 /// @brief Raise linkage types and rename as necessary to ensure that all
383 /// symbols are accessible for other modules.
384 ///
385 /// This should be called before partitioning a module to ensure that the
386 /// partitions retain access to each other's symbols.
387 void makeAllSymbolsExternallyAccessible(Module &M);
388 
389 /// @brief Clone a function declaration into a new module.
390 ///
391 /// This function can be used as the first step towards creating a callback
392 /// stub (see makeStub), or moving a function body (see moveFunctionBody).
393 ///
394 /// If the VMap argument is non-null, a mapping will be added between F and
395 /// the new declaration, and between each of F's arguments and the new
396 /// declaration's arguments. This map can then be passed in to moveFunction to
397 /// move the function body if required. Note: When moving functions between
398 /// modules with these utilities, all decls should be cloned (and added to a
399 /// single VMap) before any bodies are moved. This will ensure that references
400 /// between functions all refer to the versions in the new module.
401 Function *cloneFunctionDecl(Module &Dst, const Function &F,
402  ValueToValueMapTy *VMap = nullptr);
403 
404 /// @brief Move the body of function 'F' to a cloned function declaration in a
405 /// different module (See related cloneFunctionDecl).
406 ///
407 /// If the target function declaration is not supplied via the NewF parameter
408 /// then it will be looked up via the VMap.
409 ///
410 /// This will delete the body of function 'F' from its original parent module,
411 /// but leave its declaration.
412 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
413  ValueMaterializer *Materializer = nullptr,
414  Function *NewF = nullptr);
415 
416 /// @brief Clone a global variable declaration into a new module.
417 GlobalVariable *cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
418  ValueToValueMapTy *VMap = nullptr);
419 
420 /// @brief Move global variable GV from its parent module to cloned global
421 /// declaration in a different module.
422 ///
423 /// If the target global declaration is not supplied via the NewGV parameter
424 /// then it will be looked up via the VMap.
425 ///
426 /// This will delete the initializer of GV from its original parent module,
427 /// but leave its declaration.
428 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
429  ValueToValueMapTy &VMap,
430  ValueMaterializer *Materializer = nullptr,
431  GlobalVariable *NewGV = nullptr);
432 
433 /// @brief Clone a global alias declaration into a new module.
434 GlobalAlias *cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
435  ValueToValueMapTy &VMap);
436 
437 /// @brief Clone module flags metadata into the destination module.
438 void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
439  ValueToValueMapTy &VMap);
440 
441 } // end namespace orc
442 
443 } // end namespace llvm
444 
445 #endif // LLVM_EXECUTIONENGINE_ORC_INDIRECTIONUTILS_H
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
Definition: ValueMapper.h:25
IndirectStubsManager implementation for the host architecture, e.g.
Base class for managing collections of named indirect stubs.
Represents a symbol in the JIT.
Definition: JITSymbol.h:122
std::function< std::unique_ptr< IndirectStubsManager >)> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indriect stubs manager builder.
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
void cloneModuleFlagsMetadata(Module &Dst, const Module &Src, ValueToValueMapTy &VMap)
Clone module flags metadata into the destination module.
virtual JITSymbol findStub(StringRef Name, bool ExportedStubsOnly)=0
Find the stub with the given name.
Manage compile callbacks for in-process JITs.
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e...
std::function< JITTargetAddress()> CompileFtor
Target-independent base class for compile callback management.
Handle to a newly created compile callback.
Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override
Change the value of the implementation pointer for the stub.
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module...
std::unique_ptr< JITCompileCallbackManager > createLocalCompileCallbackManager(const Triple &T, JITTargetAddress ErrorHandlerAddress)
Create a local compile callback manager.
void moveGlobalVariableInitializer(GlobalVariable &OrigGV, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, GlobalVariable *NewGV=nullptr)
Move global variable GV from its parent module to cloned global declaration in a different module...
virtual Error createStub(StringRef StubName, JITTargetAddress StubAddr, JITSymbolFlags StubFlags)=0
Create a single stub with the given name, target address and flags.
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
#define F(x, y, z)
Definition: MD5.cpp:55
CompileCallbackInfo getCompileCallback()
Reserve a compile callback.
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:37
std::vector< JITTargetAddress > AvailableTrampolines
const char * Name
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
MemoryBlock getMemoryBlock() const
Definition: Memory.h:178
CompileCallbackInfo(JITTargetAddress Addr, CompileFtor &Compile)
CompileCallbackInfo getCompileCallbackInfo(JITTargetAddress TrampolineAddr)
Get a CompileCallbackInfo for an existing callback.
unsigned size() const
Definition: StringMap.h:111
Flags for symbols in the JIT.
Definition: JITSymbol.h:40
void releaseCompileCallback(JITTargetAddress TrampolineAddr)
Release a compile callback.
static unsigned getPageSize()
Constant * createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr)
Build a function pointer of FunctionType with the given constant address.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
Error createStub(StringRef StubName, JITTargetAddress StubAddr, JITSymbolFlags StubFlags) override
Create a single stub with the given name, target address and flags.
virtual ~IndirectStubsManager()=default
Owning version of MemoryBlock.
Definition: Memory.h:160
JITSymbol findPointer(StringRef Name) override
Find the implementation-pointer for the stub.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
void makeAllSymbolsExternallyAccessible(Module &M)
Raise linkage types and rename as necessary to ensure that all symbols are accessible for other modul...
virtual JITSymbol findPointer(StringRef Name)=0
Find the implementation-pointer for the stub.
JITTargetAddress executeCompileCallback(JITTargetAddress TrampolineAddr)
Execute the callback for the given trampoline id.
Provides a library for accessing information about this process and other processes on the operating ...
virtual Error updatePointer(StringRef Name, JITTargetAddress NewAddr)=0
Change the value of the implementation pointer for the stub.
void * base() const
Definition: Memory.h:176
#define I(x, y, z)
Definition: MD5.cpp:58
LocalJITCompileCallbackManager(JITTargetAddress ErrorHandlerAddress)
Construct a InProcessJITCompileCallbackManager.
JITCompileCallbackManager(JITTargetAddress ErrorHandlerAddress)
Construct a JITCompileCallbackManager.
Error createStubs(const StubInitsMap &StubInits) override
Create StubInits.size() stubs with the given names, target addresses, and flags.
std::map< JITTargetAddress, CompileFtor > TrampolineMapT
virtual ~JITCompileCallbackManager()=default
virtual Error createStubs(const StubInitsMap &StubInits)=0
Create StubInits.size() stubs with the given names, target addresses, and flags.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
std::unique_ptr< CompileCallbackMgr > CCMgr
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function 'F' to a cloned function declaration in a different module (See related clo...
JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override
Find the stub with the given name.
static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags...