1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
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 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "JIT.h"
17 #include "JITDwarfEmitter.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineCodeInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRelocation.h"
30 #include "llvm/ExecutionEngine/GenericValue.h"
31 #include "llvm/ExecutionEngine/JITEventListener.h"
32 #include "llvm/ExecutionEngine/JITMemoryManager.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetJITInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MutexGuard.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Disassembler.h"
45 #include "llvm/Support/Memory.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/ValueMap.h"
51 #include <algorithm>
52 #ifndef NDEBUG
53 #include <iomanip>
54 #endif
55 using namespace llvm;
56
57 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
58 STATISTIC(NumRelos, "Number of relocations applied");
59 STATISTIC(NumRetries, "Number of retries with more memory");
60
61
62 // A declaration may stop being a declaration once it's fully read from bitcode.
63 // This function returns true if F is fully read and is still a declaration.
isNonGhostDeclaration(const Function * F)64 static bool isNonGhostDeclaration(const Function *F) {
65 return F->isDeclaration() && !F->isMaterializable();
66 }
67
68 //===----------------------------------------------------------------------===//
69 // JIT lazy compilation code.
70 //
71 namespace {
72 class JITEmitter;
73 class JITResolverState;
74
75 template<typename ValueTy>
76 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
77 typedef JITResolverState *ExtraData;
onRAUW__anonc80982e60111::NoRAUWValueMapConfig78 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
79 llvm_unreachable("The JIT doesn't know how to handle a"
80 " RAUW on a value it has emitted.");
81 }
82 };
83
84 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
85 typedef JITResolverState *ExtraData;
86 static void onDelete(JITResolverState *JRS, Function *F);
87 };
88
89 class JITResolverState {
90 public:
91 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
92 FunctionToLazyStubMapTy;
93 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
94 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
95 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
96 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
97 private:
98 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
99 /// particular function so that we can reuse them if necessary.
100 FunctionToLazyStubMapTy FunctionToLazyStubMap;
101
102 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
103 /// site corresponds to, and vice versa.
104 CallSiteToFunctionMapTy CallSiteToFunctionMap;
105 FunctionToCallSitesMapTy FunctionToCallSitesMap;
106
107 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
108 /// particular GlobalVariable so that we can reuse them if necessary.
109 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
110
111 /// Instance of the JIT this ResolverState serves.
112 JIT *TheJIT;
113
114 public:
JITResolverState(JIT * jit)115 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
116 FunctionToCallSitesMap(this),
117 TheJIT(jit) {}
118
getFunctionToLazyStubMap(const MutexGuard & locked)119 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
120 const MutexGuard& locked) {
121 assert(locked.holds(TheJIT->lock));
122 return FunctionToLazyStubMap;
123 }
124
getGlobalToIndirectSymMap(const MutexGuard & lck)125 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
126 assert(lck.holds(TheJIT->lock));
127 return GlobalToIndirectSymMap;
128 }
129
LookupFunctionFromCallSite(const MutexGuard & locked,void * CallSite) const130 std::pair<void *, Function *> LookupFunctionFromCallSite(
131 const MutexGuard &locked, void *CallSite) const {
132 assert(locked.holds(TheJIT->lock));
133
134 // The address given to us for the stub may not be exactly right, it
135 // might be a little bit after the stub. As such, use upper_bound to
136 // find it.
137 CallSiteToFunctionMapTy::const_iterator I =
138 CallSiteToFunctionMap.upper_bound(CallSite);
139 assert(I != CallSiteToFunctionMap.begin() &&
140 "This is not a known call site!");
141 --I;
142 return *I;
143 }
144
AddCallSite(const MutexGuard & locked,void * CallSite,Function * F)145 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
146 assert(locked.holds(TheJIT->lock));
147
148 bool Inserted = CallSiteToFunctionMap.insert(
149 std::make_pair(CallSite, F)).second;
150 (void)Inserted;
151 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
152 FunctionToCallSitesMap[F].insert(CallSite);
153 }
154
155 void EraseAllCallSitesForPrelocked(Function *F);
156
157 // Erases _all_ call sites regardless of their function. This is used to
158 // unregister the stub addresses from the StubToResolverMap in
159 // ~JITResolver().
160 void EraseAllCallSitesPrelocked();
161 };
162
163 /// JITResolver - Keep track of, and resolve, call sites for functions that
164 /// have not yet been compiled.
165 class JITResolver {
166 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
167 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
168 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
169
170 /// LazyResolverFn - The target lazy resolver function that we actually
171 /// rewrite instructions to use.
172 TargetJITInfo::LazyResolverFn LazyResolverFn;
173
174 JITResolverState state;
175
176 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
177 /// for external functions. TODO: Of course, external functions don't need
178 /// a lazy stub. It's actually here to make it more likely that far calls
179 /// succeed, but no single stub can guarantee that. I'll remove this in a
180 /// subsequent checkin when I actually fix far calls.
181 std::map<void*, void*> ExternalFnToStubMap;
182
183 /// revGOTMap - map addresses to indexes in the GOT
184 std::map<void*, unsigned> revGOTMap;
185 unsigned nextGOTIndex;
186
187 JITEmitter &JE;
188
189 /// Instance of JIT corresponding to this Resolver.
190 JIT *TheJIT;
191
192 public:
JITResolver(JIT & jit,JITEmitter & je)193 explicit JITResolver(JIT &jit, JITEmitter &je)
194 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
195 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
196 }
197
198 ~JITResolver();
199
200 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
201 /// lazy-compilation stub if it has already been created.
202 void *getLazyFunctionStubIfAvailable(Function *F);
203
204 /// getLazyFunctionStub - This returns a pointer to a function's
205 /// lazy-compilation stub, creating one on demand as needed.
206 void *getLazyFunctionStub(Function *F);
207
208 /// getExternalFunctionStub - Return a stub for the function at the
209 /// specified address, created lazily on demand.
210 void *getExternalFunctionStub(void *FnAddr);
211
212 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
213 /// specified GV address.
214 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
215
216 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
217 /// an address. This function only manages slots, it does not manage the
218 /// contents of the slots or the memory associated with the GOT.
219 unsigned getGOTIndexForAddr(void *addr);
220
221 /// JITCompilerFn - This function is called to resolve a stub to a compiled
222 /// address. If the LLVM Function corresponding to the stub has not yet
223 /// been compiled, this function compiles it first.
224 static void *JITCompilerFn(void *Stub);
225 };
226
227 class StubToResolverMapTy {
228 /// Map a stub address to a specific instance of a JITResolver so that
229 /// lazily-compiled functions can find the right resolver to use.
230 ///
231 /// Guarded by Lock.
232 std::map<void*, JITResolver*> Map;
233
234 /// Guards Map from concurrent accesses.
235 mutable sys::Mutex Lock;
236
237 public:
238 /// Registers a Stub to be resolved by Resolver.
RegisterStubResolver(void * Stub,JITResolver * Resolver)239 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
240 MutexGuard guard(Lock);
241 Map.insert(std::make_pair(Stub, Resolver));
242 }
243 /// Unregisters the Stub when it's invalidated.
UnregisterStubResolver(void * Stub)244 void UnregisterStubResolver(void *Stub) {
245 MutexGuard guard(Lock);
246 Map.erase(Stub);
247 }
248 /// Returns the JITResolver instance that owns the Stub.
getResolverFromStub(void * Stub) const249 JITResolver *getResolverFromStub(void *Stub) const {
250 MutexGuard guard(Lock);
251 // The address given to us for the stub may not be exactly right, it might
252 // be a little bit after the stub. As such, use upper_bound to find it.
253 // This is the same trick as in LookupFunctionFromCallSite from
254 // JITResolverState.
255 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
256 assert(I != Map.begin() && "This is not a known stub!");
257 --I;
258 return I->second;
259 }
260 /// True if any stubs refer to the given resolver. Only used in an assert().
261 /// O(N)
ResolverHasStubs(JITResolver * Resolver) const262 bool ResolverHasStubs(JITResolver* Resolver) const {
263 MutexGuard guard(Lock);
264 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
265 E = Map.end(); I != E; ++I) {
266 if (I->second == Resolver)
267 return true;
268 }
269 return false;
270 }
271 };
272 /// This needs to be static so that a lazy call stub can access it with no
273 /// context except the address of the stub.
274 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
275
276 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
277 /// used to output functions to memory for execution.
278 class JITEmitter : public JITCodeEmitter {
279 JITMemoryManager *MemMgr;
280
281 // When outputting a function stub in the context of some other function, we
282 // save BufferBegin/BufferEnd/CurBufferPtr here.
283 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
284
285 // When reattempting to JIT a function after running out of space, we store
286 // the estimated size of the function we're trying to JIT here, so we can
287 // ask the memory manager for at least this much space. When we
288 // successfully emit the function, we reset this back to zero.
289 uintptr_t SizeEstimate;
290
291 /// Relocations - These are the relocations that the function needs, as
292 /// emitted.
293 std::vector<MachineRelocation> Relocations;
294
295 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
296 /// It is filled in by the StartMachineBasicBlock callback and queried by
297 /// the getMachineBasicBlockAddress callback.
298 std::vector<uintptr_t> MBBLocations;
299
300 /// ConstantPool - The constant pool for the current function.
301 ///
302 MachineConstantPool *ConstantPool;
303
304 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
305 ///
306 void *ConstantPoolBase;
307
308 /// ConstPoolAddresses - Addresses of individual constant pool entries.
309 ///
310 SmallVector<uintptr_t, 8> ConstPoolAddresses;
311
312 /// JumpTable - The jump tables for the current function.
313 ///
314 MachineJumpTableInfo *JumpTable;
315
316 /// JumpTableBase - A pointer to the first entry in the jump table.
317 ///
318 void *JumpTableBase;
319
320 /// Resolver - This contains info about the currently resolved functions.
321 JITResolver Resolver;
322
323 /// DE - The dwarf emitter for the jit.
324 OwningPtr<JITDwarfEmitter> DE;
325
326 /// LabelLocations - This vector is a mapping from Label ID's to their
327 /// address.
328 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
329
330 /// MMI - Machine module info for exception informations
331 MachineModuleInfo* MMI;
332
333 // CurFn - The llvm function being emitted. Only valid during
334 // finishFunction().
335 const Function *CurFn;
336
337 /// Information about emitted code, which is passed to the
338 /// JITEventListeners. This is reset in startFunction and used in
339 /// finishFunction.
340 JITEvent_EmittedFunctionDetails EmissionDetails;
341
342 struct EmittedCode {
343 void *FunctionBody; // Beginning of the function's allocation.
344 void *Code; // The address the function's code actually starts at.
345 void *ExceptionTable;
EmittedCode__anonc80982e60111::JITEmitter::EmittedCode346 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
347 };
348 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
349 typedef JITEmitter *ExtraData;
350 static void onDelete(JITEmitter *, const Function*);
351 static void onRAUW(JITEmitter *, const Function*, const Function*);
352 };
353 ValueMap<const Function *, EmittedCode,
354 EmittedFunctionConfig> EmittedFunctions;
355
356 DebugLoc PrevDL;
357
358 /// Instance of the JIT
359 JIT *TheJIT;
360
361 bool JITExceptionHandling;
362
363 public:
JITEmitter(JIT & jit,JITMemoryManager * JMM,TargetMachine & TM)364 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
365 : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
366 EmittedFunctions(this), TheJIT(&jit),
367 JITExceptionHandling(TM.Options.JITExceptionHandling) {
368 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
369 if (jit.getJITInfo().needsGOT()) {
370 MemMgr->AllocateGOT();
371 DEBUG(dbgs() << "JIT is managing a GOT\n");
372 }
373
374 if (JITExceptionHandling) {
375 DE.reset(new JITDwarfEmitter(jit));
376 }
377 }
~JITEmitter()378 ~JITEmitter() {
379 delete MemMgr;
380 }
381
382 /// classof - Methods for support type inquiry through isa, cast, and
383 /// dyn_cast:
384 ///
classof(const MachineCodeEmitter *)385 static inline bool classof(const MachineCodeEmitter*) { return true; }
386
getJITResolver()387 JITResolver &getJITResolver() { return Resolver; }
388
389 virtual void startFunction(MachineFunction &F);
390 virtual bool finishFunction(MachineFunction &F);
391
392 void emitConstantPool(MachineConstantPool *MCP);
393 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
394 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
395
396 void startGVStub(const GlobalValue* GV,
397 unsigned StubSize, unsigned Alignment = 1);
398 void startGVStub(void *Buffer, unsigned StubSize);
399 void finishGVStub();
400 virtual void *allocIndirectGV(const GlobalValue *GV,
401 const uint8_t *Buffer, size_t Size,
402 unsigned Alignment);
403
404 /// allocateSpace - Reserves space in the current block if any, or
405 /// allocate a new one of the given size.
406 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
407
408 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
409 /// this method does not allocate memory in the current output buffer,
410 /// because a global may live longer than the current function.
411 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
412
addRelocation(const MachineRelocation & MR)413 virtual void addRelocation(const MachineRelocation &MR) {
414 Relocations.push_back(MR);
415 }
416
StartMachineBasicBlock(MachineBasicBlock * MBB)417 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
418 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
419 MBBLocations.resize((MBB->getNumber()+1)*2);
420 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
421 if (MBB->hasAddressTaken())
422 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
423 (void*)getCurrentPCValue());
424 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
425 << (void*) getCurrentPCValue() << "]\n");
426 }
427
428 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
429 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
430
getMachineBasicBlockAddress(MachineBasicBlock * MBB) const431 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const{
432 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
433 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
434 return MBBLocations[MBB->getNumber()];
435 }
436
437 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
438 /// given function. Increase the minimum allocation size so that we get
439 /// more memory next time.
440 void retryWithMoreMemory(MachineFunction &F);
441
442 /// deallocateMemForFunction - Deallocate all memory for the specified
443 /// function body.
444 void deallocateMemForFunction(const Function *F);
445
446 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
447
emitLabel(MCSymbol * Label)448 virtual void emitLabel(MCSymbol *Label) {
449 LabelLocations[Label] = getCurrentPCValue();
450 }
451
getLabelLocations()452 virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() {
453 return &LabelLocations;
454 }
455
getLabelAddress(MCSymbol * Label) const456 virtual uintptr_t getLabelAddress(MCSymbol *Label) const {
457 assert(LabelLocations.count(Label) && "Label not emitted!");
458 return LabelLocations.find(Label)->second;
459 }
460
setModuleInfo(MachineModuleInfo * Info)461 virtual void setModuleInfo(MachineModuleInfo* Info) {
462 MMI = Info;
463 if (DE.get()) DE->setModuleInfo(Info);
464 }
465
466 private:
467 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
468 bool MayNeedFarStub);
469 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
470 };
471 }
472
onDelete(JITResolverState * JRS,Function * F)473 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
474 JRS->EraseAllCallSitesForPrelocked(F);
475 }
476
EraseAllCallSitesForPrelocked(Function * F)477 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
478 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
479 if (F2C == FunctionToCallSitesMap.end())
480 return;
481 StubToResolverMapTy &S2RMap = *StubToResolverMap;
482 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
483 E = F2C->second.end(); I != E; ++I) {
484 S2RMap.UnregisterStubResolver(*I);
485 bool Erased = CallSiteToFunctionMap.erase(*I);
486 (void)Erased;
487 assert(Erased && "Missing call site->function mapping");
488 }
489 FunctionToCallSitesMap.erase(F2C);
490 }
491
EraseAllCallSitesPrelocked()492 void JITResolverState::EraseAllCallSitesPrelocked() {
493 StubToResolverMapTy &S2RMap = *StubToResolverMap;
494 for (CallSiteToFunctionMapTy::const_iterator
495 I = CallSiteToFunctionMap.begin(),
496 E = CallSiteToFunctionMap.end(); I != E; ++I) {
497 S2RMap.UnregisterStubResolver(I->first);
498 }
499 CallSiteToFunctionMap.clear();
500 FunctionToCallSitesMap.clear();
501 }
502
~JITResolver()503 JITResolver::~JITResolver() {
504 // No need to lock because we're in the destructor, and state isn't shared.
505 state.EraseAllCallSitesPrelocked();
506 assert(!StubToResolverMap->ResolverHasStubs(this) &&
507 "Resolver destroyed with stubs still alive.");
508 }
509
510 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
511 /// if it has already been created.
getLazyFunctionStubIfAvailable(Function * F)512 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
513 MutexGuard locked(TheJIT->lock);
514
515 // If we already have a stub for this function, recycle it.
516 return state.getFunctionToLazyStubMap(locked).lookup(F);
517 }
518
519 /// getFunctionStub - This returns a pointer to a function stub, creating
520 /// one on demand as needed.
getLazyFunctionStub(Function * F)521 void *JITResolver::getLazyFunctionStub(Function *F) {
522 MutexGuard locked(TheJIT->lock);
523
524 // If we already have a lazy stub for this function, recycle it.
525 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
526 if (Stub) return Stub;
527
528 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
529 // must resolve the symbol now.
530 void *Actual = TheJIT->isCompilingLazily()
531 ? (void *)(intptr_t)LazyResolverFn : (void *)0;
532
533 // If this is an external declaration, attempt to resolve the address now
534 // to place in the stub.
535 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
536 Actual = TheJIT->getPointerToFunction(F);
537
538 // If we resolved the symbol to a null address (eg. a weak external)
539 // don't emit a stub. Return a null pointer to the application.
540 if (!Actual) return 0;
541 }
542
543 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
544 JE.startGVStub(F, SL.Size, SL.Alignment);
545 // Codegen a new stub, calling the lazy resolver or the actual address of the
546 // external function, if it was resolved.
547 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
548 JE.finishGVStub();
549
550 if (Actual != (void*)(intptr_t)LazyResolverFn) {
551 // If we are getting the stub for an external function, we really want the
552 // address of the stub in the GlobalAddressMap for the JIT, not the address
553 // of the external function.
554 TheJIT->updateGlobalMapping(F, Stub);
555 }
556
557 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
558 << F->getName() << "'\n");
559
560 if (TheJIT->isCompilingLazily()) {
561 // Register this JITResolver as the one corresponding to this call site so
562 // JITCompilerFn will be able to find it.
563 StubToResolverMap->RegisterStubResolver(Stub, this);
564
565 // Finally, keep track of the stub-to-Function mapping so that the
566 // JITCompilerFn knows which function to compile!
567 state.AddCallSite(locked, Stub, F);
568 } else if (!Actual) {
569 // If we are JIT'ing non-lazily but need to call a function that does not
570 // exist yet, add it to the JIT's work list so that we can fill in the
571 // stub address later.
572 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
573 "'Actual' should have been set above.");
574 TheJIT->addPendingFunction(F);
575 }
576
577 return Stub;
578 }
579
580 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
581 /// GV address.
getGlobalValueIndirectSym(GlobalValue * GV,void * GVAddress)582 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
583 MutexGuard locked(TheJIT->lock);
584
585 // If we already have a stub for this global variable, recycle it.
586 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
587 if (IndirectSym) return IndirectSym;
588
589 // Otherwise, codegen a new indirect symbol.
590 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
591 JE);
592
593 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
594 << "] for GV '" << GV->getName() << "'\n");
595
596 return IndirectSym;
597 }
598
599 /// getExternalFunctionStub - Return a stub for the function at the
600 /// specified address, created lazily on demand.
getExternalFunctionStub(void * FnAddr)601 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
602 // If we already have a stub for this function, recycle it.
603 void *&Stub = ExternalFnToStubMap[FnAddr];
604 if (Stub) return Stub;
605
606 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
607 JE.startGVStub(0, SL.Size, SL.Alignment);
608 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
609 JE.finishGVStub();
610
611 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
612 << "] for external function at '" << FnAddr << "'\n");
613 return Stub;
614 }
615
getGOTIndexForAddr(void * addr)616 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
617 unsigned idx = revGOTMap[addr];
618 if (!idx) {
619 idx = ++nextGOTIndex;
620 revGOTMap[addr] = idx;
621 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
622 << addr << "]\n");
623 }
624 return idx;
625 }
626
627 /// JITCompilerFn - This function is called when a lazy compilation stub has
628 /// been entered. It looks up which function this stub corresponds to, compiles
629 /// it if necessary, then returns the resultant function pointer.
JITCompilerFn(void * Stub)630 void *JITResolver::JITCompilerFn(void *Stub) {
631 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
632 assert(JR && "Unable to find the corresponding JITResolver to the call site");
633
634 Function* F = 0;
635 void* ActualPtr = 0;
636
637 {
638 // Only lock for getting the Function. The call getPointerToFunction made
639 // in this function might trigger function materializing, which requires
640 // JIT lock to be unlocked.
641 MutexGuard locked(JR->TheJIT->lock);
642
643 // The address given to us for the stub may not be exactly right, it might
644 // be a little bit after the stub. As such, use upper_bound to find it.
645 std::pair<void*, Function*> I =
646 JR->state.LookupFunctionFromCallSite(locked, Stub);
647 F = I.second;
648 ActualPtr = I.first;
649 }
650
651 // If we have already code generated the function, just return the address.
652 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
653
654 if (!Result) {
655 // Otherwise we don't have it, do lazy compilation now.
656
657 // If lazy compilation is disabled, emit a useful error message and abort.
658 if (!JR->TheJIT->isCompilingLazily()) {
659 report_fatal_error("LLVM JIT requested to do lazy compilation of"
660 " function '"
661 + F->getName() + "' when lazy compiles are disabled!");
662 }
663
664 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
665 << "' In stub ptr = " << Stub << " actual ptr = "
666 << ActualPtr << "\n");
667 (void)ActualPtr;
668
669 Result = JR->TheJIT->getPointerToFunction(F);
670 }
671
672 // Reacquire the lock to update the GOT map.
673 MutexGuard locked(JR->TheJIT->lock);
674
675 // We might like to remove the call site from the CallSiteToFunction map, but
676 // we can't do that! Multiple threads could be stuck, waiting to acquire the
677 // lock above. As soon as the 1st function finishes compiling the function,
678 // the next one will be released, and needs to be able to find the function it
679 // needs to call.
680
681 // FIXME: We could rewrite all references to this stub if we knew them.
682
683 // What we will do is set the compiled function address to map to the
684 // same GOT entry as the stub so that later clients may update the GOT
685 // if they see it still using the stub address.
686 // Note: this is done so the Resolver doesn't have to manage GOT memory
687 // Do this without allocating map space if the target isn't using a GOT
688 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
689 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
690
691 return Result;
692 }
693
694 //===----------------------------------------------------------------------===//
695 // JITEmitter code.
696 //
getPointerToGlobal(GlobalValue * V,void * Reference,bool MayNeedFarStub)697 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
698 bool MayNeedFarStub) {
699 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
700 return TheJIT->getOrEmitGlobalVariable(GV);
701
702 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
703 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
704
705 // If we have already compiled the function, return a pointer to its body.
706 Function *F = cast<Function>(V);
707
708 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
709 if (FnStub) {
710 // Return the function stub if it's already created. We do this first so
711 // that we're returning the same address for the function as any previous
712 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
713 // close enough to call.
714 return FnStub;
715 }
716
717 // If we know the target can handle arbitrary-distance calls, try to
718 // return a direct pointer.
719 if (!MayNeedFarStub) {
720 // If we have code, go ahead and return that.
721 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
722 if (ResultPtr) return ResultPtr;
723
724 // If this is an external function pointer, we can force the JIT to
725 // 'compile' it, which really just adds it to the map.
726 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
727 return TheJIT->getPointerToFunction(F);
728 }
729
730 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
731 // so. Note that it's possible to return null from getLazyFunctionStub in the
732 // case of a weak extern that fails to resolve.
733 return Resolver.getLazyFunctionStub(F);
734 }
735
getPointerToGVIndirectSym(GlobalValue * V,void * Reference)736 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
737 // Make sure GV is emitted first, and create a stub containing the fully
738 // resolved address.
739 void *GVAddress = getPointerToGlobal(V, Reference, false);
740 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
741 return StubAddr;
742 }
743
processDebugLoc(DebugLoc DL,bool BeforePrintingInsn)744 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
745 if (DL.isUnknown()) return;
746 if (!BeforePrintingInsn) return;
747
748 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
749
750 if (DL.getScope(Context) != 0 && PrevDL != DL) {
751 JITEvent_EmittedFunctionDetails::LineStart NextLine;
752 NextLine.Address = getCurrentPCValue();
753 NextLine.Loc = DL;
754 EmissionDetails.LineStarts.push_back(NextLine);
755 }
756
757 PrevDL = DL;
758 }
759
GetConstantPoolSizeInBytes(MachineConstantPool * MCP,const TargetData * TD)760 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
761 const TargetData *TD) {
762 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
763 if (Constants.empty()) return 0;
764
765 unsigned Size = 0;
766 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
767 MachineConstantPoolEntry CPE = Constants[i];
768 unsigned AlignMask = CPE.getAlignment() - 1;
769 Size = (Size + AlignMask) & ~AlignMask;
770 Type *Ty = CPE.getType();
771 Size += TD->getTypeAllocSize(Ty);
772 }
773 return Size;
774 }
775
startFunction(MachineFunction & F)776 void JITEmitter::startFunction(MachineFunction &F) {
777 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
778 << F.getFunction()->getName() << "\n");
779
780 uintptr_t ActualSize = 0;
781 // Set the memory writable, if it's not already
782 MemMgr->setMemoryWritable();
783
784 if (SizeEstimate > 0) {
785 // SizeEstimate will be non-zero on reallocation attempts.
786 ActualSize = SizeEstimate;
787 }
788
789 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
790 ActualSize);
791 BufferEnd = BufferBegin+ActualSize;
792 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
793
794 // Ensure the constant pool/jump table info is at least 4-byte aligned.
795 emitAlignment(16);
796
797 emitConstantPool(F.getConstantPool());
798 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
799 initJumpTableInfo(MJTI);
800
801 // About to start emitting the machine code for the function.
802 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
803 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
804 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
805
806 MBBLocations.clear();
807
808 EmissionDetails.MF = &F;
809 EmissionDetails.LineStarts.clear();
810 }
811
finishFunction(MachineFunction & F)812 bool JITEmitter::finishFunction(MachineFunction &F) {
813 if (CurBufferPtr == BufferEnd) {
814 // We must call endFunctionBody before retrying, because
815 // deallocateMemForFunction requires it.
816 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
817 retryWithMoreMemory(F);
818 return true;
819 }
820
821 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
822 emitJumpTableInfo(MJTI);
823
824 // FnStart is the start of the text, not the start of the constant pool and
825 // other per-function data.
826 uint8_t *FnStart =
827 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
828
829 // FnEnd is the end of the function's machine code.
830 uint8_t *FnEnd = CurBufferPtr;
831
832 if (!Relocations.empty()) {
833 CurFn = F.getFunction();
834 NumRelos += Relocations.size();
835
836 // Resolve the relocations to concrete pointers.
837 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
838 MachineRelocation &MR = Relocations[i];
839 void *ResultPtr = 0;
840 if (!MR.letTargetResolve()) {
841 if (MR.isExternalSymbol()) {
842 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
843 false);
844 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
845 << ResultPtr << "]\n");
846
847 // If the target REALLY wants a stub for this function, emit it now.
848 if (MR.mayNeedFarStub()) {
849 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
850 }
851 } else if (MR.isGlobalValue()) {
852 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
853 BufferBegin+MR.getMachineCodeOffset(),
854 MR.mayNeedFarStub());
855 } else if (MR.isIndirectSymbol()) {
856 ResultPtr = getPointerToGVIndirectSym(
857 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
858 } else if (MR.isBasicBlock()) {
859 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
860 } else if (MR.isConstantPoolIndex()) {
861 ResultPtr =
862 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
863 } else {
864 assert(MR.isJumpTableIndex());
865 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
866 }
867
868 MR.setResultPointer(ResultPtr);
869 }
870
871 // if we are managing the GOT and the relocation wants an index,
872 // give it one
873 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
874 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
875 MR.setGOTIndex(idx);
876 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
877 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
878 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
879 << "\n");
880 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
881 }
882 }
883 }
884
885 CurFn = 0;
886 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
887 Relocations.size(), MemMgr->getGOTBase());
888 }
889
890 // Update the GOT entry for F to point to the new code.
891 if (MemMgr->isManagingGOT()) {
892 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
893 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
894 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
895 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
896 << "\n");
897 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
898 }
899 }
900
901 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
902 // global variables that were referenced in the relocations.
903 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
904
905 if (CurBufferPtr == BufferEnd) {
906 retryWithMoreMemory(F);
907 return true;
908 } else {
909 // Now that we've succeeded in emitting the function, reset the
910 // SizeEstimate back down to zero.
911 SizeEstimate = 0;
912 }
913
914 BufferBegin = CurBufferPtr = 0;
915 NumBytes += FnEnd-FnStart;
916
917 // Invalidate the icache if necessary.
918 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
919
920 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
921 EmissionDetails);
922
923 // Reset the previous debug location.
924 PrevDL = DebugLoc();
925
926 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
927 << "] Function: " << F.getFunction()->getName()
928 << ": " << (FnEnd-FnStart) << " bytes of text, "
929 << Relocations.size() << " relocations\n");
930
931 Relocations.clear();
932 ConstPoolAddresses.clear();
933
934 // Mark code region readable and executable if it's not so already.
935 MemMgr->setMemoryExecutable();
936
937 DEBUG({
938 if (sys::hasDisassembler()) {
939 dbgs() << "JIT: Disassembled code:\n";
940 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
941 (uintptr_t)FnStart);
942 } else {
943 dbgs() << "JIT: Binary code:\n";
944 uint8_t* q = FnStart;
945 for (int i = 0; q < FnEnd; q += 4, ++i) {
946 if (i == 4)
947 i = 0;
948 if (i == 0)
949 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
950 bool Done = false;
951 for (int j = 3; j >= 0; --j) {
952 if (q + j >= FnEnd)
953 Done = true;
954 else
955 dbgs() << (unsigned short)q[j];
956 }
957 if (Done)
958 break;
959 dbgs() << ' ';
960 if (i == 3)
961 dbgs() << '\n';
962 }
963 dbgs()<< '\n';
964 }
965 });
966
967 if (JITExceptionHandling) {
968 uintptr_t ActualSize = 0;
969 SavedBufferBegin = BufferBegin;
970 SavedBufferEnd = BufferEnd;
971 SavedCurBufferPtr = CurBufferPtr;
972
973 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
974 ActualSize);
975 BufferEnd = BufferBegin+ActualSize;
976 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
977 uint8_t *EhStart;
978 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
979 EhStart);
980 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
981 FrameRegister);
982 BufferBegin = SavedBufferBegin;
983 BufferEnd = SavedBufferEnd;
984 CurBufferPtr = SavedCurBufferPtr;
985
986 if (JITExceptionHandling) {
987 TheJIT->RegisterTable(F.getFunction(), FrameRegister);
988 }
989 }
990
991 if (MMI)
992 MMI->EndFunction();
993
994 return false;
995 }
996
retryWithMoreMemory(MachineFunction & F)997 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
998 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
999 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1000 ConstPoolAddresses.clear();
1001 ++NumRetries;
1002 deallocateMemForFunction(F.getFunction());
1003 // Try again with at least twice as much free space.
1004 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1005
1006 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
1007 if (MBB->hasAddressTaken())
1008 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
1009 }
1010 }
1011
1012 /// deallocateMemForFunction - Deallocate all memory for the specified
1013 /// function body. Also drop any references the function has to stubs.
1014 /// May be called while the Function is being destroyed inside ~Value().
deallocateMemForFunction(const Function * F)1015 void JITEmitter::deallocateMemForFunction(const Function *F) {
1016 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
1017 Emitted = EmittedFunctions.find(F);
1018 if (Emitted != EmittedFunctions.end()) {
1019 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1020 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1021 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
1022
1023 EmittedFunctions.erase(Emitted);
1024 }
1025
1026 if (JITExceptionHandling) {
1027 TheJIT->DeregisterTable(F);
1028 }
1029 }
1030
1031
allocateSpace(uintptr_t Size,unsigned Alignment)1032 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1033 if (BufferBegin)
1034 return JITCodeEmitter::allocateSpace(Size, Alignment);
1035
1036 // create a new memory block if there is no active one.
1037 // care must be taken so that BufferBegin is invalidated when a
1038 // block is trimmed
1039 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1040 BufferEnd = BufferBegin+Size;
1041 return CurBufferPtr;
1042 }
1043
allocateGlobal(uintptr_t Size,unsigned Alignment)1044 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1045 // Delegate this call through the memory manager.
1046 return MemMgr->allocateGlobal(Size, Alignment);
1047 }
1048
emitConstantPool(MachineConstantPool * MCP)1049 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1050 if (TheJIT->getJITInfo().hasCustomConstantPool())
1051 return;
1052
1053 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1054 if (Constants.empty()) return;
1055
1056 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1057 unsigned Align = MCP->getConstantPoolAlignment();
1058 ConstantPoolBase = allocateSpace(Size, Align);
1059 ConstantPool = MCP;
1060
1061 if (ConstantPoolBase == 0) return; // Buffer overflow.
1062
1063 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1064 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1065
1066 // Initialize the memory for all of the constant pool entries.
1067 unsigned Offset = 0;
1068 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1069 MachineConstantPoolEntry CPE = Constants[i];
1070 unsigned AlignMask = CPE.getAlignment() - 1;
1071 Offset = (Offset + AlignMask) & ~AlignMask;
1072
1073 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1074 ConstPoolAddresses.push_back(CAddr);
1075 if (CPE.isMachineConstantPoolEntry()) {
1076 // FIXME: add support to lower machine constant pool values into bytes!
1077 report_fatal_error("Initialize memory with machine specific constant pool"
1078 "entry has not been implemented!");
1079 }
1080 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1081 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1082 dbgs().write_hex(CAddr) << "]\n");
1083
1084 Type *Ty = CPE.Val.ConstVal->getType();
1085 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1086 }
1087 }
1088
initJumpTableInfo(MachineJumpTableInfo * MJTI)1089 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1090 if (TheJIT->getJITInfo().hasCustomJumpTables())
1091 return;
1092 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1093 return;
1094
1095 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1096 if (JT.empty()) return;
1097
1098 unsigned NumEntries = 0;
1099 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1100 NumEntries += JT[i].MBBs.size();
1101
1102 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getTargetData());
1103
1104 // Just allocate space for all the jump tables now. We will fix up the actual
1105 // MBB entries in the tables after we emit the code for each block, since then
1106 // we will know the final locations of the MBBs in memory.
1107 JumpTable = MJTI;
1108 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1109 MJTI->getEntryAlignment(*TheJIT->getTargetData()));
1110 }
1111
emitJumpTableInfo(MachineJumpTableInfo * MJTI)1112 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1113 if (TheJIT->getJITInfo().hasCustomJumpTables())
1114 return;
1115
1116 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1117 if (JT.empty() || JumpTableBase == 0) return;
1118
1119
1120 switch (MJTI->getEntryKind()) {
1121 case MachineJumpTableInfo::EK_Inline:
1122 return;
1123 case MachineJumpTableInfo::EK_BlockAddress: {
1124 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1125 // .word LBB123
1126 assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == sizeof(void*) &&
1127 "Cross JIT'ing?");
1128
1129 // For each jump table, map each target in the jump table to the address of
1130 // an emitted MachineBasicBlock.
1131 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1132
1133 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1134 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1135 // Store the address of the basic block for this jump table slot in the
1136 // memory we allocated for the jump table in 'initJumpTableInfo'
1137 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1138 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1139 }
1140 break;
1141 }
1142
1143 case MachineJumpTableInfo::EK_Custom32:
1144 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1145 case MachineJumpTableInfo::EK_LabelDifference32: {
1146 assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == 4&&"Cross JIT'ing?");
1147 // For each jump table, place the offset from the beginning of the table
1148 // to the target address.
1149 int *SlotPtr = (int*)JumpTableBase;
1150
1151 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1152 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1153 // Store the offset of the basic block for this jump table slot in the
1154 // memory we allocated for the jump table in 'initJumpTableInfo'
1155 uintptr_t Base = (uintptr_t)SlotPtr;
1156 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1157 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1158 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1159 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1160 }
1161 }
1162 break;
1163 }
1164 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1165 llvm_unreachable(
1166 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1167 }
1168 }
1169
startGVStub(const GlobalValue * GV,unsigned StubSize,unsigned Alignment)1170 void JITEmitter::startGVStub(const GlobalValue* GV,
1171 unsigned StubSize, unsigned Alignment) {
1172 SavedBufferBegin = BufferBegin;
1173 SavedBufferEnd = BufferEnd;
1174 SavedCurBufferPtr = CurBufferPtr;
1175
1176 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1177 BufferEnd = BufferBegin+StubSize+1;
1178 }
1179
startGVStub(void * Buffer,unsigned StubSize)1180 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1181 SavedBufferBegin = BufferBegin;
1182 SavedBufferEnd = BufferEnd;
1183 SavedCurBufferPtr = CurBufferPtr;
1184
1185 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1186 BufferEnd = BufferBegin+StubSize+1;
1187 }
1188
finishGVStub()1189 void JITEmitter::finishGVStub() {
1190 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1191 NumBytes += getCurrentPCOffset();
1192 BufferBegin = SavedBufferBegin;
1193 BufferEnd = SavedBufferEnd;
1194 CurBufferPtr = SavedCurBufferPtr;
1195 }
1196
allocIndirectGV(const GlobalValue * GV,const uint8_t * Buffer,size_t Size,unsigned Alignment)1197 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1198 const uint8_t *Buffer, size_t Size,
1199 unsigned Alignment) {
1200 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1201 memcpy(IndGV, Buffer, Size);
1202 return IndGV;
1203 }
1204
1205 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1206 // in the constant pool that was last emitted with the 'emitConstantPool'
1207 // method.
1208 //
getConstantPoolEntryAddress(unsigned ConstantNum) const1209 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1210 assert(ConstantNum < ConstantPool->getConstants().size() &&
1211 "Invalid ConstantPoolIndex!");
1212 return ConstPoolAddresses[ConstantNum];
1213 }
1214
1215 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1216 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1217 //
getJumpTableEntryAddress(unsigned Index) const1218 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1219 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1220 assert(Index < JT.size() && "Invalid jump table index!");
1221
1222 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getTargetData());
1223
1224 unsigned Offset = 0;
1225 for (unsigned i = 0; i < Index; ++i)
1226 Offset += JT[i].MBBs.size();
1227
1228 Offset *= EntrySize;
1229
1230 return (uintptr_t)((char *)JumpTableBase + Offset);
1231 }
1232
onDelete(JITEmitter * Emitter,const Function * F)1233 void JITEmitter::EmittedFunctionConfig::onDelete(
1234 JITEmitter *Emitter, const Function *F) {
1235 Emitter->deallocateMemForFunction(F);
1236 }
onRAUW(JITEmitter *,const Function *,const Function *)1237 void JITEmitter::EmittedFunctionConfig::onRAUW(
1238 JITEmitter *, const Function*, const Function*) {
1239 llvm_unreachable("The JIT doesn't know how to handle a"
1240 " RAUW on a value it has emitted.");
1241 }
1242
1243
1244 //===----------------------------------------------------------------------===//
1245 // Public interface to this file
1246 //===----------------------------------------------------------------------===//
1247
createEmitter(JIT & jit,JITMemoryManager * JMM,TargetMachine & tm)1248 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1249 TargetMachine &tm) {
1250 return new JITEmitter(jit, JMM, tm);
1251 }
1252
1253 // getPointerToFunctionOrStub - If the specified function has been
1254 // code-gen'd, return a pointer to the function. If not, compile it, or use
1255 // a stub to implement lazy compilation if available.
1256 //
getPointerToFunctionOrStub(Function * F)1257 void *JIT::getPointerToFunctionOrStub(Function *F) {
1258 // If we have already code generated the function, just return the address.
1259 if (void *Addr = getPointerToGlobalIfAvailable(F))
1260 return Addr;
1261
1262 // Get a stub if the target supports it.
1263 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1264 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1265 return JE->getJITResolver().getLazyFunctionStub(F);
1266 }
1267
updateFunctionStub(Function * F)1268 void JIT::updateFunctionStub(Function *F) {
1269 // Get the empty stub we generated earlier.
1270 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1271 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1272 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1273 void *Addr = getPointerToGlobalIfAvailable(F);
1274 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1275
1276 // Tell the target jit info to rewrite the stub at the specified address,
1277 // rather than creating a new one.
1278 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1279 JE->startGVStub(Stub, layout.Size);
1280 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1281 JE->finishGVStub();
1282 }
1283
1284 /// freeMachineCodeForFunction - release machine code memory for given Function.
1285 ///
freeMachineCodeForFunction(Function * F)1286 void JIT::freeMachineCodeForFunction(Function *F) {
1287 // Delete translation for this from the ExecutionEngine, so it will get
1288 // retranslated next time it is used.
1289 updateGlobalMapping(F, 0);
1290
1291 // Free the actual memory for the function body and related stuff.
1292 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1293 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
1294 }
1295