Taints the non-acquire RMW's store address with the load part
[oota-llvm.git] / lib / ExecutionEngine / Orc / OrcMCJITReplacement.h
1 //===---- 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
24 namespace llvm {
25 namespace orc {
26
27 class OrcMCJITReplacement : public ExecutionEngine {
28
29   // OrcMCJITReplacement needs to do a little extra book-keeping to ensure that
30   // Orc's automatic finalization doesn't kick in earlier than MCJIT clients are
31   // expecting - see finalizeMemory.
32   class MCJITReplacementMemMgr : public MCJITMemoryManager {
33   public:
34     MCJITReplacementMemMgr(OrcMCJITReplacement &M,
35                            std::shared_ptr<MCJITMemoryManager> ClientMM)
36       : M(M), ClientMM(std::move(ClientMM)) {}
37
38     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
39                                  unsigned SectionID,
40                                  StringRef SectionName) override {
41       uint8_t *Addr =
42           ClientMM->allocateCodeSection(Size, Alignment, SectionID,
43                                         SectionName);
44       M.SectionsAllocatedSinceLastLoad.insert(Addr);
45       return Addr;
46     }
47
48     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
49                                  unsigned SectionID, StringRef SectionName,
50                                  bool IsReadOnly) override {
51       uint8_t *Addr = ClientMM->allocateDataSection(Size, Alignment, SectionID,
52                                                     SectionName, IsReadOnly);
53       M.SectionsAllocatedSinceLastLoad.insert(Addr);
54       return Addr;
55     }
56
57     void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
58                                 uintptr_t RODataSize, uint32_t RODataAlign,
59                                 uintptr_t RWDataSize,
60                                 uint32_t RWDataAlign) override {
61       return ClientMM->reserveAllocationSpace(CodeSize, CodeAlign,
62                                               RODataSize, RODataAlign,
63                                               RWDataSize, RWDataAlign);
64     }
65
66     bool needsToReserveAllocationSpace() override {
67       return ClientMM->needsToReserveAllocationSpace();
68     }
69
70     void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
71                           size_t Size) override {
72       return ClientMM->registerEHFrames(Addr, LoadAddr, Size);
73     }
74
75     void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
76                             size_t Size) override {
77       return ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
78     }
79
80     void notifyObjectLoaded(RuntimeDyld &RTDyld,
81                             const object::ObjectFile &O) override {
82       return ClientMM->notifyObjectLoaded(RTDyld, O);
83     }
84
85     void notifyObjectLoaded(ExecutionEngine *EE,
86                             const object::ObjectFile &O) override {
87       return ClientMM->notifyObjectLoaded(EE, O);
88     }
89
90     bool finalizeMemory(std::string *ErrMsg = nullptr) override {
91       // Each set of objects loaded will be finalized exactly once, but since
92       // symbol lookup during relocation may recursively trigger the
93       // loading/relocation of other modules, and since we're forwarding all
94       // finalizeMemory calls to a single underlying memory manager, we need to
95       // defer forwarding the call on until all necessary objects have been
96       // loaded. Otherwise, during the relocation of a leaf object, we will end
97       // up finalizing memory, causing a crash further up the stack when we
98       // attempt to apply relocations to finalized memory.
99       // To avoid finalizing too early, look at how many objects have been
100       // loaded but not yet finalized. This is a bit of a hack that relies on
101       // the fact that we're lazily emitting object files: The only way you can
102       // get more than one set of objects loaded but not yet finalized is if
103       // they were loaded during relocation of another set.
104       if (M.UnfinalizedSections.size() == 1)
105         return ClientMM->finalizeMemory(ErrMsg);
106       return false;
107     }
108
109   private:
110     OrcMCJITReplacement &M;
111     std::shared_ptr<MCJITMemoryManager> ClientMM;
112   };
113
114   class LinkingResolver : public RuntimeDyld::SymbolResolver {
115   public:
116     LinkingResolver(OrcMCJITReplacement &M) : M(M) {}
117
118     RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) override {
119       return M.findMangledSymbol(Name);
120     }
121
122     RuntimeDyld::SymbolInfo
123     findSymbolInLogicalDylib(const std::string &Name) override {
124       return M.ClientResolver->findSymbolInLogicalDylib(Name);
125     }
126
127   private:
128     OrcMCJITReplacement &M;
129   };
130
131 private:
132
133   static ExecutionEngine *
134   createOrcMCJITReplacement(std::string *ErrorMsg,
135                             std::shared_ptr<MCJITMemoryManager> MemMgr,
136                             std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
137                             std::unique_ptr<TargetMachine> TM) {
138     return new OrcMCJITReplacement(std::move(MemMgr), std::move(Resolver),
139                                    std::move(TM));
140   }
141
142 public:
143   static void Register() {
144     OrcMCJITReplacementCtor = createOrcMCJITReplacement;
145   }
146
147   OrcMCJITReplacement(
148       std::shared_ptr<MCJITMemoryManager> MemMgr,
149       std::shared_ptr<RuntimeDyld::SymbolResolver> ClientResolver,
150       std::unique_ptr<TargetMachine> TM)
151       : ExecutionEngine(TM->createDataLayout()), TM(std::move(TM)),
152         MemMgr(*this, std::move(MemMgr)), Resolver(*this),
153         ClientResolver(std::move(ClientResolver)), NotifyObjectLoaded(*this),
154         NotifyFinalized(*this),
155         ObjectLayer(NotifyObjectLoaded, NotifyFinalized),
156         CompileLayer(ObjectLayer, SimpleCompiler(*this->TM)),
157         LazyEmitLayer(CompileLayer) {}
158
159   void addModule(std::unique_ptr<Module> M) override {
160
161     // If this module doesn't have a DataLayout attached then attach the
162     // default.
163     if (M->getDataLayout().isDefault()) {
164       M->setDataLayout(getDataLayout());
165     } else {
166       assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
167     }
168     Modules.push_back(std::move(M));
169     std::vector<Module *> Ms;
170     Ms.push_back(&*Modules.back());
171     LazyEmitLayer.addModuleSet(std::move(Ms), &MemMgr, &Resolver);
172   }
173
174   void addObjectFile(std::unique_ptr<object::ObjectFile> O) override {
175     std::vector<std::unique_ptr<object::ObjectFile>> Objs;
176     Objs.push_back(std::move(O));
177     ObjectLayer.addObjectSet(std::move(Objs), &MemMgr, &Resolver);
178   }
179
180   void addObjectFile(object::OwningBinary<object::ObjectFile> O) override {
181     std::unique_ptr<object::ObjectFile> Obj;
182     std::unique_ptr<MemoryBuffer> Buf;
183     std::tie(Obj, Buf) = O.takeBinary();
184     std::vector<std::unique_ptr<object::ObjectFile>> Objs;
185     Objs.push_back(std::move(Obj));
186     ObjectLayer.addObjectSet(std::move(Objs), &MemMgr, &Resolver);
187   }
188
189   void addArchive(object::OwningBinary<object::Archive> A) override {
190     Archives.push_back(std::move(A));
191   }
192
193   uint64_t getSymbolAddress(StringRef Name) {
194     return findSymbol(Name).getAddress();
195   }
196
197   RuntimeDyld::SymbolInfo findSymbol(StringRef Name) {
198     return findMangledSymbol(Mangle(Name));
199   }
200
201   void finalizeObject() override {
202     // This is deprecated - Aim to remove in ExecutionEngine.
203     // REMOVE IF POSSIBLE - Doesn't make sense for New JIT.
204   }
205
206   void mapSectionAddress(const void *LocalAddress,
207                          uint64_t TargetAddress) override {
208     for (auto &P : UnfinalizedSections)
209       if (P.second.count(LocalAddress))
210         ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress);
211   }
212
213   uint64_t getGlobalValueAddress(const std::string &Name) override {
214     return getSymbolAddress(Name);
215   }
216
217   uint64_t getFunctionAddress(const std::string &Name) override {
218     return getSymbolAddress(Name);
219   }
220
221   void *getPointerToFunction(Function *F) override {
222     uint64_t FAddr = getSymbolAddress(F->getName());
223     return reinterpret_cast<void *>(static_cast<uintptr_t>(FAddr));
224   }
225
226   void *getPointerToNamedFunction(StringRef Name,
227                                   bool AbortOnFailure = true) override {
228     uint64_t Addr = getSymbolAddress(Name);
229     if (!Addr && AbortOnFailure)
230       llvm_unreachable("Missing symbol!");
231     return reinterpret_cast<void *>(static_cast<uintptr_t>(Addr));
232   }
233
234   GenericValue runFunction(Function *F,
235                            ArrayRef<GenericValue> ArgValues) override;
236
237   void setObjectCache(ObjectCache *NewCache) override {
238     CompileLayer.setObjectCache(NewCache);
239   }
240
241   void setProcessAllSections(bool ProcessAllSections) override {
242     ObjectLayer.setProcessAllSections(ProcessAllSections);
243   }
244
245 private:
246
247   RuntimeDyld::SymbolInfo findMangledSymbol(StringRef Name) {
248     if (auto Sym = LazyEmitLayer.findSymbol(Name, false))
249       return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
250     if (auto Sym = ClientResolver->findSymbol(Name))
251       return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
252     if (auto Sym = scanArchives(Name))
253       return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
254
255     return nullptr;
256   }
257
258   JITSymbol scanArchives(StringRef Name) {
259     for (object::OwningBinary<object::Archive> &OB : Archives) {
260       object::Archive *A = OB.getBinary();
261       // Look for our symbols in each Archive
262       object::Archive::child_iterator ChildIt = A->findSym(Name);
263       if (std::error_code EC = ChildIt->getError())
264         report_fatal_error(EC.message());
265       if (ChildIt != A->child_end()) {
266         // FIXME: Support nested archives?
267         ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
268             (*ChildIt)->getAsBinary();
269         if (ChildBinOrErr.getError())
270           continue;
271         std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
272         if (ChildBin->isObject()) {
273           std::vector<std::unique_ptr<object::ObjectFile>> ObjSet;
274           ObjSet.push_back(std::unique_ptr<object::ObjectFile>(
275               static_cast<object::ObjectFile *>(ChildBin.release())));
276           ObjectLayer.addObjectSet(std::move(ObjSet), &MemMgr, &Resolver);
277           if (auto Sym = ObjectLayer.findSymbol(Name, true))
278             return Sym;
279         }
280       }
281     }
282     return nullptr;
283   }
284
285   class NotifyObjectLoadedT {
286   public:
287     typedef std::vector<std::unique_ptr<object::ObjectFile>> ObjListT;
288     typedef std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>
289         LoadedObjInfoListT;
290
291     NotifyObjectLoadedT(OrcMCJITReplacement &M) : M(M) {}
292
293     void operator()(ObjectLinkingLayerBase::ObjSetHandleT H,
294                     const ObjListT &Objects,
295                     const LoadedObjInfoListT &Infos) const {
296       M.UnfinalizedSections[H] = std::move(M.SectionsAllocatedSinceLastLoad);
297       M.SectionsAllocatedSinceLastLoad = SectionAddrSet();
298       assert(Objects.size() == Infos.size() &&
299              "Incorrect number of Infos for Objects.");
300       for (unsigned I = 0; I < Objects.size(); ++I)
301         M.MemMgr.notifyObjectLoaded(&M, *Objects[I]);
302     }
303
304   private:
305     OrcMCJITReplacement &M;
306   };
307
308   class NotifyFinalizedT {
309   public:
310     NotifyFinalizedT(OrcMCJITReplacement &M) : M(M) {}
311     void operator()(ObjectLinkingLayerBase::ObjSetHandleT H) {
312       M.UnfinalizedSections.erase(H);
313     }
314
315   private:
316     OrcMCJITReplacement &M;
317   };
318
319   std::string Mangle(StringRef Name) {
320     std::string MangledName;
321     {
322       raw_string_ostream MangledNameStream(MangledName);
323       Mang.getNameWithPrefix(MangledNameStream, Name, getDataLayout());
324     }
325     return MangledName;
326   }
327
328   typedef ObjectLinkingLayer<NotifyObjectLoadedT> ObjectLayerT;
329   typedef IRCompileLayer<ObjectLayerT> CompileLayerT;
330   typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
331
332   std::unique_ptr<TargetMachine> TM;
333   MCJITReplacementMemMgr MemMgr;
334   LinkingResolver Resolver;
335   std::shared_ptr<RuntimeDyld::SymbolResolver> ClientResolver;
336   Mangler Mang;
337
338   NotifyObjectLoadedT NotifyObjectLoaded;
339   NotifyFinalizedT NotifyFinalized;
340
341   ObjectLayerT ObjectLayer;
342   CompileLayerT CompileLayer;
343   LazyEmitLayerT LazyEmitLayer;
344
345   // We need to store ObjLayerT::ObjSetHandles for each of the object sets
346   // that have been emitted but not yet finalized so that we can forward the
347   // mapSectionAddress calls appropriately.
348   typedef std::set<const void *> SectionAddrSet;
349   struct ObjSetHandleCompare {
350     bool operator()(ObjectLayerT::ObjSetHandleT H1,
351                     ObjectLayerT::ObjSetHandleT H2) const {
352       return &*H1 < &*H2;
353     }
354   };
355   SectionAddrSet SectionsAllocatedSinceLastLoad;
356   std::map<ObjectLayerT::ObjSetHandleT, SectionAddrSet, ObjSetHandleCompare>
357       UnfinalizedSections;
358
359   std::vector<object::OwningBinary<object::Archive>> Archives;
360 };
361
362 } // End namespace orc.
363 } // End namespace llvm.
364
365 #endif // LLVM_LIB_EXECUTIONENGINE_ORC_MCJITREPLACEMENT_H