blob: 28fc04b283d315d981d37c5f2862b395c6bc8701 [file] [log] [blame]
Lang Hames93de2a12015-01-23 21:25:00 +00001//===---- OrcMCJITReplacement.h - Orc based MCJIT replacement ---*- 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// Orc based MCJIT replacement.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
15#define LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
16
17#include "llvm/ExecutionEngine/ExecutionEngine.h"
18#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
19#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
20#include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
21#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
22#include "llvm/Object/Archive.h"
23#include "llvm/Target/TargetSubtargetInfo.h"
24
25namespace llvm {
26
27class OrcMCJITReplacement : public ExecutionEngine {
28
29 class ForwardingRTDyldMM : public RTDyldMemoryManager {
30 public:
31 ForwardingRTDyldMM(OrcMCJITReplacement &M) : M(M) {}
32
33 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
34 unsigned SectionID,
35 StringRef SectionName) override {
36 uint8_t *Addr =
37 M.MM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
38 M.SectionsAllocatedSinceLastLoad.insert(Addr);
39 return Addr;
40 }
41
42 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
43 unsigned SectionID, StringRef SectionName,
44 bool IsReadOnly) override {
45 uint8_t *Addr = M.MM->allocateDataSection(Size, Alignment, SectionID,
46 SectionName, IsReadOnly);
47 M.SectionsAllocatedSinceLastLoad.insert(Addr);
48 return Addr;
49 }
50
51 void reserveAllocationSpace(uintptr_t CodeSize, uintptr_t DataSizeRO,
52 uintptr_t DataSizeRW) override {
53 return M.MM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
54 }
55
56 bool needsToReserveAllocationSpace() override {
57 return M.MM->needsToReserveAllocationSpace();
58 }
59
60 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
61 size_t Size) override {
62 return M.MM->registerEHFrames(Addr, LoadAddr, Size);
63 }
64
65 void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
66 size_t Size) override {
67 return M.MM->deregisterEHFrames(Addr, LoadAddr, Size);
68 }
69
70 uint64_t getSymbolAddress(const std::string &Name) override {
71 return M.getSymbolAddressWithoutMangling(Name);
72 }
73
74 void *getPointerToNamedFunction(const std::string &Name,
75 bool AbortOnFailure = true) override {
76 return M.MM->getPointerToNamedFunction(Name, AbortOnFailure);
77 }
78
79 void notifyObjectLoaded(ExecutionEngine *EE,
80 const object::ObjectFile &O) override {
81 return M.MM->notifyObjectLoaded(EE, O);
82 }
83
84 bool finalizeMemory(std::string *ErrMsg = nullptr) override {
85 // Each set of objects loaded will be finalized exactly once, but since
86 // symbol lookup during relocation may recursively trigger the
87 // loading/relocation of other modules, and since we're forwarding all
88 // finalizeMemory calls to a single underlying memory manager, we need to
89 // defer forwarding the call on until all necessary objects have been
90 // loaded. Otherwise, during the relocation of a leaf object, we will end
91 // up finalizing memory, causing a crash further up the stack when we
92 // attempt to apply relocations to finalized memory.
93 // To avoid finalizing too early, look at how many objects have been
94 // loaded but not yet finalized. This is a bit of a hack that relies on
95 // the fact that we're lazily emitting object files: The only way you can
96 // get more than one set of objects loaded but not yet finalized is if
97 // they were loaded during relocation of another set.
98 if (M.UnfinalizedSections.size() == 1)
99 return M.MM->finalizeMemory(ErrMsg);
100 return false;
101 }
102
103 private:
104 OrcMCJITReplacement &M;
105 };
106
107private:
108 static ExecutionEngine *
109 createOrcMCJITReplacement(std::string *ErrorMsg,
110 std::unique_ptr<RTDyldMemoryManager> OrcJMM,
111 std::unique_ptr<llvm::TargetMachine> TM) {
112 return new llvm::OrcMCJITReplacement(std::move(OrcJMM), std::move(TM));
113 }
114
115public:
116 static void Register() {
117 OrcMCJITReplacementCtor = createOrcMCJITReplacement;
118 }
119
120 OrcMCJITReplacement(std::unique_ptr<RTDyldMemoryManager> MM,
121 std::unique_ptr<TargetMachine> TM)
Eric Christopher8b770652015-01-26 19:03:15 +0000122 : TM(std::move(TM)), MM(std::move(MM)), Mang(this->TM->getDataLayout()),
Lang Hames93de2a12015-01-23 21:25:00 +0000123 NotifyObjectLoaded(*this), NotifyFinalized(*this),
Lang Hames28452d82015-01-23 22:11:07 +0000124 ObjectLayer(ObjectLayerT::CreateRTDyldMMFtor(), NotifyObjectLoaded,
125 NotifyFinalized),
Lang Hames93de2a12015-01-23 21:25:00 +0000126 CompileLayer(ObjectLayer, SimpleCompiler(*this->TM)),
127 LazyEmitLayer(CompileLayer) {
Eric Christopher8b770652015-01-26 19:03:15 +0000128 setDataLayout(this->TM->getDataLayout());
Lang Hames93de2a12015-01-23 21:25:00 +0000129 }
130
Reid Kleckner7b23b432015-01-23 22:25:47 +0000131 void addModule(std::unique_ptr<Module> M) override {
Lang Hames93de2a12015-01-23 21:25:00 +0000132
133 // If this module doesn't have a DataLayout attached then attach the
134 // default.
135 if (!M->getDataLayout())
136 M->setDataLayout(getDataLayout());
137
138 OwnedModules.push_back(std::move(M));
139 std::vector<Module *> Ms;
140 Ms.push_back(&*OwnedModules.back());
141 LazyEmitLayer.addModuleSet(std::move(Ms),
142 llvm::make_unique<ForwardingRTDyldMM>(*this));
143 }
144
145 void addObjectFile(std::unique_ptr<object::ObjectFile> O) override {
146 std::vector<std::unique_ptr<object::ObjectFile>> Objs;
147 Objs.push_back(std::move(O));
148 ObjectLayer.addObjectSet(std::move(Objs),
149 llvm::make_unique<ForwardingRTDyldMM>(*this));
150 }
151
152 void addObjectFile(object::OwningBinary<object::ObjectFile> O) override {
153 std::unique_ptr<object::ObjectFile> Obj;
154 std::unique_ptr<MemoryBuffer> Buf;
155 std::tie(Obj, Buf) = O.takeBinary();
156 std::vector<std::unique_ptr<object::ObjectFile>> Objs;
157 Objs.push_back(std::move(Obj));
158 ObjectLayer.addObjectSet(std::move(Objs),
159 llvm::make_unique<ForwardingRTDyldMM>(*this));
160 }
161
162 void addArchive(object::OwningBinary<object::Archive> A) override {
163 Archives.push_back(std::move(A));
164 }
165
166 uint64_t getSymbolAddress(StringRef Name) {
167 return getSymbolAddressWithoutMangling(Mangle(Name));
168 }
169
170 void finalizeObject() override {
171 // This is deprecated - Aim to remove in ExecutionEngine.
172 // REMOVE IF POSSIBLE - Doesn't make sense for New JIT.
173 }
174
175 void mapSectionAddress(const void *LocalAddress,
176 uint64_t TargetAddress) override {
177 for (auto &P : UnfinalizedSections)
178 if (P.second.count(LocalAddress))
179 ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress);
180 }
181
182 uint64_t getGlobalValueAddress(const std::string &Name) override {
183 return getSymbolAddress(Name);
184 }
185
186 uint64_t getFunctionAddress(const std::string &Name) override {
187 return getSymbolAddress(Name);
188 }
189
190 void *getPointerToFunction(Function *F) override {
191 uint64_t FAddr = getSymbolAddress(F->getName());
192 return reinterpret_cast<void *>(static_cast<uintptr_t>(FAddr));
193 }
194
195 void *getPointerToNamedFunction(StringRef Name,
196 bool AbortOnFailure = true) override {
197 uint64_t Addr = getSymbolAddress(Name);
198 if (!Addr && AbortOnFailure)
199 llvm_unreachable("Missing symbol!");
200 return reinterpret_cast<void *>(static_cast<uintptr_t>(Addr));
201 }
202
203 GenericValue runFunction(Function *F,
204 const std::vector<GenericValue> &ArgValues) override;
205
206 void setObjectCache(ObjectCache *NewCache) override {
207 CompileLayer.setObjectCache(NewCache);
208 }
209
210private:
211 uint64_t getSymbolAddressWithoutMangling(StringRef Name) {
212 if (uint64_t Addr = LazyEmitLayer.getSymbolAddress(Name, false))
213 return Addr;
214 if (uint64_t Addr = MM->getSymbolAddress(Name))
215 return Addr;
216 if (uint64_t Addr = scanArchives(Name))
217 return Addr;
218
219 return 0;
220 }
221
222 uint64_t scanArchives(StringRef Name) {
223 for (object::OwningBinary<object::Archive> &OB : Archives) {
224 object::Archive *A = OB.getBinary();
225 // Look for our symbols in each Archive
226 object::Archive::child_iterator ChildIt = A->findSym(Name);
227 if (ChildIt != A->child_end()) {
228 // FIXME: Support nested archives?
229 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
230 ChildIt->getAsBinary();
231 if (ChildBinOrErr.getError())
232 continue;
233 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
234 if (ChildBin->isObject()) {
235 std::vector<std::unique_ptr<object::ObjectFile>> ObjSet;
236 ObjSet.push_back(std::unique_ptr<object::ObjectFile>(
237 static_cast<object::ObjectFile *>(ChildBin.release())));
238 ObjectLayer.addObjectSet(
239 std::move(ObjSet), llvm::make_unique<ForwardingRTDyldMM>(*this));
240 if (uint64_t Addr = ObjectLayer.getSymbolAddress(Name, true))
241 return Addr;
242 }
243 }
244 }
245 return 0;
246 }
247
248 class NotifyObjectLoadedT {
249 public:
250 typedef std::vector<std::unique_ptr<object::ObjectFile>> ObjListT;
251 typedef std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>
252 LoadedObjInfoListT;
253
254 NotifyObjectLoadedT(OrcMCJITReplacement &M) : M(M) {}
255
256 void operator()(ObjectLinkingLayerBase::ObjSetHandleT H,
257 const ObjListT &Objects,
258 const LoadedObjInfoListT &Infos) const {
259 M.UnfinalizedSections[H] = std::move(M.SectionsAllocatedSinceLastLoad);
NAKAMURA Takumi2fb9a5232015-01-25 11:41:49 +0000260 M.SectionsAllocatedSinceLastLoad = SectionAddrSet();
Lang Hames93de2a12015-01-23 21:25:00 +0000261 assert(Objects.size() == Infos.size() &&
262 "Incorrect number of Infos for Objects.");
263 for (unsigned I = 0; I < Objects.size(); ++I)
264 M.MM->notifyObjectLoaded(&M, *Objects[I]);
265 };
266
267 private:
268 OrcMCJITReplacement &M;
269 };
270
271 class NotifyFinalizedT {
272 public:
273 NotifyFinalizedT(OrcMCJITReplacement &M) : M(M) {}
274 void operator()(ObjectLinkingLayerBase::ObjSetHandleT H) {
275 M.UnfinalizedSections.erase(H);
276 }
277
278 private:
279 OrcMCJITReplacement &M;
280 };
281
282 std::string Mangle(StringRef Name) {
283 std::string MangledName;
284 {
285 raw_string_ostream MangledNameStream(MangledName);
286 Mang.getNameWithPrefix(MangledNameStream, Name);
287 }
288 return MangledName;
289 }
290
291 typedef ObjectLinkingLayer<NotifyObjectLoadedT> ObjectLayerT;
292 typedef IRCompileLayer<ObjectLayerT> CompileLayerT;
293 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
294
295 std::unique_ptr<TargetMachine> TM;
296 std::unique_ptr<RTDyldMemoryManager> MM;
297 Mangler Mang;
298
299 NotifyObjectLoadedT NotifyObjectLoaded;
300 NotifyFinalizedT NotifyFinalized;
301
302 ObjectLayerT ObjectLayer;
303 CompileLayerT CompileLayer;
304 LazyEmitLayerT LazyEmitLayer;
305
306 // MCJIT keeps modules alive - we need to do the same for backwards
307 // compatibility.
308 std::vector<std::unique_ptr<Module>> OwnedModules;
309
310 // We need to store ObjLayerT::ObjSetHandles for each of the object sets
311 // that have been emitted but not yet finalized so that we can forward the
312 // mapSectionAddress calls appropriately.
313 typedef std::set<const void *> SectionAddrSet;
314 struct ObjSetHandleCompare {
315 bool operator()(ObjectLayerT::ObjSetHandleT H1,
316 ObjectLayerT::ObjSetHandleT H2) const {
317 return &*H1 < &*H2;
318 }
319 };
320 SectionAddrSet SectionsAllocatedSinceLastLoad;
321 std::map<ObjectLayerT::ObjSetHandleT, SectionAddrSet, ObjSetHandleCompare>
322 UnfinalizedSections;
323
324 std::vector<object::OwningBinary<object::Archive>> Archives;
325};
326}
327
328#endif // LLVM_LIB_EXECUTIONENGINE_ORC_MCJITREPLACEMENT_H