LLVM  9.0.0svn
ExecutionUtils.cpp
Go to the documentation of this file.
1 //===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
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 
10 
11 #include "llvm/IR/Constants.h"
12 #include "llvm/IR/Function.h"
13 #include "llvm/IR/GlobalVariable.h"
14 #include "llvm/IR/Module.h"
17 
18 namespace llvm {
19 namespace orc {
20 
22  : InitList(
23  GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
24  I((InitList && End) ? InitList->getNumOperands() : 0) {
25 }
26 
28  assert(InitList == Other.InitList && "Incomparable iterators.");
29  return I == Other.I;
30 }
31 
33  return !(*this == Other);
34 }
35 
37  ++I;
38  return *this;
39 }
40 
42  CtorDtorIterator Temp = *this;
43  ++I;
44  return Temp;
45 }
46 
48  ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
49  assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
50 
51  Constant *FuncC = CS->getOperand(1);
52  Function *Func = nullptr;
53 
54  // Extract function pointer, pulling off any casts.
55  while (FuncC) {
56  if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
57  Func = F;
58  break;
59  } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
60  if (CE->isCast())
61  FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
62  else
63  break;
64  } else {
65  // This isn't anything we recognize. Bail out with Func left set to null.
66  break;
67  }
68  }
69 
70  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
71  Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
72  if (Data && !isa<GlobalValue>(Data))
73  Data = nullptr;
74  return Element(Priority->getZExtValue(), Func, Data);
75 }
76 
78  const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
79  return make_range(CtorDtorIterator(CtorsList, false),
80  CtorDtorIterator(CtorsList, true));
81 }
82 
84  const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
85  return make_range(CtorDtorIterator(DtorsList, false),
86  CtorDtorIterator(DtorsList, true));
87 }
88 
90  if (empty(CtorDtors))
91  return;
92 
93  MangleAndInterner Mangle(
94  JD.getExecutionSession(),
95  (*CtorDtors.begin()).Func->getParent()->getDataLayout());
96 
97  for (const auto &CtorDtor : CtorDtors) {
98  assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
99  "Ctor/Dtor function must be named to be runnable under the JIT");
100 
101  // FIXME: Maybe use a symbol promoter here instead.
102  if (CtorDtor.Func->hasLocalLinkage()) {
103  CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
104  CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
105  }
106 
107  if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
108  dbgs() << " Skipping because why now?\n";
109  continue;
110  }
111 
112  CtorDtorsByPriority[CtorDtor.Priority].push_back(
113  Mangle(CtorDtor.Func->getName()));
114  }
115 }
116 
118  using CtorDtorTy = void (*)();
119 
120  SymbolNameSet Names;
121 
122  for (auto &KV : CtorDtorsByPriority) {
123  for (auto &Name : KV.second) {
124  auto Added = Names.insert(Name).second;
125  (void)Added;
126  assert(Added && "Ctor/Dtor names clashed");
127  }
128  }
129 
130  auto &ES = JD.getExecutionSession();
131  if (auto CtorDtorMap =
132  ES.lookup(JITDylibSearchList({{&JD, true}}), std::move(Names),
133  NoDependenciesToRegister, true)) {
134  for (auto &KV : CtorDtorsByPriority) {
135  for (auto &Name : KV.second) {
136  assert(CtorDtorMap->count(Name) && "No entry for Name");
137  auto CtorDtor = reinterpret_cast<CtorDtorTy>(
138  static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
139  CtorDtor();
140  }
141  }
142  CtorDtorsByPriority.clear();
143  return Error::success();
144  } else
145  return CtorDtorMap.takeError();
146 }
147 
149  auto& CXXDestructorDataPairs = DSOHandleOverride;
150  for (auto &P : CXXDestructorDataPairs)
151  P.first(P.second);
152  CXXDestructorDataPairs.clear();
153 }
154 
156  void *Arg,
157  void *DSOHandle) {
158  auto& CXXDestructorDataPairs =
159  *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
160  CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
161  return 0;
162 }
163 
165  MangleAndInterner &Mangle) {
166  SymbolMap RuntimeInterposes;
167  RuntimeInterposes[Mangle("__dso_handle")] =
168  JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
170  RuntimeInterposes[Mangle("__cxa_atexit")] =
171  JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
173 
174  return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
175 }
176 
179  : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
180  GlobalPrefix(GlobalPrefix) {}
181 
183 DynamicLibrarySearchGenerator::Load(const char *FileName, char GlobalPrefix,
184  SymbolPredicate Allow) {
185  std::string ErrMsg;
186  auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
187  if (!Lib.isValid())
188  return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
189  return DynamicLibrarySearchGenerator(std::move(Lib), GlobalPrefix,
190  std::move(Allow));
191 }
192 
195  const SymbolNameSet &Names) {
196  orc::SymbolNameSet Added;
197  orc::SymbolMap NewSymbols;
198 
199  bool HasGlobalPrefix = (GlobalPrefix != '\0');
200 
201  for (auto &Name : Names) {
202  if ((*Name).empty())
203  continue;
204 
205  if (Allow && !Allow(Name))
206  continue;
207 
208  if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
209  continue;
210 
211  std::string Tmp((*Name).data() + HasGlobalPrefix,
212  (*Name).size() - HasGlobalPrefix);
213  if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
214  Added.insert(Name);
215  NewSymbols[Name] = JITEvaluatedSymbol(
216  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
218  }
219  }
220 
221  // Add any new symbols to JD. Since the generator is only called for symbols
222  // that are not already defined, this will never trigger a duplicate
223  // definition error, so we can wrap this call in a 'cantFail'.
224  if (!NewSymbols.empty())
225  cantFail(JD.define(absoluteSymbols(std::move(NewSymbols))));
226 
227  return Added;
228 }
229 
230 } // End namespace orc.
231 } // End namespace llvm.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:703
Accessor for an element of the global_ctors/global_dtors array.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static Expected< DynamicLibrarySearchGenerator > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:405
Externally visible function.
Definition: GlobalValue.h:48
F(f)
Expected< SymbolNameSet > operator()(JITDylib &JD, const SymbolNameSet &Names)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
CtorDtorIterator & operator++()
Pre-increment iterator.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols, VModuleKey K=VModuleKey())
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Definition: Core.h:331
Definition: BitVector.h:937
std::vector< std::pair< JITDylib *, bool > > JITDylibSearchList
A list of (JITDylib*, bool) pairs.
Definition: Core.h:57
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:884
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:918
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
void add(iterator_range< CtorDtorIterator > CtorDtors)
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
std::function< bool(SymbolStringPtr)> SymbolPredicate
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
Value * getOperand(unsigned i) const
Definition: User.h:169
#define P(N)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast_or_null(const Y &Val)
Definition: Casting.h:353
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
unsigned getNumOperands() const
Definition: User.h:191
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm.global_dtors instance.
Module.h This file contains the declarations for the Module class.
static Constant * getInitializer(Constant *C)
Definition: Evaluator.cpp:205
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:208
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:122
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
Element operator*() const
Dereference iterator.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
IteratorT begin() const
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition: Core.cpp:140
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:495
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77