LLVM 17.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"
24#include "llvm/Object/Archive.h"
26#include <algorithm>
27#include <cstdint>
28#include <utility>
29#include <vector>
30
31namespace llvm {
32
33class ConstantArray;
34class GlobalVariable;
35class Function;
36class Module;
37class Value;
38
39namespace orc {
40
41class 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.
49public:
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
83private:
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.
99public:
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
123private:
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
144public:
145 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
147 Error run();
148
149private:
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.
173public:
174 /// Run any destructors recorded by the overriden __cxa_atexit function
175 /// (CXAAtExitOverride).
176 void runDestructors();
177
178protected:
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
192public:
194};
195
196/// An interface for Itanium __cxa_atexit interposer implementations.
198public:
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
207private:
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.
218public:
219 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
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,
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,
236
237 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
238 /// the current process.
240 GetForCurrentProcess(char GlobalPrefix,
242 return Load(nullptr, GlobalPrefix, std::move(Allow));
243 }
244
246 JITDylibLookupFlags JDLookupFlags,
247 const SymbolLookupSet &Symbols) override;
248
249private:
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.
261public:
262 // Interface builder function for objects loaded from this archive.
265 ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
266
267 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
268 ///
269 /// This call will succeed if the file at the given path is a static library
270 /// is a valid archive, otherwise it will return an error.
272 Load(ObjectLayer &L, const char *FileName,
273 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
274
275 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
276 ///
277 /// This call will succeed if the file at the given path is a static library
278 /// or a MachO universal binary containing a static library that is compatible
279 /// with the given triple. Otherwise it will return an error.
281 Load(ObjectLayer &L, const char *FileName, const Triple &TT,
282 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
283
284 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
285 /// This call will succeed if the buffer contains a valid archive, otherwise
286 /// it will return an error.
288 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
289 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
290
291 /// Returns a list of filenames of dynamic libraries that this archive has
292 /// imported. This class does not load these libraries by itself. User is
293 /// responsible for making sure these libraries are avaliable to the JITDylib.
294 const std::set<std::string> &getImportedDynamicLibraries() const {
295 return ImportedDynamicLibraries;
296 }
297
299 JITDylibLookupFlags JDLookupFlags,
300 const SymbolLookupSet &Symbols) override;
301
302private:
304 std::unique_ptr<MemoryBuffer> ArchiveBuffer,
305 GetObjectFileInterface GetObjFileInterface,
306 Error &Err);
307
308 Error buildObjectFilesMap();
309
310 ObjectLayer &L;
311 GetObjectFileInterface GetObjFileInterface;
312 std::set<std::string> ImportedDynamicLibraries;
313 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
314 std::unique_ptr<object::Archive> Archive;
316};
317
318/// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
319/// stubs.
320///
321/// If an instance of this class is attached to a JITDylib as a fallback
322/// definition generator, PLT stubs and dllimport __imp_ symbols will be
323/// generated for external symbols found outside the given jitdylib. Currently
324/// only supports x86_64 architecture.
326public:
327 /// Creates a DLLImportDefinitionGenerator instance.
328 static std::unique_ptr<DLLImportDefinitionGenerator>
330
332 JITDylibLookupFlags JDLookupFlags,
333 const SymbolLookupSet &Symbols) override;
334
335private:
337 : ES(ES), L(L) {}
338
339 static Expected<unsigned> getTargetPointerSize(const Triple &TT);
340 static Expected<support::endianness> getTargetEndianness(const Triple &TT);
342 createStubsGraph(const SymbolMap &Resolved);
343
344 static StringRef getImpPrefix() { return "__imp_"; }
345
346 static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
347
350};
351
352} // end namespace orc
353} // end namespace llvm
354
355#endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
This file defines the StringMap class.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
@ GlobalPrefix
Definition: AsmWriter.cpp:347
#define F(x, y, z)
Definition: MD5.cpp:55
Machine Check Debug Module
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ConstantArray - Constant Array Declarations.
Definition: Constants.h:409
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
Tagged union holding either a T or a Error.
Definition: Error.h:470
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator > global_value_iterator
Definition: Module.h:694
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ObjectFormatType
Definition: Triple.h:279
LLVM Value Representation.
Definition: Value.h:74
A range adaptor for a pair of iterators.
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
Element operator*() const
Dereference iterator.
CtorDtorIterator & operator++()
Pre-increment iterator.
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
void add(iterator_range< CtorDtorIterator > CtorDtors)
A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT stubs.
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
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 generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:926
A utility class to expose symbols found via dlsym to the JIT.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
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.
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...
An ExecutionSession represents a running JIT program.
Definition: Core.h:1373
An interface for Itanium __cxa_atexit interposer implementations.
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:962
Support class for static dtor execution.
JITTargetAddress toTargetAddress(PtrTy *P)
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
std::pair< DestructorPtr, void * > CXXDestructorDataPair
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition: Core.h:901
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:26
Interface for Layers that accept object files.
Definition: Layer.h:133
An ObjectLayer implementation built on JITLink.
This iterator provides a convenient way to iterate over GlobalValues that have initialization effects...
StaticInitGVIterator & operator++()
bool operator!=(const StaticInitGVIterator &O) const
bool operator==(const StaticInitGVIterator &O) const
A utility class to expose symbols from a static library.
const std::set< std::string > & getImportedDynamicLibraries() const
Returns a list of filenames of dynamic libraries that this archive has imported.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer.
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.
unique_function< Expected< MaterializationUnit::Interface >(ExecutionSession &ES, MemoryBufferRef ObjBuffer)> GetObjectFileInterface
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:180
Pointer to a pooled string representing a symbol name.
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
iterator_range< StaticInitGVIterator > getStaticInitGVs(Module &M)
Create an iterator range over the GlobalValues that contribute to static initialization.
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:132
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:154
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Accessor for an element of the global_ctors/global_dtors array.
Element(unsigned Priority, Function *Func, Value *Data)