1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
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 // 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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "JITDebugRegisterer.h"
18 #include "JITDwarfEmitter.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Module.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/ExecutionEngine/GenericValue.h"
30 #include "llvm/ExecutionEngine/JITEventListener.h"
31 #include "llvm/ExecutionEngine/JITMemoryManager.h"
32 #include "llvm/CodeGen/MachineCodeInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetJITInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MutexGuard.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/System/Disassembler.h"
43 #include "llvm/System/Memory.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/ValueMap.h"
56 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57 STATISTIC(NumRelos, "Number of relocations applied");
58 STATISTIC(NumRetries, "Number of retries with more memory");
59 static JIT *TheJIT = 0;
62 //===----------------------------------------------------------------------===//
63 // JIT lazy compilation code.
66 class JITResolverState;
68 template<typename ValueTy>
69 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
70 typedef JITResolverState *ExtraData;
71 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
72 assert(false && "The JIT doesn't know how to handle a"
73 " RAUW on a value it has emitted.");
77 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
78 typedef JITResolverState *ExtraData;
79 static void onDelete(JITResolverState *JRS, Function *F);
82 class JITResolverState {
84 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
86 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
87 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
88 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
89 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
91 /// FunctionToStubMap - Keep track of the stub created for a particular
92 /// function so that we can reuse them if necessary.
93 FunctionToStubMapTy FunctionToStubMap;
95 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
96 /// site corresponds to, and vice versa.
97 CallSiteToFunctionMapTy CallSiteToFunctionMap;
98 FunctionToCallSitesMapTy FunctionToCallSitesMap;
100 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
101 /// particular GlobalVariable so that we can reuse them if necessary.
102 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
105 JITResolverState() : FunctionToStubMap(this),
106 FunctionToCallSitesMap(this) {}
108 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
109 assert(locked.holds(TheJIT->lock));
110 return FunctionToStubMap;
113 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
114 assert(locked.holds(TheJIT->lock));
115 return GlobalToIndirectSymMap;
118 pair<void *, Function *> LookupFunctionFromCallSite(
119 const MutexGuard &locked, void *CallSite) const {
120 assert(locked.holds(TheJIT->lock));
122 // The address given to us for the stub may not be exactly right, it might be
123 // a little bit after the stub. As such, use upper_bound to find it.
124 CallSiteToFunctionMapTy::const_iterator I =
125 CallSiteToFunctionMap.upper_bound(CallSite);
126 assert(I != CallSiteToFunctionMap.begin() &&
127 "This is not a known call site!");
132 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
133 assert(locked.holds(TheJIT->lock));
135 bool Inserted = CallSiteToFunctionMap.insert(
136 std::make_pair(CallSite, F)).second;
138 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
139 FunctionToCallSitesMap[F].insert(CallSite);
142 // Returns the Function of the stub if a stub was erased, or NULL if there
143 // was no stub. This function uses the call-site->function map to find a
144 // relevant function, but asserts that only stubs and not other call sites
145 // will be passed in.
146 Function *EraseStub(const MutexGuard &locked, void *Stub) {
147 CallSiteToFunctionMapTy::iterator C2F_I =
148 CallSiteToFunctionMap.find(Stub);
149 if (C2F_I == CallSiteToFunctionMap.end()) {
154 Function *const F = C2F_I->second;
156 void *RealStub = FunctionToStubMap.lookup(F);
157 assert(RealStub == Stub &&
158 "Call-site that wasn't a stub pass in to EraseStub");
160 FunctionToStubMap.erase(F);
161 CallSiteToFunctionMap.erase(C2F_I);
163 // Remove the stub from the function->call-sites map, and remove the whole
164 // entry from the map if that was the last call site.
165 FunctionToCallSitesMapTy::iterator F2C_I = FunctionToCallSitesMap.find(F);
166 assert(F2C_I != FunctionToCallSitesMap.end() &&
167 "FunctionToCallSitesMap broken");
168 bool Erased = F2C_I->second.erase(Stub);
170 assert(Erased && "FunctionToCallSitesMap broken");
171 if (F2C_I->second.empty())
172 FunctionToCallSitesMap.erase(F2C_I);
177 void EraseAllCallSites(const MutexGuard &locked, Function *F) {
178 assert(locked.holds(TheJIT->lock));
179 EraseAllCallSitesPrelocked(F);
181 void EraseAllCallSitesPrelocked(Function *F) {
182 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
183 if (F2C == FunctionToCallSitesMap.end())
185 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
186 E = F2C->second.end(); I != E; ++I) {
187 bool Erased = CallSiteToFunctionMap.erase(*I);
189 assert(Erased && "Missing call site->function mapping");
191 FunctionToCallSitesMap.erase(F2C);
195 /// JITResolver - Keep track of, and resolve, call sites for functions that
196 /// have not yet been compiled.
198 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
199 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
200 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
202 /// LazyResolverFn - The target lazy resolver function that we actually
203 /// rewrite instructions to use.
204 TargetJITInfo::LazyResolverFn LazyResolverFn;
206 JITResolverState state;
208 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
209 /// external functions.
210 std::map<void*, void*> ExternalFnToStubMap;
212 /// revGOTMap - map addresses to indexes in the GOT
213 std::map<void*, unsigned> revGOTMap;
214 unsigned nextGOTIndex;
216 static JITResolver *TheJITResolver;
218 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
221 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
222 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
223 TheJITResolver = this;
230 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
231 /// if it has already been created.
232 void *getFunctionStubIfAvailable(Function *F);
234 /// getFunctionStub - This returns a pointer to a function stub, creating
235 /// one on demand as needed. If empty is true, create a function stub
236 /// pointing at address 0, to be filled in later.
237 void *getFunctionStub(Function *F);
239 /// getExternalFunctionStub - Return a stub for the function at the
240 /// specified address, created lazily on demand.
241 void *getExternalFunctionStub(void *FnAddr);
243 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
244 /// specified GV address.
245 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
247 /// AddCallbackAtLocation - If the target is capable of rewriting an
248 /// instruction without the use of a stub, record the location of the use so
249 /// we know which function is being used at the location.
250 void *AddCallbackAtLocation(Function *F, void *Location) {
251 MutexGuard locked(TheJIT->lock);
252 /// Get the target-specific JIT resolver function.
253 state.AddCallSite(locked, Location, F);
254 return (void*)(intptr_t)LazyResolverFn;
257 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
258 SmallVectorImpl<void*> &Ptrs);
260 GlobalValue *invalidateStub(void *Stub);
262 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
263 /// an address. This function only manages slots, it does not manage the
264 /// contents of the slots or the memory associated with the GOT.
265 unsigned getGOTIndexForAddr(void *addr);
267 /// JITCompilerFn - This function is called to resolve a stub to a compiled
268 /// address. If the LLVM Function corresponding to the stub has not yet
269 /// been compiled, this function compiles it first.
270 static void *JITCompilerFn(void *Stub);
274 JITResolver *JITResolver::TheJITResolver = 0;
276 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
277 JRS->EraseAllCallSitesPrelocked(F);
280 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
281 /// if it has already been created.
282 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
283 MutexGuard locked(TheJIT->lock);
285 // If we already have a stub for this function, recycle it.
286 return state.getFunctionToStubMap(locked).lookup(F);
289 /// getFunctionStub - This returns a pointer to a function stub, creating
290 /// one on demand as needed.
291 void *JITResolver::getFunctionStub(Function *F) {
292 MutexGuard locked(TheJIT->lock);
294 // If we already have a stub for this function, recycle it.
295 void *&Stub = state.getFunctionToStubMap(locked)[F];
296 if (Stub) return Stub;
298 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
299 // case we must resolve the symbol now.
300 void *Actual = TheJIT->isLazyCompilationDisabled()
301 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
303 // If this is an external declaration, attempt to resolve the address now
304 // to place in the stub.
305 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
306 Actual = TheJIT->getPointerToFunction(F);
308 // If we resolved the symbol to a null address (eg. a weak external)
309 // don't emit a stub. Return a null pointer to the application. If dlsym
310 // stubs are enabled, not being able to resolve the address is not
312 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
315 // Codegen a new stub, calling the lazy resolver or the actual address of the
316 // external function, if it was resolved.
317 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
318 *TheJIT->getCodeEmitter());
320 if (Actual != (void*)(intptr_t)LazyResolverFn) {
321 // If we are getting the stub for an external function, we really want the
322 // address of the stub in the GlobalAddressMap for the JIT, not the address
323 // of the external function.
324 TheJIT->updateGlobalMapping(F, Stub);
327 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
328 << F->getName() << "'\n");
330 // Finally, keep track of the stub-to-Function mapping so that the
331 // JITCompilerFn knows which function to compile!
332 state.AddCallSite(locked, Stub, F);
334 // If we are JIT'ing non-lazily but need to call a function that does not
335 // exist yet, add it to the JIT's work list so that we can fill in the stub
337 if (!Actual && TheJIT->isLazyCompilationDisabled())
338 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
339 TheJIT->addPendingFunction(F);
344 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
346 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
347 MutexGuard locked(TheJIT->lock);
349 // If we already have a stub for this global variable, recycle it.
350 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
351 if (IndirectSym) return IndirectSym;
353 // Otherwise, codegen a new indirect symbol.
354 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
355 *TheJIT->getCodeEmitter());
357 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
358 << "] for GV '" << GV->getName() << "'\n");
363 /// getExternalFunctionStub - Return a stub for the function at the
364 /// specified address, created lazily on demand.
365 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
366 // If we already have a stub for this function, recycle it.
367 void *&Stub = ExternalFnToStubMap[FnAddr];
368 if (Stub) return Stub;
370 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
371 *TheJIT->getCodeEmitter());
373 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
374 << "] for external function at '" << FnAddr << "'\n");
378 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
379 unsigned idx = revGOTMap[addr];
381 idx = ++nextGOTIndex;
382 revGOTMap[addr] = idx;
383 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
389 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
390 SmallVectorImpl<void*> &Ptrs) {
391 MutexGuard locked(TheJIT->lock);
393 const FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
394 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
396 for (FunctionToStubMapTy::const_iterator i = FM.begin(), e = FM.end();
398 Function *F = i->first;
399 if (F->isDeclaration() && F->hasExternalLinkage()) {
400 GVs.push_back(i->first);
401 Ptrs.push_back(i->second);
404 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
406 GVs.push_back(i->first);
407 Ptrs.push_back(i->second);
411 GlobalValue *JITResolver::invalidateStub(void *Stub) {
412 MutexGuard locked(TheJIT->lock);
414 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
416 // Look up the cheap way first, to see if it's a function stub we are
417 // invalidating. If so, remove it from both the forward and reverse maps.
418 if (Function *F = state.EraseStub(locked, Stub)) {
422 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
423 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
425 if (i->second != Stub)
427 GlobalValue *GV = i->first;
432 // Lastly, check to see if it's in the ExternalFnToStubMap.
433 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
434 e = ExternalFnToStubMap.end(); i != e; ++i) {
435 if (i->second != Stub)
437 ExternalFnToStubMap.erase(i);
444 /// JITCompilerFn - This function is called when a lazy compilation stub has
445 /// been entered. It looks up which function this stub corresponds to, compiles
446 /// it if necessary, then returns the resultant function pointer.
447 void *JITResolver::JITCompilerFn(void *Stub) {
448 JITResolver &JR = *TheJITResolver;
454 // Only lock for getting the Function. The call getPointerToFunction made
455 // in this function might trigger function materializing, which requires
456 // JIT lock to be unlocked.
457 MutexGuard locked(TheJIT->lock);
459 // The address given to us for the stub may not be exactly right, it might
460 // be a little bit after the stub. As such, use upper_bound to find it.
461 pair<void*, Function*> I =
462 JR.state.LookupFunctionFromCallSite(locked, Stub);
467 // If we have already code generated the function, just return the address.
468 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
471 // Otherwise we don't have it, do lazy compilation now.
473 // If lazy compilation is disabled, emit a useful error message and abort.
474 if (TheJIT->isLazyCompilationDisabled()) {
475 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
476 + F->getName() + "' when lazy compiles are disabled!");
479 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
480 << "' In stub ptr = " << Stub << " actual ptr = "
481 << ActualPtr << "\n");
483 Result = TheJIT->getPointerToFunction(F);
486 // Reacquire the lock to update the GOT map.
487 MutexGuard locked(TheJIT->lock);
489 // We might like to remove the call site from the CallSiteToFunction map, but
490 // we can't do that! Multiple threads could be stuck, waiting to acquire the
491 // lock above. As soon as the 1st function finishes compiling the function,
492 // the next one will be released, and needs to be able to find the function it
495 // FIXME: We could rewrite all references to this stub if we knew them.
497 // What we will do is set the compiled function address to map to the
498 // same GOT entry as the stub so that later clients may update the GOT
499 // if they see it still using the stub address.
500 // Note: this is done so the Resolver doesn't have to manage GOT memory
501 // Do this without allocating map space if the target isn't using a GOT
502 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
503 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
508 //===----------------------------------------------------------------------===//
512 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
513 /// used to output functions to memory for execution.
514 class JITEmitter : public JITCodeEmitter {
515 JITMemoryManager *MemMgr;
517 // When outputting a function stub in the context of some other function, we
518 // save BufferBegin/BufferEnd/CurBufferPtr here.
519 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
521 // When reattempting to JIT a function after running out of space, we store
522 // the estimated size of the function we're trying to JIT here, so we can
523 // ask the memory manager for at least this much space. When we
524 // successfully emit the function, we reset this back to zero.
525 uintptr_t SizeEstimate;
527 /// Relocations - These are the relocations that the function needs, as
529 std::vector<MachineRelocation> Relocations;
531 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
532 /// It is filled in by the StartMachineBasicBlock callback and queried by
533 /// the getMachineBasicBlockAddress callback.
534 std::vector<uintptr_t> MBBLocations;
536 /// ConstantPool - The constant pool for the current function.
538 MachineConstantPool *ConstantPool;
540 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
542 void *ConstantPoolBase;
544 /// ConstPoolAddresses - Addresses of individual constant pool entries.
546 SmallVector<uintptr_t, 8> ConstPoolAddresses;
548 /// JumpTable - The jump tables for the current function.
550 MachineJumpTableInfo *JumpTable;
552 /// JumpTableBase - A pointer to the first entry in the jump table.
556 /// Resolver - This contains info about the currently resolved functions.
557 JITResolver Resolver;
559 /// DE - The dwarf emitter for the jit.
560 OwningPtr<JITDwarfEmitter> DE;
562 /// DR - The debug registerer for the jit.
563 OwningPtr<JITDebugRegisterer> DR;
565 /// LabelLocations - This vector is a mapping from Label ID's to their
567 std::vector<uintptr_t> LabelLocations;
569 /// MMI - Machine module info for exception informations
570 MachineModuleInfo* MMI;
572 // GVSet - a set to keep track of which globals have been seen
573 SmallPtrSet<const GlobalVariable*, 8> GVSet;
575 // CurFn - The llvm function being emitted. Only valid during
577 const Function *CurFn;
579 /// Information about emitted code, which is passed to the
580 /// JITEventListeners. This is reset in startFunction and used in
582 JITEvent_EmittedFunctionDetails EmissionDetails;
585 void *FunctionBody; // Beginning of the function's allocation.
586 void *Code; // The address the function's code actually starts at.
587 void *ExceptionTable;
588 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
590 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
591 typedef JITEmitter *ExtraData;
592 static void onDelete(JITEmitter *, const Function*);
593 static void onRAUW(JITEmitter *, const Function*, const Function*);
595 ValueMap<const Function *, EmittedCode,
596 EmittedFunctionConfig> EmittedFunctions;
598 // CurFnStubUses - For a given Function, a vector of stubs that it
599 // references. This facilitates the JIT detecting that a stub is no
600 // longer used, so that it may be deallocated.
601 DenseMap<AssertingVH<const Function>, SmallVector<void*, 1> > CurFnStubUses;
603 // StubFnRefs - For a given pointer to a stub, a set of Functions which
604 // reference the stub. When the count of a stub's references drops to zero,
605 // the stub is unused.
606 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
608 // ExtFnStubs - A map of external function names to stubs which have entries
609 // in the JITResolver's ExternalFnToStubMap.
610 StringMap<void *> ExtFnStubs;
612 DebugLocTuple PrevDLT;
615 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
616 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0),
617 EmittedFunctions(this) {
618 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
619 if (jit.getJITInfo().needsGOT()) {
620 MemMgr->AllocateGOT();
621 DEBUG(errs() << "JIT is managing a GOT\n");
624 if (DwarfExceptionHandling || JITEmitDebugInfo) {
625 DE.reset(new JITDwarfEmitter(jit));
627 if (JITEmitDebugInfo) {
628 DR.reset(new JITDebugRegisterer(TM));
635 /// classof - Methods for support type inquiry through isa, cast, and
638 static inline bool classof(const JITEmitter*) { return true; }
639 static inline bool classof(const MachineCodeEmitter*) { return true; }
641 JITResolver &getJITResolver() { return Resolver; }
643 virtual void startFunction(MachineFunction &F);
644 virtual bool finishFunction(MachineFunction &F);
646 void emitConstantPool(MachineConstantPool *MCP);
647 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
648 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
650 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
651 unsigned Alignment = 1);
652 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
654 virtual void* finishGVStub(const GlobalValue *GV);
656 /// allocateSpace - Reserves space in the current block if any, or
657 /// allocate a new one of the given size.
658 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
660 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
661 /// this method does not allocate memory in the current output buffer,
662 /// because a global may live longer than the current function.
663 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
665 virtual void addRelocation(const MachineRelocation &MR) {
666 Relocations.push_back(MR);
669 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
670 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
671 MBBLocations.resize((MBB->getNumber()+1)*2);
672 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
673 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
674 << (void*) getCurrentPCValue() << "]\n");
677 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
678 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
680 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
681 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
682 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
683 return MBBLocations[MBB->getNumber()];
686 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
687 /// given function. Increase the minimum allocation size so that we get
688 /// more memory next time.
689 void retryWithMoreMemory(MachineFunction &F);
691 /// deallocateMemForFunction - Deallocate all memory for the specified
693 void deallocateMemForFunction(const Function *F);
695 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
696 /// using the stub at the specified address. Allows
697 /// deallocateMemForFunction to also remove stubs no longer referenced.
698 void AddStubToCurrentFunction(void *Stub);
700 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
701 /// MachineRelocations that reference external functions by name.
702 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
704 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
706 virtual void emitLabel(uint64_t LabelID) {
707 if (LabelLocations.size() <= LabelID)
708 LabelLocations.resize((LabelID+1)*2);
709 LabelLocations[LabelID] = getCurrentPCValue();
712 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
713 assert(LabelLocations.size() > (unsigned)LabelID &&
714 LabelLocations[LabelID] && "Label not emitted!");
715 return LabelLocations[LabelID];
718 virtual void setModuleInfo(MachineModuleInfo* Info) {
720 if (DE.get()) DE->setModuleInfo(Info);
723 void setMemoryExecutable() {
724 MemMgr->setMemoryExecutable();
727 JITMemoryManager *getMemMgr() const { return MemMgr; }
730 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
731 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
733 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
734 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
735 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
736 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
740 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
741 bool DoesntNeedStub) {
742 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
743 return TheJIT->getOrEmitGlobalVariable(GV);
745 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
746 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
748 // If we have already compiled the function, return a pointer to its body.
749 Function *F = cast<Function>(V);
751 if (!DoesntNeedStub) {
752 // Return the function stub if it's already created.
753 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
755 AddStubToCurrentFunction(ResultPtr);
757 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
759 if (ResultPtr) return ResultPtr;
761 // If this is an external function pointer, we can force the JIT to
762 // 'compile' it, which really just adds it to the map. In dlsym mode,
763 // external functions are forced through a stub, regardless of reloc type.
764 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
765 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
766 return TheJIT->getPointerToFunction(F);
768 // Okay, the function has not been compiled yet, if the target callback
769 // mechanism is capable of rewriting the instruction directly, prefer to do
770 // that instead of emitting a stub. This uses the lazy resolver, so is not
771 // legal if lazy compilation is disabled.
772 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
773 return Resolver.AddCallbackAtLocation(F, Reference);
775 // Otherwise, we have to emit a stub.
776 void *StubAddr = Resolver.getFunctionStub(F);
778 // Add the stub to the current function's list of referenced stubs, so we can
779 // deallocate them if the current function is ever freed. It's possible to
780 // return null from getFunctionStub in the case of a weak extern that fails
783 AddStubToCurrentFunction(StubAddr);
788 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
790 // Make sure GV is emitted first, and create a stub containing the fully
792 void *GVAddress = getPointerToGlobal(V, Reference, true);
793 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
795 // Add the stub to the current function's list of referenced stubs, so we can
796 // deallocate them if the current function is ever freed.
797 AddStubToCurrentFunction(StubAddr);
802 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
803 assert(CurFn && "Stub added to current function, but current function is 0!");
805 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
806 StubsUsed.push_back(StubAddr);
808 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
809 FnRefs.insert(CurFn);
812 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
813 if (!DL.isUnknown()) {
814 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
816 if (BeforePrintingInsn) {
817 if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
818 JITEvent_EmittedFunctionDetails::LineStart NextLine;
819 NextLine.Address = getCurrentPCValue();
821 EmissionDetails.LineStarts.push_back(NextLine);
829 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
830 const TargetData *TD) {
831 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
832 if (Constants.empty()) return 0;
835 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
836 MachineConstantPoolEntry CPE = Constants[i];
837 unsigned AlignMask = CPE.getAlignment() - 1;
838 Size = (Size + AlignMask) & ~AlignMask;
839 const Type *Ty = CPE.getType();
840 Size += TD->getTypeAllocSize(Ty);
845 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
846 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
847 if (JT.empty()) return 0;
849 unsigned NumEntries = 0;
850 for (unsigned i = 0, e = JT.size(); i != e; ++i)
851 NumEntries += JT[i].MBBs.size();
853 unsigned EntrySize = MJTI->getEntrySize();
855 return NumEntries * EntrySize;
858 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
859 if (Alignment == 0) Alignment = 1;
860 // Since we do not know where the buffer will be allocated, be pessimistic.
861 return Size + Alignment;
864 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
865 /// into the running total Size.
867 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
868 const Type *ElTy = GV->getType()->getElementType();
869 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
871 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
872 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
874 // Assume code section ends with worst possible alignment, so first
875 // variable needs maximal padding.
878 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
883 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
884 /// but are referenced from the constant; put them in GVSet and add their
885 /// size into the running total Size.
887 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
889 // If its undefined, return the garbage.
890 if (isa<UndefValue>(C))
893 // If the value is a ConstantExpr
894 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
895 Constant *Op0 = CE->getOperand(0);
896 switch (CE->getOpcode()) {
897 case Instruction::GetElementPtr:
898 case Instruction::Trunc:
899 case Instruction::ZExt:
900 case Instruction::SExt:
901 case Instruction::FPTrunc:
902 case Instruction::FPExt:
903 case Instruction::UIToFP:
904 case Instruction::SIToFP:
905 case Instruction::FPToUI:
906 case Instruction::FPToSI:
907 case Instruction::PtrToInt:
908 case Instruction::IntToPtr:
909 case Instruction::BitCast: {
910 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
913 case Instruction::Add:
914 case Instruction::FAdd:
915 case Instruction::Sub:
916 case Instruction::FSub:
917 case Instruction::Mul:
918 case Instruction::FMul:
919 case Instruction::UDiv:
920 case Instruction::SDiv:
921 case Instruction::URem:
922 case Instruction::SRem:
923 case Instruction::And:
924 case Instruction::Or:
925 case Instruction::Xor: {
926 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
927 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
932 raw_string_ostream Msg(msg);
933 Msg << "ConstantExpr not handled: " << *CE;
934 llvm_report_error(Msg.str());
939 if (C->getType()->getTypeID() == Type::PointerTyID)
940 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
941 if (GVSet.insert(GV))
942 Size = addSizeOfGlobal(GV, Size);
947 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
948 /// but are referenced from the given initializer.
950 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
952 if (!isa<UndefValue>(Init) &&
953 !isa<ConstantVector>(Init) &&
954 !isa<ConstantAggregateZero>(Init) &&
955 !isa<ConstantArray>(Init) &&
956 !isa<ConstantStruct>(Init) &&
957 Init->getType()->isFirstClassType())
958 Size = addSizeOfGlobalsInConstantVal(Init, Size);
962 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
963 /// globals; then walk the initializers of those globals looking for more.
964 /// If their size has not been considered yet, add it into the running total
967 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
971 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
973 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
975 const TargetInstrDesc &Desc = I->getDesc();
976 const MachineInstr &MI = *I;
977 unsigned NumOps = Desc.getNumOperands();
978 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
979 const MachineOperand &MO = MI.getOperand(CurOp);
981 GlobalValue* V = MO.getGlobal();
982 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
985 // If seen in previous function, it will have an entry here.
986 if (TheJIT->getPointerToGlobalIfAvailable(GV))
988 // If seen earlier in this function, it will have an entry here.
989 // FIXME: it should be possible to combine these tables, by
990 // assuming the addresses of the new globals in this module
991 // start at 0 (or something) and adjusting them after codegen
992 // complete. Another possibility is to grab a marker bit in GV.
993 if (GVSet.insert(GV))
994 // A variable as yet unseen. Add in its size.
995 Size = addSizeOfGlobal(GV, Size);
1000 DEBUG(errs() << "JIT: About to look through initializers\n");
1001 // Look for more globals that are referenced only from initializers.
1002 // GVSet.end is computed each time because the set can grow as we go.
1003 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
1004 I != GVSet.end(); I++) {
1005 const GlobalVariable* GV = *I;
1006 if (GV->hasInitializer())
1007 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
1013 void JITEmitter::startFunction(MachineFunction &F) {
1014 DEBUG(errs() << "JIT: Starting CodeGen of Function "
1015 << F.getFunction()->getName() << "\n");
1017 uintptr_t ActualSize = 0;
1018 // Set the memory writable, if it's not already
1019 MemMgr->setMemoryWritable();
1020 if (MemMgr->NeedsExactSize()) {
1021 DEBUG(errs() << "JIT: ExactSize\n");
1022 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
1023 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
1024 MachineConstantPool *MCP = F.getConstantPool();
1026 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1027 ActualSize = RoundUpToAlign(ActualSize, 16);
1029 // Add the alignment of the constant pool
1030 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
1032 // Add the constant pool size
1033 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1035 // Add the aligment of the jump table info
1036 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
1038 // Add the jump table size
1039 ActualSize += GetJumpTableSizeInBytes(MJTI);
1041 // Add the alignment for the function
1042 ActualSize = RoundUpToAlign(ActualSize,
1043 std::max(F.getFunction()->getAlignment(), 8U));
1045 // Add the function size
1046 ActualSize += TII->GetFunctionSizeInBytes(F);
1048 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
1049 // Add the size of the globals that will be allocated after this function.
1050 // These are all the ones referenced from this function that were not
1051 // previously allocated.
1052 ActualSize += GetSizeOfGlobalsInBytes(F);
1053 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
1054 } else if (SizeEstimate > 0) {
1055 // SizeEstimate will be non-zero on reallocation attempts.
1056 ActualSize = SizeEstimate;
1059 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1061 BufferEnd = BufferBegin+ActualSize;
1062 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
1064 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1067 emitConstantPool(F.getConstantPool());
1068 initJumpTableInfo(F.getJumpTableInfo());
1070 // About to start emitting the machine code for the function.
1071 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1072 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1073 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
1075 MBBLocations.clear();
1077 EmissionDetails.MF = &F;
1078 EmissionDetails.LineStarts.clear();
1081 bool JITEmitter::finishFunction(MachineFunction &F) {
1082 if (CurBufferPtr == BufferEnd) {
1083 // We must call endFunctionBody before retrying, because
1084 // deallocateMemForFunction requires it.
1085 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1086 retryWithMoreMemory(F);
1090 emitJumpTableInfo(F.getJumpTableInfo());
1092 // FnStart is the start of the text, not the start of the constant pool and
1093 // other per-function data.
1095 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1097 // FnEnd is the end of the function's machine code.
1098 uint8_t *FnEnd = CurBufferPtr;
1100 if (!Relocations.empty()) {
1101 CurFn = F.getFunction();
1102 NumRelos += Relocations.size();
1104 // Resolve the relocations to concrete pointers.
1105 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1106 MachineRelocation &MR = Relocations[i];
1107 void *ResultPtr = 0;
1108 if (!MR.letTargetResolve()) {
1109 if (MR.isExternalSymbol()) {
1110 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1112 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1113 << ResultPtr << "]\n");
1115 // If the target REALLY wants a stub for this function, emit it now.
1116 if (!MR.doesntNeedStub()) {
1117 if (!TheJIT->areDlsymStubsEnabled()) {
1118 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1120 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1122 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1123 AddStubToCurrentFunction(Stub);
1128 } else if (MR.isGlobalValue()) {
1129 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1130 BufferBegin+MR.getMachineCodeOffset(),
1131 MR.doesntNeedStub());
1132 } else if (MR.isIndirectSymbol()) {
1133 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1134 BufferBegin+MR.getMachineCodeOffset(),
1135 MR.doesntNeedStub());
1136 } else if (MR.isBasicBlock()) {
1137 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1138 } else if (MR.isConstantPoolIndex()) {
1139 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1141 assert(MR.isJumpTableIndex());
1142 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1145 MR.setResultPointer(ResultPtr);
1148 // if we are managing the GOT and the relocation wants an index,
1150 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1151 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1152 MR.setGOTIndex(idx);
1153 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1154 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1155 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1157 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1163 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1164 Relocations.size(), MemMgr->getGOTBase());
1167 // Update the GOT entry for F to point to the new code.
1168 if (MemMgr->isManagingGOT()) {
1169 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1170 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1171 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1172 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1174 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1178 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1179 // global variables that were referenced in the relocations.
1180 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1182 if (CurBufferPtr == BufferEnd) {
1183 retryWithMoreMemory(F);
1186 // Now that we've succeeded in emitting the function, reset the
1187 // SizeEstimate back down to zero.
1191 BufferBegin = CurBufferPtr = 0;
1192 NumBytes += FnEnd-FnStart;
1194 // Invalidate the icache if necessary.
1195 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1197 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1200 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1201 << "] Function: " << F.getFunction()->getName()
1202 << ": " << (FnEnd-FnStart) << " bytes of text, "
1203 << Relocations.size() << " relocations\n");
1205 Relocations.clear();
1206 ConstPoolAddresses.clear();
1208 // Mark code region readable and executable if it's not so already.
1209 MemMgr->setMemoryExecutable();
1212 if (sys::hasDisassembler()) {
1213 errs() << "JIT: Disassembled code:\n";
1214 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1215 (uintptr_t)FnStart);
1217 errs() << "JIT: Binary code:\n";
1218 uint8_t* q = FnStart;
1219 for (int i = 0; q < FnEnd; q += 4, ++i) {
1223 errs() << "JIT: " << (long)(q - FnStart) << ": ";
1225 for (int j = 3; j >= 0; --j) {
1229 errs() << (unsigned short)q[j];
1241 if (DwarfExceptionHandling || JITEmitDebugInfo) {
1242 uintptr_t ActualSize = 0;
1243 SavedBufferBegin = BufferBegin;
1244 SavedBufferEnd = BufferEnd;
1245 SavedCurBufferPtr = CurBufferPtr;
1247 if (MemMgr->NeedsExactSize()) {
1248 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1251 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1253 BufferEnd = BufferBegin+ActualSize;
1254 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
1256 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1258 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1260 uint8_t *EhEnd = CurBufferPtr;
1261 BufferBegin = SavedBufferBegin;
1262 BufferEnd = SavedBufferEnd;
1263 CurBufferPtr = SavedCurBufferPtr;
1265 if (DwarfExceptionHandling) {
1266 TheJIT->RegisterTable(FrameRegister);
1269 if (JITEmitDebugInfo) {
1271 I.FnStart = FnStart;
1273 I.EhStart = EhStart;
1275 DR->RegisterFunction(F.getFunction(), I);
1285 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1286 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
1287 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1288 ConstPoolAddresses.clear();
1290 deallocateMemForFunction(F.getFunction());
1291 // Try again with at least twice as much free space.
1292 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1295 /// deallocateMemForFunction - Deallocate all memory for the specified
1296 /// function body. Also drop any references the function has to stubs.
1297 /// May be called while the Function is being destroyed inside ~Value().
1298 void JITEmitter::deallocateMemForFunction(const Function *F) {
1299 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
1300 Emitted = EmittedFunctions.find(F);
1301 if (Emitted != EmittedFunctions.end()) {
1302 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1303 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1304 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
1306 EmittedFunctions.erase(Emitted);
1309 // TODO: Do we need to unregister exception handling information from libgcc
1312 if (JITEmitDebugInfo) {
1313 DR->UnregisterFunction(F);
1316 // If the function did not reference any stubs, return.
1317 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1320 // For each referenced stub, erase the reference to this function, and then
1321 // erase the list of referenced stubs.
1322 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1323 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1324 void *Stub = StubList[i];
1326 // If we already invalidated this stub for this function, continue.
1327 if (StubFnRefs.count(Stub) == 0)
1330 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1333 // If this function was the last reference to the stub, invalidate the stub
1334 // in the JITResolver. Were there a memory manager deallocateStub routine,
1335 // we could call that at this point too.
1336 if (FnRefs.empty()) {
1337 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
1338 StubFnRefs.erase(Stub);
1340 // Invalidate the stub. If it is a GV stub, update the JIT's global
1341 // mapping for that GV to zero, otherwise, search the string map of
1342 // external function names to stubs and remove the entry for this stub.
1343 GlobalValue *GV = Resolver.invalidateStub(Stub);
1345 TheJIT->updateGlobalMapping(GV, 0);
1347 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1348 e = ExtFnStubs.end(); i != e; ++i) {
1349 if (i->second == Stub) {
1350 ExtFnStubs.erase(i);
1357 CurFnStubUses.erase(F);
1361 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1363 return JITCodeEmitter::allocateSpace(Size, Alignment);
1365 // create a new memory block if there is no active one.
1366 // care must be taken so that BufferBegin is invalidated when a
1368 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1369 BufferEnd = BufferBegin+Size;
1370 return CurBufferPtr;
1373 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1374 // Delegate this call through the memory manager.
1375 return MemMgr->allocateGlobal(Size, Alignment);
1378 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1379 if (TheJIT->getJITInfo().hasCustomConstantPool())
1382 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1383 if (Constants.empty()) return;
1385 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1386 unsigned Align = MCP->getConstantPoolAlignment();
1387 ConstantPoolBase = allocateSpace(Size, Align);
1390 if (ConstantPoolBase == 0) return; // Buffer overflow.
1392 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1393 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1395 // Initialize the memory for all of the constant pool entries.
1396 unsigned Offset = 0;
1397 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1398 MachineConstantPoolEntry CPE = Constants[i];
1399 unsigned AlignMask = CPE.getAlignment() - 1;
1400 Offset = (Offset + AlignMask) & ~AlignMask;
1402 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1403 ConstPoolAddresses.push_back(CAddr);
1404 if (CPE.isMachineConstantPoolEntry()) {
1405 // FIXME: add support to lower machine constant pool values into bytes!
1406 llvm_report_error("Initialize memory with machine specific constant pool"
1407 "entry has not been implemented!");
1409 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1410 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1411 errs().write_hex(CAddr) << "]\n");
1413 const Type *Ty = CPE.Val.ConstVal->getType();
1414 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1418 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1419 if (TheJIT->getJITInfo().hasCustomJumpTables())
1422 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1423 if (JT.empty()) return;
1425 unsigned NumEntries = 0;
1426 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1427 NumEntries += JT[i].MBBs.size();
1429 unsigned EntrySize = MJTI->getEntrySize();
1431 // Just allocate space for all the jump tables now. We will fix up the actual
1432 // MBB entries in the tables after we emit the code for each block, since then
1433 // we will know the final locations of the MBBs in memory.
1435 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1438 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1439 if (TheJIT->getJITInfo().hasCustomJumpTables())
1442 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1443 if (JT.empty() || JumpTableBase == 0) return;
1445 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1446 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1447 // For each jump table, place the offset from the beginning of the table
1448 // to the target address.
1449 int *SlotPtr = (int*)JumpTableBase;
1451 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1452 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1453 // Store the offset of the basic block for this jump table slot in the
1454 // memory we allocated for the jump table in 'initJumpTableInfo'
1455 uintptr_t Base = (uintptr_t)SlotPtr;
1456 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1457 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1458 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1462 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1464 // For each jump table, map each target in the jump table to the address of
1465 // an emitted MachineBasicBlock.
1466 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1468 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1469 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1470 // Store the address of the basic block for this jump table slot in the
1471 // memory we allocated for the jump table in 'initJumpTableInfo'
1472 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1473 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1478 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1479 unsigned Alignment) {
1480 SavedBufferBegin = BufferBegin;
1481 SavedBufferEnd = BufferEnd;
1482 SavedCurBufferPtr = CurBufferPtr;
1484 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1485 BufferEnd = BufferBegin+StubSize+1;
1488 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1489 unsigned StubSize) {
1490 SavedBufferBegin = BufferBegin;
1491 SavedBufferEnd = BufferEnd;
1492 SavedCurBufferPtr = CurBufferPtr;
1494 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1495 BufferEnd = BufferBegin+StubSize+1;
1498 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1499 NumBytes += getCurrentPCOffset();
1500 std::swap(SavedBufferBegin, BufferBegin);
1501 BufferEnd = SavedBufferEnd;
1502 CurBufferPtr = SavedCurBufferPtr;
1503 return SavedBufferBegin;
1506 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1507 // in the constant pool that was last emitted with the 'emitConstantPool'
1510 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1511 assert(ConstantNum < ConstantPool->getConstants().size() &&
1512 "Invalid ConstantPoolIndex!");
1513 return ConstPoolAddresses[ConstantNum];
1516 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1517 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1519 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1520 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1521 assert(Index < JT.size() && "Invalid jump table index!");
1523 unsigned Offset = 0;
1524 unsigned EntrySize = JumpTable->getEntrySize();
1526 for (unsigned i = 0; i < Index; ++i)
1527 Offset += JT[i].MBBs.size();
1529 Offset *= EntrySize;
1531 return (uintptr_t)((char *)JumpTableBase + Offset);
1534 void JITEmitter::EmittedFunctionConfig::onDelete(
1535 JITEmitter *Emitter, const Function *F) {
1536 Emitter->deallocateMemForFunction(F);
1538 void JITEmitter::EmittedFunctionConfig::onRAUW(
1539 JITEmitter *, const Function*, const Function*) {
1540 llvm_unreachable("The JIT doesn't know how to handle a"
1541 " RAUW on a value it has emitted.");
1545 //===----------------------------------------------------------------------===//
1546 // Public interface to this file
1547 //===----------------------------------------------------------------------===//
1549 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1550 TargetMachine &tm) {
1551 return new JITEmitter(jit, JMM, tm);
1554 // getPointerToNamedFunction - This function is used as a global wrapper to
1555 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1556 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1557 // need to resolve function(s) that are being mis-codegenerated, so we need to
1558 // resolve their addresses at runtime, and this is the way to do it.
1560 void *getPointerToNamedFunction(const char *Name) {
1561 if (Function *F = TheJIT->FindFunctionNamed(Name))
1562 return TheJIT->getPointerToFunction(F);
1563 return TheJIT->getPointerToNamedFunction(Name);
1567 // getPointerToFunctionOrStub - If the specified function has been
1568 // code-gen'd, return a pointer to the function. If not, compile it, or use
1569 // a stub to implement lazy compilation if available.
1571 void *JIT::getPointerToFunctionOrStub(Function *F) {
1572 // If we have already code generated the function, just return the address.
1573 if (void *Addr = getPointerToGlobalIfAvailable(F))
1576 // Get a stub if the target supports it.
1577 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1578 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1579 return JE->getJITResolver().getFunctionStub(F);
1582 void JIT::updateFunctionStub(Function *F) {
1583 // Get the empty stub we generated earlier.
1584 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1585 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1586 void *Stub = JE->getJITResolver().getFunctionStub(F);
1588 // Tell the target jit info to rewrite the stub at the specified address,
1589 // rather than creating a new one.
1590 void *Addr = getPointerToGlobalIfAvailable(F);
1591 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1594 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1595 /// that were emitted during code generation.
1597 void JIT::updateDlsymStubTable() {
1598 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1599 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1601 SmallVector<GlobalValue*, 8> GVs;
1602 SmallVector<void*, 8> Ptrs;
1603 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1605 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1607 unsigned nStubs = GVs.size() + ExtFns.size();
1609 // If there are no relocatable stubs, return.
1613 // If there are no new relocatable stubs, return.
1614 void *CurTable = JE->getMemMgr()->getDlsymTable();
1615 if (CurTable && (*(unsigned *)CurTable == nStubs))
1618 // Calculate the size of the stub info
1619 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1621 SmallVector<unsigned, 8> Offsets;
1622 for (unsigned i = 0; i != GVs.size(); ++i) {
1623 Offsets.push_back(offset);
1624 offset += GVs[i]->getName().size() + 1;
1626 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1628 Offsets.push_back(offset);
1629 offset += strlen(i->first()) + 1;
1632 // Allocate space for the new "stub", which contains the dlsym table.
1633 JE->startGVStub(0, offset, 4);
1635 // Emit the number of records
1636 JE->emitInt32(nStubs);
1638 // Emit the string offsets
1639 for (unsigned i = 0; i != nStubs; ++i)
1640 JE->emitInt32(Offsets[i]);
1642 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1643 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1644 // relocation can write the relocated pointer at the appropriate place in
1646 for (unsigned i = 0; i != GVs.size(); ++i) {
1647 intptr_t Ptr = (intptr_t)Ptrs[i];
1648 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1650 if (isa<Function>(GVs[i]))
1653 if (sizeof(Ptr) == 8)
1658 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1660 intptr_t Ptr = (intptr_t)i->second | 1;
1662 if (sizeof(Ptr) == 8)
1668 // Emit the strings.
1669 for (unsigned i = 0; i != GVs.size(); ++i)
1670 JE->emitString(GVs[i]->getName());
1671 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1673 JE->emitString(i->first());
1675 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1676 // deallocate space for the old one, if one existed.
1677 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1680 /// freeMachineCodeForFunction - release machine code memory for given Function.
1682 void JIT::freeMachineCodeForFunction(Function *F) {
1683 // Delete translation for this from the ExecutionEngine, so it will get
1684 // retranslated next time it is used.
1685 updateGlobalMapping(F, 0);
1687 // Free the actual memory for the function body and related stuff.
1688 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1689 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);