LLVM  8.0.1
RTDyldObjectLinkingLayer.cpp
Go to the documentation of this file.
1 //===-- RTDyldObjectLinkingLayer.cpp - RuntimeDyld backed ORC ObjectLayer -===//
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 
11 
12 namespace {
13 
14 using namespace llvm;
15 using namespace llvm::orc;
16 
17 class JITDylibSearchOrderResolver : public JITSymbolResolver {
18 public:
19  JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
20 
21  void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) {
22  auto &ES = MR.getTargetJITDylib().getExecutionSession();
23  SymbolNameSet InternedSymbols;
24 
25  // Intern the requested symbols: lookup takes interned strings.
26  for (auto &S : Symbols)
27  InternedSymbols.insert(ES.intern(S));
28 
29  // Build an OnResolve callback to unwrap the interned strings and pass them
30  // to the OnResolved callback.
31  // FIXME: Switch to move capture of OnResolved once we have c++14.
32  auto OnResolvedWithUnwrap =
33  [OnResolved](Expected<SymbolMap> InternedResult) {
34  if (!InternedResult) {
35  OnResolved(InternedResult.takeError());
36  return;
37  }
38 
39  LookupResult Result;
40  for (auto &KV : *InternedResult)
41  Result[*KV.first] = std::move(KV.second);
42  OnResolved(Result);
43  };
44 
45  // We're not waiting for symbols to be ready. Just log any errors.
46  auto OnReady = [&ES](Error Err) { ES.reportError(std::move(Err)); };
47 
48  // Register dependencies for all symbols contained in this set.
49  auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
50  MR.addDependenciesForAll(Deps);
51  };
52 
53  JITDylibSearchList SearchOrder;
54  MR.getTargetJITDylib().withSearchOrderDo(
55  [&](const JITDylibSearchList &JDs) { SearchOrder = JDs; });
56  ES.lookup(SearchOrder, InternedSymbols, OnResolvedWithUnwrap, OnReady,
57  RegisterDependencies);
58  }
59 
60  Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
61  LookupSet Result;
62 
63  for (auto &KV : MR.getSymbols()) {
64  if (Symbols.count(*KV.first))
65  Result.insert(*KV.first);
66  }
67 
68  return Result;
69  }
70 
71 private:
73 };
74 
75 } // end anonymous namespace
76 
77 namespace llvm {
78 namespace orc {
79 
81  ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
82  NotifyLoadedFunction NotifyLoaded, NotifyEmittedFunction NotifyEmitted)
83  : ObjectLayer(ES), GetMemoryManager(GetMemoryManager),
84  NotifyLoaded(std::move(NotifyLoaded)),
85  NotifyEmitted(std::move(NotifyEmitted)) {}
86 
88  std::unique_ptr<MemoryBuffer> O) {
89  assert(O && "Object must not be null");
90 
91  // This method launches an asynchronous link step that will fulfill our
92  // materialization responsibility. We need to switch R to be heap
93  // allocated before that happens so it can live as long as the asynchronous
94  // link needs it to (i.e. it must be able to outlive this method).
95  auto SharedR = std::make_shared<MaterializationResponsibility>(std::move(R));
96 
97  auto &ES = getExecutionSession();
98 
100 
101  if (!Obj) {
102  getExecutionSession().reportError(Obj.takeError());
103  SharedR->failMaterialization();
104  return;
105  }
106 
107  // Collect the internal symbols from the object file: We will need to
108  // filter these later.
109  auto InternalSymbols = std::make_shared<std::set<StringRef>>();
110  {
111  for (auto &Sym : (*Obj)->symbols()) {
112  if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global)) {
113  if (auto SymName = Sym.getName())
114  InternalSymbols->insert(*SymName);
115  else {
116  ES.reportError(SymName.takeError());
118  return;
119  }
120  }
121  }
122  }
123 
124  auto K = R.getVModuleKey();
125  RuntimeDyld::MemoryManager *MemMgr = nullptr;
126 
127  // Create a record a memory manager for this object.
128  {
129  auto Tmp = GetMemoryManager();
130  std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
131  MemMgrs.push_back(std::move(Tmp));
132  MemMgr = MemMgrs.back().get();
133  }
134 
135  JITDylibSearchOrderResolver Resolver(*SharedR);
136 
137  /* Thoughts on proper cross-dylib weak symbol handling:
138  *
139  * Change selection of canonical defs to be a manually triggered process, and
140  * add a 'canonical' bit to symbol definitions. When canonical def selection
141  * is triggered, sweep the JITDylibs to mark defs as canonical, discard
142  * duplicate defs.
143  */
145  **Obj, std::move(O), *MemMgr, Resolver, ProcessAllSections,
146  [this, K, SharedR, &Obj, InternalSymbols](
147  std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
148  std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
149  return onObjLoad(K, *SharedR, **Obj, std::move(LoadedObjInfo),
150  ResolvedSymbols, *InternalSymbols);
151  },
152  [this, K, SharedR](Error Err) {
153  onObjEmit(K, *SharedR, std::move(Err));
154  });
155 }
156 
157 Error RTDyldObjectLinkingLayer::onObjLoad(
159  std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
160  std::map<StringRef, JITEvaluatedSymbol> Resolved,
161  std::set<StringRef> &InternalSymbols) {
162  SymbolFlagsMap ExtraSymbolsToClaim;
163  SymbolMap Symbols;
164  for (auto &KV : Resolved) {
165  // Scan the symbols and add them to the Symbols map for resolution.
166 
167  // We never claim internal symbols.
168  if (InternalSymbols.count(KV.first))
169  continue;
170 
171  auto InternedName = getExecutionSession().intern(KV.first);
172  auto Flags = KV.second.getFlags();
173 
174  // Override object flags and claim responsibility for symbols if
175  // requested.
176  if (OverrideObjectFlags || AutoClaimObjectSymbols) {
177  auto I = R.getSymbols().find(InternedName);
178 
179  if (OverrideObjectFlags && I != R.getSymbols().end())
180  Flags = JITSymbolFlags::stripTransientFlags(I->second);
181  else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
182  ExtraSymbolsToClaim[InternedName] = Flags;
183  }
184 
185  Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
186  }
187 
188  if (!ExtraSymbolsToClaim.empty())
189  if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
190  return Err;
191 
192  R.resolve(Symbols);
193 
194  if (NotifyLoaded)
195  NotifyLoaded(K, Obj, *LoadedObjInfo);
196 
197  return Error::success();
198 }
199 
200 void RTDyldObjectLinkingLayer::onObjEmit(VModuleKey K,
202  Error Err) {
203  if (Err) {
204  getExecutionSession().reportError(std::move(Err));
206  return;
207  }
208 
209  R.emit();
210 
211  if (NotifyEmitted)
212  NotifyEmitted(K);
213 }
214 
215 } // End namespace orc.
216 } // End namespace llvm.
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:161
void emit()
Notifies the target JITDylib (and any pending queries on that JITDylib) that all symbols covered by t...
Definition: Core.cpp:415
This class represents lattice values for constants.
Definition: AllocatorList.h:24
Error defineMaterializing(const SymbolFlagsMap &SymbolFlags)
Adds new symbols to the JITDylib and this responsibility instance.
Definition: Core.cpp:426
static sys::Mutex Lock
This class is the base class for all object file types.
Definition: ObjectFile.h:202
std::function< void(VModuleKey, const object::ObjectFile &Obj, const RuntimeDyld::LoadedObjectInfo &)> NotifyLoadedFunction
Functor for receiving object-loaded notifications.
void jitLinkForORC(object::ObjectFile &Obj, std::unique_ptr< MemoryBuffer > UnderlyingBuffer, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver, bool ProcessAllSections, std::function< Error(std::unique_ptr< LoadedObjectInfo >, std::map< StringRef, JITEvaluatedSymbol >)> OnLoaded, std::function< void(Error)> OnEmitted)
uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:40
Definition: BitVector.h:938
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:715
std::vector< std::pair< JITDylib *, bool > > JITDylibSearchList
A list of (JITDylib*, bool) pairs.
Definition: Core.h:58
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
RTDyldObjectLinkingLayer(ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager, NotifyLoadedFunction NotifyLoaded=NotifyLoadedFunction(), NotifyEmittedFunction NotifyEmitted=NotifyEmittedFunction())
Construct an ObjectLinkingLayer with the given NotifyLoaded, and NotifyEmitted functors.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:155
ExecutionSession & getExecutionSession()
Returns the execution session for this layer.
Definition: Layer.h:120
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
VModuleKey getVModuleKey() const
Returns the VModuleKey for this instance.
Definition: Core.h:172
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1774
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:188
std::function< void(VModuleKey)> NotifyEmittedFunction
Functor for receiving finalization notifications.
Symbol resolution interface.
Definition: JITSymbol.h:344
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
void resolve(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition: Core.cpp:393
std::function< std::unique_ptr< RuntimeDyld::MemoryManager >()> GetMemoryManagerFunction
An ExecutionSession represents a running JIT program.
Definition: Core.h:697
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:209
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:754
#define I(x, y, z)
Definition: MD5.cpp:58
iterator end()
Definition: DenseMap.h:109
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:123
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition: Core.cpp:443
const SymbolFlagsMap & getSymbols()
Returns the symbol flags map for this responsibility instance.
Definition: Core.h:178
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
static JITSymbolFlags stripTransientFlags(JITSymbolFlags Orig)
Definition: JITSymbol.h:74
Interface for Layers that accept object files.
Definition: Layer.h:114
void emit(MaterializationResponsibility R, std::unique_ptr< MemoryBuffer > O) override
Emit the object.