blob: 09c1bae24e31f764983d39a1ae46cb291fc6a0bc [file] [log] [blame]
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +00001//===-- MCJIT.h - Class definition for the MCJIT ----------------*- 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#ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_H
11#define LLVM_LIB_EXECUTIONENGINE_MCJIT_H
12
Andrew Kaylorea395922013-10-01 01:47:35 +000013#include "llvm/ADT/DenseMap.h"
Andrew Kaylorc89fc822013-10-24 00:19:14 +000014#include "llvm/ADT/SmallPtrSet.h"
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +000015#include "llvm/ADT/SmallVector.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
Andrew Kaylorced4e8f2013-04-25 21:02:36 +000017#include "llvm/ExecutionEngine/ObjectCache.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000018#include "llvm/ExecutionEngine/ObjectImage.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000019#include "llvm/ExecutionEngine/RuntimeDyld.h"
Andrew Kaylorc89fc822013-10-24 00:19:14 +000020#include "llvm/IR/Module.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000021
22namespace llvm {
Andrew Kaylorea395922013-10-01 01:47:35 +000023class MCJIT;
24
25// This is a helper class that the MCJIT execution engine uses for linking
26// functions across modules that it owns. It aggregates the memory manager
27// that is passed in to the MCJIT constructor and defers most functionality
28// to that object.
29class LinkingMemoryManager : public RTDyldMemoryManager {
30public:
31 LinkingMemoryManager(MCJIT *Parent, RTDyldMemoryManager *MM)
32 : ParentEngine(Parent), ClientMM(MM) {}
33
34 virtual uint64_t getSymbolAddress(const std::string &Name);
35
36 // Functions deferred to client memory manager
37 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000038 unsigned SectionID, StringRef SectionName) {
39 return ClientMM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
Andrew Kaylorea395922013-10-01 01:47:35 +000040 }
41
42 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000043 unsigned SectionID, StringRef SectionName,
44 bool IsReadOnly) {
Andrew Kaylorea395922013-10-01 01:47:35 +000045 return ClientMM->allocateDataSection(Size, Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000046 SectionID, SectionName, IsReadOnly);
Andrew Kaylorea395922013-10-01 01:47:35 +000047 }
Lang Hames937ec542014-02-12 21:30:07 +000048
49 virtual void reserveAllocationSpace(
50 uintptr_t CodeSize, uintptr_t DataSizeRO, uintptr_t DataSizeRW) {
51 return ClientMM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
52 }
53
54 virtual bool needsToReserveAllocationSpace() {
55 return ClientMM->needsToReserveAllocationSpace();
56 }
Andrew Kaylorea395922013-10-01 01:47:35 +000057
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +000058 virtual void notifyObjectLoaded(ExecutionEngine *EE,
59 const ObjectImage *Obj) {
60 ClientMM->notifyObjectLoaded(EE, Obj);
61 }
62
Andrew Kaylor7bb13442013-10-11 21:25:48 +000063 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
64 ClientMM->registerEHFrames(Addr, LoadAddr, Size);
Andrew Kaylorea395922013-10-01 01:47:35 +000065 }
66
Andrew Kaylorc442a762013-10-16 00:14:21 +000067 virtual void deregisterEHFrames(uint8_t *Addr,
68 uint64_t LoadAddr,
69 size_t Size) {
70 ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
71 }
72
Andrew Kaylorea395922013-10-01 01:47:35 +000073 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
74 return ClientMM->finalizeMemory(ErrMsg);
75 }
76
77private:
78 MCJIT *ParentEngine;
79 OwningPtr<RTDyldMemoryManager> ClientMM;
80};
Andrew Kayloradc70562012-10-02 21:18:39 +000081
Andrew Kaylorc89fc822013-10-24 00:19:14 +000082// About Module states: added->loaded->finalized.
Yaron Kerenfb955822013-10-19 09:03:20 +000083//
84// The purpose of the "added" state is having modules in standby. (added=known
85// but not compiled). The idea is that you can add a module to provide function
86// definitions but if nothing in that module is referenced by a module in which
Yaron Keren1ec9df32013-10-24 10:04:47 +000087// a function is executed (note the wording here because it's not exactly the
Yaron Kerenfb955822013-10-19 09:03:20 +000088// ideal case) then the module never gets compiled. This is sort of lazy
89// compilation.
90//
91// The purpose of the "loaded" state (loaded=compiled and required sections
92// copied into local memory but not yet ready for execution) is to have an
93// intermediate state wherein clients can remap the addresses of sections, using
94// MCJIT::mapSectionAddress, (in preparation for later copying to a new location
95// or an external process) before relocations and page permissions are applied.
96//
97// It might not be obvious at first glance, but the "remote-mcjit" case in the
98// lli tool does this. In that case, the intermediate action is taken by the
99// RemoteMemoryManager in response to the notifyObjectLoaded function being
100// called.
101
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000102class MCJIT : public ExecutionEngine {
Jim Grosbachbea67532012-08-21 15:42:49 +0000103 MCJIT(Module *M, TargetMachine *tm, RTDyldMemoryManager *MemMgr,
104 bool AllocateGVsWithCode);
Jim Grosbach7b162492011-03-18 22:48:41 +0000105
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000106 typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
Andrew Kaylorea395922013-10-01 01:47:35 +0000107
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000108 class OwningModuleContainer {
Andrew Kaylorea395922013-10-01 01:47:35 +0000109 public:
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000110 OwningModuleContainer() {
111 }
112 ~OwningModuleContainer() {
113 freeModulePtrSet(AddedModules);
114 freeModulePtrSet(LoadedModules);
115 freeModulePtrSet(FinalizedModules);
116 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000117
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000118 ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
119 ModulePtrSet::iterator end_added() { return AddedModules.end(); }
120
121 ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
122 ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
123
124 ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
125 ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
126
127 void addModule(Module *M) {
128 AddedModules.insert(M);
129 }
130
131 bool removeModule(Module *M) {
132 return AddedModules.erase(M) || LoadedModules.erase(M) ||
133 FinalizedModules.erase(M);
134 }
135
136 bool hasModuleBeenAddedButNotLoaded(Module *M) {
137 return AddedModules.count(M) != 0;
138 }
139
140 bool hasModuleBeenLoaded(Module *M) {
141 // If the module is in either the "loaded" or "finalized" sections it
142 // has been loaded.
143 return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
144 }
145
146 bool hasModuleBeenFinalized(Module *M) {
147 return FinalizedModules.count(M) != 0;
148 }
149
150 bool ownsModule(Module* M) {
151 return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
152 (FinalizedModules.count(M) != 0);
153 }
154
155 void markModuleAsLoaded(Module *M) {
156 // This checks against logic errors in the MCJIT implementation.
157 // This function should never be called with either a Module that MCJIT
158 // does not own or a Module that has already been loaded and/or finalized.
159 assert(AddedModules.count(M) &&
160 "markModuleAsLoaded: Module not found in AddedModules");
161
162 // Remove the module from the "Added" set.
163 AddedModules.erase(M);
164
165 // Add the Module to the "Loaded" set.
166 LoadedModules.insert(M);
167 }
168
169 void markModuleAsFinalized(Module *M) {
170 // This checks against logic errors in the MCJIT implementation.
171 // This function should never be called with either a Module that MCJIT
172 // does not own, a Module that has not been loaded or a Module that has
173 // already been finalized.
174 assert(LoadedModules.count(M) &&
175 "markModuleAsFinalized: Module not found in LoadedModules");
176
177 // Remove the module from the "Loaded" section of the list.
178 LoadedModules.erase(M);
179
180 // Add the Module to the "Finalized" section of the list by inserting it
181 // before the 'end' iterator.
182 FinalizedModules.insert(M);
183 }
184
185 void markAllLoadedModulesAsFinalized() {
186 for (ModulePtrSet::iterator I = LoadedModules.begin(),
187 E = LoadedModules.end();
188 I != E; ++I) {
189 Module *M = *I;
190 FinalizedModules.insert(M);
191 }
192 LoadedModules.clear();
193 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000194
195 private:
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000196 ModulePtrSet AddedModules;
197 ModulePtrSet LoadedModules;
198 ModulePtrSet FinalizedModules;
199
200 void freeModulePtrSet(ModulePtrSet& MPS) {
201 // Go through the module set and delete everything.
202 for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
203 Module *M = *I;
204 delete M;
205 }
206 MPS.clear();
207 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000208 };
209
Jim Grosbach7b162492011-03-18 22:48:41 +0000210 TargetMachine *TM;
211 MCContext *Ctx;
Andrew Kaylorea395922013-10-01 01:47:35 +0000212 LinkingMemoryManager MemMgr;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000213 RuntimeDyld Dyld;
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000214 SmallVector<JITEventListener*, 2> EventListeners;
Jim Grosbach7b162492011-03-18 22:48:41 +0000215
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000216 OwningModuleContainer OwnedModules;
Andrew Kaylorea395922013-10-01 01:47:35 +0000217
Lang Hames173c69f2014-01-08 04:09:09 +0000218 SmallVector<object::Archive*, 2> Archives;
219
220 typedef SmallVector<ObjectImage *, 2> LoadedObjectList;
221 LoadedObjectList LoadedObjects;
Jim Grosbach7b162492011-03-18 22:48:41 +0000222
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000223 // An optional ObjectCache to be notified of compiled objects and used to
224 // perform lookup of pre-compiled code to avoid re-compilation.
225 ObjectCache *ObjCache;
226
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000227 Function *FindFunctionNamedInModulePtrSet(const char *FnName,
228 ModulePtrSet::iterator I,
229 ModulePtrSet::iterator E);
230
231 void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
232 ModulePtrSet::iterator I,
233 ModulePtrSet::iterator E);
234
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000235public:
236 ~MCJIT();
237
238 /// @name ExecutionEngine interface implementation
239 /// @{
Andrew Kaylorea395922013-10-01 01:47:35 +0000240 virtual void addModule(Module *M);
Lang Hames173c69f2014-01-08 04:09:09 +0000241 virtual void addObjectFile(object::ObjectFile *O);
242 virtual void addArchive(object::Archive *O);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000243 virtual bool removeModule(Module *M);
244
245 /// FindFunctionNamed - Search all of the active modules to find the one that
246 /// defines FnName. This is very slow operation and shouldn't be used for
247 /// general code.
248 virtual Function *FindFunctionNamed(const char *FnName);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000249
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000250 /// Sets the object manager that MCJIT should use to avoid compilation.
251 virtual void setObjectCache(ObjectCache *manager);
252
Andrew Kaylorea395922013-10-01 01:47:35 +0000253 virtual void generateCodeForModule(Module *M);
254
David Tweed2e7efed2013-05-17 10:01:46 +0000255 /// finalizeObject - ensure the module is fully processed and is usable.
256 ///
257 /// It is the user-level function for completing the process of making the
258 /// object usable for execution. It should be called after sections within an
259 /// object have been relocated using mapSectionAddress. When this method is
260 /// called the MCJIT execution engine will reapply relocations for a loaded
261 /// object.
Yaron Kerenfb955822013-10-19 09:03:20 +0000262 /// Is it OK to finalize a set of modules, add modules and finalize again.
Andrew Kaylor2fb40ce2013-10-21 23:27:02 +0000263 // FIXME: Do we really need both of these?
Andrew Kaylora714efc2012-11-05 20:57:16 +0000264 virtual void finalizeObject();
Andrew Kaylorea395922013-10-01 01:47:35 +0000265 virtual void finalizeModule(Module *);
266 void finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000267
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000268 /// runStaticConstructorsDestructors - This method is used to execute all of
269 /// the static constructors or destructors for a program.
270 ///
271 /// \param isDtors - Run the destructors instead of constructors.
272 void runStaticConstructorsDestructors(bool isDtors);
273
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000274 virtual void *getPointerToBasicBlock(BasicBlock *BB);
275
276 virtual void *getPointerToFunction(Function *F);
277
278 virtual void *recompileAndRelinkFunction(Function *F);
279
280 virtual void freeMachineCodeForFunction(Function *F);
281
282 virtual GenericValue runFunction(Function *F,
283 const std::vector<GenericValue> &ArgValues);
284
Jim Grosbachd5274402011-03-22 18:05:27 +0000285 /// getPointerToNamedFunction - This method returns the address of the
286 /// specified function by using the dlsym function call. As such it is only
287 /// useful for resolving library symbols, not code generated symbols.
288 ///
289 /// If AbortOnFailure is false and no function with the given name is
290 /// found, this function silently returns a null pointer. Otherwise,
291 /// it prints a message to stderr and aborts.
292 ///
Danil Malyshev7e325782012-01-05 21:16:14 +0000293 virtual void *getPointerToNamedFunction(const std::string &Name,
294 bool AbortOnFailure = true);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000295
Jim Grosbach0ddb3a42012-01-16 23:50:55 +0000296 /// mapSectionAddress - map a section to its target address space value.
297 /// Map the address of a JIT section as returned from the memory manager
298 /// to the address in the target process as the running code will see it.
299 /// This is the address which will be used for relocation resolution.
Jim Grosbach6d613972012-09-13 21:50:06 +0000300 virtual void mapSectionAddress(const void *LocalAddress,
301 uint64_t TargetAddress) {
Jim Grosbach0ddb3a42012-01-16 23:50:55 +0000302 Dyld.mapSectionAddress(LocalAddress, TargetAddress);
303 }
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000304 virtual void RegisterJITEventListener(JITEventListener *L);
305 virtual void UnregisterJITEventListener(JITEventListener *L);
306
Andrew Kaylorea395922013-10-01 01:47:35 +0000307 // If successful, these function will implicitly finalize all loaded objects.
308 // To get a function address within MCJIT without causing a finalize, use
309 // getSymbolAddress.
310 virtual uint64_t getGlobalValueAddress(const std::string &Name);
311 virtual uint64_t getFunctionAddress(const std::string &Name);
312
Juergen Ributzka5fe955c2014-01-23 19:23:28 +0000313 virtual TargetMachine *getTargetMachine() { return TM; }
314
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000315 /// @}
316 /// @name (Private) Registration Interfaces
317 /// @{
318
319 static void Register() {
320 MCJITCtor = createJIT;
321 }
322
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000323 static ExecutionEngine *createJIT(Module *M,
324 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000325 RTDyldMemoryManager *MemMgr,
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000326 bool GVsWithCode,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +0000327 TargetMachine *TM);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000328
329 // @}
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000330
Andrew Kaylorea395922013-10-01 01:47:35 +0000331 // This is not directly exposed via the ExecutionEngine API, but it is
332 // used by the LinkingMemoryManager.
333 uint64_t getSymbolAddress(const std::string &Name,
334 bool CheckFunctionsOnly);
335
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000336protected:
337 /// emitObject -- Generate a JITed object in memory from the specified module
338 /// Currently, MCJIT only supports a single module and the module passed to
339 /// this function call is expected to be the contained module. The module
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000340 /// is passed as a parameter here to prepare for multiple module support in
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000341 /// the future.
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000342 ObjectBufferStream* emitObject(Module *M);
343
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000344 void NotifyObjectEmitted(const ObjectImage& Obj);
345 void NotifyFreeingObject(const ObjectImage& Obj);
Andrew Kaylorea395922013-10-01 01:47:35 +0000346
347 uint64_t getExistingSymbolAddress(const std::string &Name);
348 Module *findModuleForSymbol(const std::string &Name,
349 bool CheckFunctionsOnly);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000350};
351
352} // End llvm namespace
353
354#endif