LLVM  14.0.0git
ExecutionUtils.h
Go to the documentation of this file.
1 //===- ExecutionUtils.h - Utilities for executing code in Orc ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Contains utilities for executing code in Orc.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
14 #define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
15 
16 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Object/Archive.h"
25 #include <algorithm>
26 #include <cstdint>
27 #include <utility>
28 #include <vector>
29 
30 namespace llvm {
31 
32 class ConstantArray;
33 class GlobalVariable;
34 class Function;
35 class Module;
36 class TargetMachine;
37 class Value;
38 
39 namespace orc {
40 
41 class ObjectLayer;
42 
43 /// This iterator provides a convenient way to iterate over the elements
44 /// of an llvm.global_ctors/llvm.global_dtors instance.
45 ///
46 /// The easiest way to get hold of instances of this class is to use the
47 /// getConstructors/getDestructors functions.
49 public:
50  /// Accessor for an element of the global_ctors/global_dtors array.
51  ///
52  /// This class provides a read-only view of the element with any casts on
53  /// the function stripped away.
54  struct Element {
57 
58  unsigned Priority;
61  };
62 
63  /// Construct an iterator instance. If End is true then this iterator
64  /// acts as the end of the range, otherwise it is the beginning.
65  CtorDtorIterator(const GlobalVariable *GV, bool End);
66 
67  /// Test iterators for equality.
68  bool operator==(const CtorDtorIterator &Other) const;
69 
70  /// Test iterators for inequality.
71  bool operator!=(const CtorDtorIterator &Other) const;
72 
73  /// Pre-increment iterator.
75 
76  /// Post-increment iterator.
78 
79  /// Dereference iterator. The resulting value provides a read-only view
80  /// of this element of the global_ctors/global_dtors list.
81  Element operator*() const;
82 
83 private:
84  const ConstantArray *InitList;
85  unsigned I;
86 };
87 
88 /// Create an iterator range over the entries of the llvm.global_ctors
89 /// array.
91 
92 /// Create an iterator range over the entries of the llvm.global_ctors
93 /// array.
95 
96 /// This iterator provides a convenient way to iterate over GlobalValues that
97 /// have initialization effects.
99 public:
100  StaticInitGVIterator() = default;
101 
103  : I(M.global_values().begin()), E(M.global_values().end()),
104  ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
105  if (I != E) {
106  if (!isStaticInitGlobal(*I))
107  moveToNextStaticInitGlobal();
108  } else
110  }
111 
112  bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
113  bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
114 
116  assert(I != E && "Increment past end of range");
117  moveToNextStaticInitGlobal();
118  return *this;
119  }
120 
121  GlobalValue &operator*() { return *I; }
122 
123 private:
124  bool isStaticInitGlobal(GlobalValue &GV);
125  void moveToNextStaticInitGlobal() {
126  ++I;
127  while (I != E && !isStaticInitGlobal(*I))
128  ++I;
129  if (I == E)
131  }
132 
135 };
136 
137 /// Create an iterator range over the GlobalValues that contribute to static
138 /// initialization.
141 }
142 
144 public:
145  CtorDtorRunner(JITDylib &JD) : JD(JD) {}
146  void add(iterator_range<CtorDtorIterator> CtorDtors);
147  Error run();
148 
149 private:
150  using CtorDtorList = std::vector<SymbolStringPtr>;
151  using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
152 
153  JITDylib &JD;
154  CtorDtorPriorityMap CtorDtorsByPriority;
155 };
156 
157 /// Support class for static dtor execution. For hosted (in-process) JITs
158 /// only!
159 ///
160 /// If a __cxa_atexit function isn't found C++ programs that use static
161 /// destructors will fail to link. However, we don't want to use the host
162 /// process's __cxa_atexit, because it will schedule JIT'd destructors to run
163 /// after the JIT has been torn down, which is no good. This class makes it easy
164 /// to override __cxa_atexit (and the related __dso_handle).
165 ///
166 /// To use, clients should manually call searchOverrides from their symbol
167 /// resolver. This should generally be done after attempting symbol resolution
168 /// inside the JIT, but before searching the host process's symbol table. When
169 /// the client determines that destructors should be run (generally at JIT
170 /// teardown or after a return from main), the runDestructors method should be
171 /// called.
173 public:
174  /// Run any destructors recorded by the overriden __cxa_atexit function
175  /// (CXAAtExitOverride).
176  void runDestructors();
177 
178 protected:
179  template <typename PtrTy> JITTargetAddress toTargetAddress(PtrTy *P) {
180  return static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(P));
181  }
182 
183  using DestructorPtr = void (*)(void *);
184  using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
185  using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
187  static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
188  void *DSOHandle);
189 };
190 
192 public:
194 };
195 
196 /// An interface for Itanium __cxa_atexit interposer implementations.
198 public:
199  struct AtExitRecord {
200  void (*F)(void *);
201  void *Ctx;
202  };
203 
204  void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
205  void runAtExits(void *DSOHandle);
206 
207 private:
208  std::mutex AtExitsMutex;
210 };
211 
212 /// A utility class to expose symbols found via dlsym to the JIT.
213 ///
214 /// If an instance of this class is attached to a JITDylib as a fallback
215 /// definition generator, then any symbol found in the given DynamicLibrary that
216 /// passes the 'Allow' predicate will be added to the JITDylib.
218 public:
220 
221  /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
222  /// given sys::DynamicLibrary.
223  ///
224  /// If the Allow predicate is given then only symbols matching the predicate
225  /// will be searched for. If the predicate is not given then all symbols will
226  /// be searched for.
227  DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
228  SymbolPredicate Allow = SymbolPredicate());
229 
230  /// Permanently loads the library at the given path and, on success, returns
231  /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
232  /// in the library. On failure returns the reason the library failed to load.
234  Load(const char *FileName, char GlobalPrefix,
235  SymbolPredicate Allow = SymbolPredicate());
236 
237  /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
238  /// the current process.
240  GetForCurrentProcess(char GlobalPrefix,
241  SymbolPredicate Allow = SymbolPredicate()) {
242  return Load(nullptr, GlobalPrefix, std::move(Allow));
243  }
244 
246  JITDylibLookupFlags JDLookupFlags,
247  const SymbolLookupSet &Symbols) override;
248 
249 private:
250  sys::DynamicLibrary Dylib;
251  SymbolPredicate Allow;
252  char GlobalPrefix;
253 };
254 
255 /// A utility class to expose symbols from a static library.
256 ///
257 /// If an instance of this class is attached to a JITDylib as a fallback
258 /// definition generator, then any symbol found in the archive will result in
259 /// the containing object being added to the JITDylib.
261 public:
262  /// Try to create a StaticLibraryDefinitionGenerator from the given path.
263  ///
264  /// This call will succeed if the file at the given path is a static library
265  /// is a valid archive, otherwise it will return an error.
267  Load(ObjectLayer &L, const char *FileName);
268 
269  /// Try to create a StaticLibraryDefinitionGenerator from the given path.
270  ///
271  /// This call will succeed if the file at the given path is a static library
272  /// or a MachO universal binary containing a static library that is compatible
273  /// with the given triple. Otherwise it will return an error.
275  Load(ObjectLayer &L, const char *FileName, const Triple &TT);
276 
277  /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
278  /// This call will succeed if the buffer contains a valid archive, otherwise
279  /// it will return an error.
281  Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer);
282 
284  JITDylibLookupFlags JDLookupFlags,
285  const SymbolLookupSet &Symbols) override;
286 
287 private:
289  std::unique_ptr<MemoryBuffer> ArchiveBuffer,
290  Error &Err);
291 
292  ObjectLayer &L;
293  std::unique_ptr<MemoryBuffer> ArchiveBuffer;
294  std::unique_ptr<object::Archive> Archive;
295 };
296 
297 } // end namespace orc
298 } // end namespace llvm
299 
300 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
llvm::orc::CtorDtorIterator::Element::Func
Function * Func
Definition: ExecutionUtils.h:59
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::orc::JITDylib
Represents a JIT'd dynamic library.
Definition: Core.h:938
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
JITSymbol.h
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::orc::CtorDtorRunner::add
void add(iterator_range< CtorDtorIterator > CtorDtors)
Definition: ExecutionUtils.cpp:112
llvm::orc::getConstructors
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
Definition: ExecutionUtils.cpp:80
llvm::Function
Definition: Function.h:62
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
llvm::orc::SymbolLookupSet
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:175
llvm::orc::SymbolStringPtr
Pointer to a pooled string representing a symbol name.
Definition: SymbolStringPool.h:50
llvm::GlobalVariable
Definition: GlobalVariable.h:40
llvm::orc::StaticLibraryDefinitionGenerator::Load
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName)
Try to create a StaticLibraryDefinitionGenerator from the given path.
Definition: ExecutionUtils.cpp:272
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
GlobalPrefix
@ GlobalPrefix
Definition: AsmWriter.cpp:343
DynamicLibrary.h
llvm::orc::StaticInitGVIterator::StaticInitGVIterator
StaticInitGVIterator(Module &M)
Definition: ExecutionUtils.h:102
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::sys::path::begin
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:226
llvm::orc::ItaniumCXAAtExitSupport::AtExitRecord::F
void(* F)(void *)
Definition: ExecutionUtils.h:200
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::orc::LocalCXXRuntimeOverridesBase::DSOHandleOverride
CXXDestructorDataPairList DSOHandleOverride
Definition: ExecutionUtils.h:186
llvm::Mangler
Definition: Mangler.h:27
llvm::concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator >
llvm::orc::LookupKind
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:149
RuntimeDyld.h
llvm::orc::CtorDtorIterator::operator==
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
Definition: ExecutionUtils.cpp:30
llvm::sys::DynamicLibrary
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
Definition: DynamicLibrary.h:36
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::orc::CtorDtorIterator
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
Definition: ExecutionUtils.h:48
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:206
llvm::orc::DynamicLibrarySearchGenerator::DynamicLibrarySearchGenerator
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
Definition: ExecutionUtils.cpp:221
llvm::orc::CtorDtorIterator::Element::Data
Value * Data
Definition: ExecutionUtils.h:60
llvm::orc::StaticInitGVIterator
This iterator provides a convenient way to iterate over GlobalValues that have initialization effects...
Definition: ExecutionUtils.h:98
llvm::orc::LocalCXXRuntimeOverrides::enable
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Definition: ExecutionUtils.cpp:184
llvm::orc::DynamicLibrarySearchGenerator
A utility class to expose symbols found via dlsym to the JIT.
Definition: ExecutionUtils.h:217
llvm::ConstantArray
ConstantArray - Constant Array Declarations.
Definition: Constants.h:409
llvm::orc::StaticInitGVIterator::StaticInitGVIterator
StaticInitGVIterator()=default
llvm::orc::ObjectLayer
Interface for Layers that accept object files.
Definition: Layer.h:134
llvm::orc::ItaniumCXAAtExitSupport
An interface for Itanium __cxa_atexit interposer implementations.
Definition: ExecutionUtils.h:197
StringMap.h
llvm::orc::CtorDtorIterator::Element::Priority
unsigned Priority
Definition: ExecutionUtils.h:58
llvm::orc::getStaticInitGVs
iterator_range< StaticInitGVIterator > getStaticInitGVs(Module &M)
Create an iterator range over the GlobalValues that contribute to static initialization.
Definition: ExecutionUtils.h:139
llvm::orc::LocalCXXRuntimeOverridesBase::runDestructors
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
Definition: ExecutionUtils.cpp:168
llvm::orc::DynamicLibrarySearchGenerator::tryToGenerate
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition: ExecutionUtils.cpp:237
llvm::orc::LocalCXXRuntimeOverridesBase::CXXDestructorDataPairList
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
Definition: ExecutionUtils.h:185
llvm::orc::LocalCXXRuntimeOverridesBase::DestructorPtr
void(*)(void *) DestructorPtr
Definition: ExecutionUtils.h:183
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:206
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::orc::getDestructors
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
Definition: ExecutionUtils.cpp:86
uint64_t
llvm::orc::ItaniumCXAAtExitSupport::AtExitRecord::Ctx
void * Ctx
Definition: ExecutionUtils.h:201
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::DenseMap
Definition: DenseMap.h:714
Archive.h
llvm::orc::LocalCXXRuntimeOverridesBase::CXAAtExitOverride
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
Definition: ExecutionUtils.cpp:175
llvm::orc::CtorDtorIterator::Element
Accessor for an element of the global_ctors/global_dtors array.
Definition: ExecutionUtils.h:54
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::orc::CtorDtorIterator::operator!=
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
Definition: ExecutionUtils.cpp:35
iterator_range.h
llvm::orc::StaticLibraryDefinitionGenerator
A utility class to expose symbols from a static library.
Definition: ExecutionUtils.h:260
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:83
llvm::orc::DefinitionGenerator
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:903
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::orc::StaticInitGVIterator::operator==
bool operator==(const StaticInitGVIterator &O) const
Definition: ExecutionUtils.h:112
llvm::orc::StaticLibraryDefinitionGenerator::Create
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer)
Try to create a StaticLibrarySearchGenerator from the given memory buffer.
Definition: ExecutionUtils.cpp:328
llvm::orc::CtorDtorIterator::operator++
CtorDtorIterator & operator++()
Pre-increment iterator.
Definition: ExecutionUtils.cpp:39
llvm::orc::StaticInitGVIterator::operator!=
bool operator!=(const StaticInitGVIterator &O) const
Definition: ExecutionUtils.h:113
Module
Machine Check Debug Module
Definition: MachineCheckDebugify.cpp:122
llvm::orc::LookupState
Wraps state for a lookup-in-progress.
Definition: Core.h:878
llvm::orc::ItaniumCXAAtExitSupport::runAtExits
void runAtExits(void *DSOHandle)
Definition: ExecutionUtils.cpp:203
llvm::Triple::ObjectFormatType
ObjectFormatType
Definition: Triple.h:236
llvm::orc::ItaniumCXAAtExitSupport::registerAtExit
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Definition: ExecutionUtils.cpp:197
llvm::orc::MangleAndInterner
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:26
llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
Definition: ExecutionUtils.h:240
llvm::orc::StaticInitGVIterator::operator*
GlobalValue & operator*()
Definition: ExecutionUtils.h:121
Mangling.h
llvm::orc::ItaniumCXAAtExitSupport::AtExitRecord
Definition: ExecutionUtils.h:199
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::AArch64CC::LS
@ LS
Definition: AArch64BaseInfo.h:264
llvm::orc::StaticLibraryDefinitionGenerator::tryToGenerate
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition: ExecutionUtils.cpp:341
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::orc::CtorDtorIterator::Element::Element
Element(unsigned Priority, Function *Func, Value *Data)
Definition: ExecutionUtils.h:55
llvm::orc::LocalCXXRuntimeOverridesBase
Support class for static dtor execution.
Definition: ExecutionUtils.h:172
llvm::orc::StaticInitGVIterator::operator++
StaticInitGVIterator & operator++()
Definition: ExecutionUtils.h:115
llvm::orc::CtorDtorIterator::CtorDtorIterator
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
Definition: ExecutionUtils.cpp:24
Core.h
llvm::orc::CtorDtorIterator::operator*
Element operator*() const
Dereference iterator.
Definition: ExecutionUtils.cpp:50
llvm::orc::DynamicLibrarySearchGenerator::SymbolPredicate
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
Definition: ExecutionUtils.h:219
llvm::orc::LocalCXXRuntimeOverridesBase::CXXDestructorDataPair
std::pair< DestructorPtr, void * > CXXDestructorDataPair
Definition: ExecutionUtils.h:184
llvm::orc::DynamicLibrarySearchGenerator::Load
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Definition: ExecutionUtils.cpp:227
llvm::iterator_range
A range adaptor for a pair of iterators.
Definition: iterator_range.h:30
llvm::orc::LocalCXXRuntimeOverridesBase::toTargetAddress
JITTargetAddress toTargetAddress(PtrTy *P)
Definition: ExecutionUtils.h:179
llvm::orc::LocalCXXRuntimeOverrides
Definition: ExecutionUtils.h:191
llvm::orc::JITDylibLookupFlags
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:127
llvm::Module::global_value_iterator
concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator > global_value_iterator
Definition: Module.h:691
llvm::orc::CtorDtorRunner::run
Error run()
Definition: ExecutionUtils.cpp:140
OrcError.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::orc::CtorDtorRunner
Definition: ExecutionUtils.h:143
llvm::codeview::PublicSymFlags::Function
@ Function
llvm::orc::CtorDtorRunner::CtorDtorRunner
CtorDtorRunner(JITDylib &JD)
Definition: ExecutionUtils.h:145