1 //===---- OrcMCJITReplacement.h - Orc based MCJIT replacement ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Orc based MCJIT replacement.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
15 #define LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
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"
27 class OrcMCJITReplacement : public ExecutionEngine {
29 class ForwardingRTDyldMM : public RTDyldMemoryManager {
31 ForwardingRTDyldMM(OrcMCJITReplacement &M) : M(M) {}
33 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
35 StringRef SectionName) override {
37 M.MM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
38 M.SectionsAllocatedSinceLastLoad.insert(Addr);
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);
51 void reserveAllocationSpace(uintptr_t CodeSize, uintptr_t DataSizeRO,
52 uintptr_t DataSizeRW) override {
53 return M.MM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
56 bool needsToReserveAllocationSpace() override {
57 return M.MM->needsToReserveAllocationSpace();
60 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
61 size_t Size) override {
62 return M.MM->registerEHFrames(Addr, LoadAddr, Size);
65 void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
66 size_t Size) override {
67 return M.MM->deregisterEHFrames(Addr, LoadAddr, Size);
70 uint64_t getSymbolAddress(const std::string &Name) override {
71 return M.getSymbolAddressWithoutMangling(Name);
74 void *getPointerToNamedFunction(const std::string &Name,
75 bool AbortOnFailure = true) override {
76 return M.MM->getPointerToNamedFunction(Name, AbortOnFailure);
79 void notifyObjectLoaded(ExecutionEngine *EE,
80 const object::ObjectFile &O) override {
81 return M.MM->notifyObjectLoaded(EE, O);
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);
104 OrcMCJITReplacement &M;
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));
116 static void Register() {
117 OrcMCJITReplacementCtor = createOrcMCJITReplacement;
120 OrcMCJITReplacement(std::unique_ptr<RTDyldMemoryManager> MM,
121 std::unique_ptr<TargetMachine> TM)
122 : TM(std::move(TM)), MM(std::move(MM)), Mang(this->TM->getDataLayout()),
123 NotifyObjectLoaded(*this), NotifyFinalized(*this),
124 ObjectLayer(ObjectLayerT::CreateRTDyldMMFtor(), NotifyObjectLoaded,
126 CompileLayer(ObjectLayer, SimpleCompiler(*this->TM)),
127 LazyEmitLayer(CompileLayer) {
128 setDataLayout(this->TM->getDataLayout());
131 void addModule(std::unique_ptr<Module> M) override {
133 // If this module doesn't have a DataLayout attached then attach the
135 if (!M->getDataLayout())
136 M->setDataLayout(getDataLayout());
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));
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));
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));
162 void addArchive(object::OwningBinary<object::Archive> A) override {
163 Archives.push_back(std::move(A));
166 uint64_t getSymbolAddress(StringRef Name) {
167 return getSymbolAddressWithoutMangling(Mangle(Name));
170 void finalizeObject() override {
171 // This is deprecated - Aim to remove in ExecutionEngine.
172 // REMOVE IF POSSIBLE - Doesn't make sense for New JIT.
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);
182 uint64_t getGlobalValueAddress(const std::string &Name) override {
183 return getSymbolAddress(Name);
186 uint64_t getFunctionAddress(const std::string &Name) override {
187 return getSymbolAddress(Name);
190 void *getPointerToFunction(Function *F) override {
191 uint64_t FAddr = getSymbolAddress(F->getName());
192 return reinterpret_cast<void *>(static_cast<uintptr_t>(FAddr));
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));
203 GenericValue runFunction(Function *F,
204 const std::vector<GenericValue> &ArgValues) override;
206 void setObjectCache(ObjectCache *NewCache) override {
207 CompileLayer.setObjectCache(NewCache);
211 uint64_t getSymbolAddressWithoutMangling(StringRef Name) {
212 if (uint64_t Addr = LazyEmitLayer.getSymbolAddress(Name, false))
214 if (uint64_t Addr = MM->getSymbolAddress(Name))
216 if (uint64_t Addr = scanArchives(Name))
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())
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))
248 class NotifyObjectLoadedT {
250 typedef std::vector<std::unique_ptr<object::ObjectFile>> ObjListT;
251 typedef std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>
254 NotifyObjectLoadedT(OrcMCJITReplacement &M) : M(M) {}
256 void operator()(ObjectLinkingLayerBase::ObjSetHandleT H,
257 const ObjListT &Objects,
258 const LoadedObjInfoListT &Infos) const {
259 M.UnfinalizedSections[H] = std::move(M.SectionsAllocatedSinceLastLoad);
260 M.SectionsAllocatedSinceLastLoad = SectionAddrSet();
261 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]);
268 OrcMCJITReplacement &M;
271 class NotifyFinalizedT {
273 NotifyFinalizedT(OrcMCJITReplacement &M) : M(M) {}
274 void operator()(ObjectLinkingLayerBase::ObjSetHandleT H) {
275 M.UnfinalizedSections.erase(H);
279 OrcMCJITReplacement &M;
282 std::string Mangle(StringRef Name) {
283 std::string MangledName;
285 raw_string_ostream MangledNameStream(MangledName);
286 Mang.getNameWithPrefix(MangledNameStream, Name);
291 typedef ObjectLinkingLayer<NotifyObjectLoadedT> ObjectLayerT;
292 typedef IRCompileLayer<ObjectLayerT> CompileLayerT;
293 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
295 std::unique_ptr<TargetMachine> TM;
296 std::unique_ptr<RTDyldMemoryManager> MM;
299 NotifyObjectLoadedT NotifyObjectLoaded;
300 NotifyFinalizedT NotifyFinalized;
302 ObjectLayerT ObjectLayer;
303 CompileLayerT CompileLayer;
304 LazyEmitLayerT LazyEmitLayer;
306 // MCJIT keeps modules alive - we need to do the same for backwards
308 std::vector<std::unique_ptr<Module>> OwnedModules;
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 {
320 SectionAddrSet SectionsAllocatedSinceLastLoad;
321 std::map<ObjectLayerT::ObjSetHandleT, SectionAddrSet, ObjSetHandleCompare>
324 std::vector<object::OwningBinary<object::Archive>> Archives;
328 #endif // LLVM_LIB_EXECUTIONENGINE_ORC_MCJITREPLACEMENT_H