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 "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/System/Disassembler.h"
36 #include "llvm/System/Memory.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/Statistic.h"
43 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
44 STATISTIC(NumRelos, "Number of relocations applied");
45 static JIT *TheJIT = 0;
48 //===----------------------------------------------------------------------===//
49 // JIT lazy compilation code.
52 class JITResolverState {
54 /// FunctionToStubMap - Keep track of the stub created for a particular
55 /// function so that we can reuse them if necessary.
56 std::map<Function*, void*> FunctionToStubMap;
58 /// StubToFunctionMap - Keep track of the function that each stub
60 std::map<void*, Function*> StubToFunctionMap;
62 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
63 /// particular GlobalVariable so that we can reuse them if necessary.
64 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
67 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
68 assert(locked.holds(TheJIT->lock));
69 return FunctionToStubMap;
72 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
73 assert(locked.holds(TheJIT->lock));
74 return StubToFunctionMap;
77 std::map<GlobalValue*, void*>&
78 getGlobalToLazyPtrMap(const MutexGuard& locked) {
79 assert(locked.holds(TheJIT->lock));
80 return GlobalToLazyPtrMap;
84 /// JITResolver - Keep track of, and resolve, call sites for functions that
85 /// have not yet been compiled.
87 /// LazyResolverFn - The target lazy resolver function that we actually
88 /// rewrite instructions to use.
89 TargetJITInfo::LazyResolverFn LazyResolverFn;
91 JITResolverState state;
93 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
94 /// external functions.
95 std::map<void*, void*> ExternalFnToStubMap;
97 //map addresses to indexes in the GOT
98 std::map<void*, unsigned> revGOTMap;
99 unsigned nextGOTIndex;
101 static JITResolver *TheJITResolver;
103 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
106 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
107 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
108 TheJITResolver = this;
115 /// getFunctionStub - This returns a pointer to a function stub, creating
116 /// one on demand as needed.
117 void *getFunctionStub(Function *F);
119 /// getExternalFunctionStub - Return a stub for the function at the
120 /// specified address, created lazily on demand.
121 void *getExternalFunctionStub(void *FnAddr);
123 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
125 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
127 /// AddCallbackAtLocation - If the target is capable of rewriting an
128 /// instruction without the use of a stub, record the location of the use so
129 /// we know which function is being used at the location.
130 void *AddCallbackAtLocation(Function *F, void *Location) {
131 MutexGuard locked(TheJIT->lock);
132 /// Get the target-specific JIT resolver function.
133 state.getStubToFunctionMap(locked)[Location] = F;
134 return (void*)(intptr_t)LazyResolverFn;
137 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
138 /// an address. This function only manages slots, it does not manage the
139 /// contents of the slots or the memory associated with the GOT.
140 unsigned getGOTIndexForAddr(void *addr);
142 /// JITCompilerFn - This function is called to resolve a stub to a compiled
143 /// address. If the LLVM Function corresponding to the stub has not yet
144 /// been compiled, this function compiles it first.
145 static void *JITCompilerFn(void *Stub);
149 JITResolver *JITResolver::TheJITResolver = 0;
151 /// getFunctionStub - This returns a pointer to a function stub, creating
152 /// one on demand as needed.
153 void *JITResolver::getFunctionStub(Function *F) {
154 MutexGuard locked(TheJIT->lock);
156 // If we already have a stub for this function, recycle it.
157 void *&Stub = state.getFunctionToStubMap(locked)[F];
158 if (Stub) return Stub;
160 // Call the lazy resolver function unless we already KNOW it is an external
161 // function, in which case we just skip the lazy resolution step.
162 void *Actual = (void*)(intptr_t)LazyResolverFn;
163 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
164 Actual = TheJIT->getPointerToFunction(F);
166 // Otherwise, codegen a new stub. For now, the stub will call the lazy
167 // resolver function.
168 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
169 *TheJIT->getCodeEmitter());
171 if (Actual != (void*)(intptr_t)LazyResolverFn) {
172 // If we are getting the stub for an external function, we really want the
173 // address of the stub in the GlobalAddressMap for the JIT, not the address
174 // of the external function.
175 TheJIT->updateGlobalMapping(F, Stub);
178 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
179 << F->getName() << "'\n";
181 // Finally, keep track of the stub-to-Function mapping so that the
182 // JITCompilerFn knows which function to compile!
183 state.getStubToFunctionMap(locked)[Stub] = F;
187 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
189 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
190 MutexGuard locked(TheJIT->lock);
192 // If we already have a stub for this global variable, recycle it.
193 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
194 if (LazyPtr) return LazyPtr;
196 // Otherwise, codegen a new lazy pointer.
197 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
198 *TheJIT->getCodeEmitter());
200 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
201 << GV->getName() << "'\n";
206 /// getExternalFunctionStub - Return a stub for the function at the
207 /// specified address, created lazily on demand.
208 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
209 // If we already have a stub for this function, recycle it.
210 void *&Stub = ExternalFnToStubMap[FnAddr];
211 if (Stub) return Stub;
213 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
214 *TheJIT->getCodeEmitter());
216 DOUT << "JIT: Stub emitted at [" << Stub
217 << "] for external function at '" << FnAddr << "'\n";
221 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
222 unsigned idx = revGOTMap[addr];
224 idx = ++nextGOTIndex;
225 revGOTMap[addr] = idx;
226 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
231 /// JITCompilerFn - This function is called when a lazy compilation stub has
232 /// been entered. It looks up which function this stub corresponds to, compiles
233 /// it if necessary, then returns the resultant function pointer.
234 void *JITResolver::JITCompilerFn(void *Stub) {
235 JITResolver &JR = *TheJITResolver;
237 MutexGuard locked(TheJIT->lock);
239 // The address given to us for the stub may not be exactly right, it might be
240 // a little bit after the stub. As such, use upper_bound to find it.
241 std::map<void*, Function*>::iterator I =
242 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
243 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
244 "This is not a known stub!");
245 Function *F = (--I)->second;
247 // If we have already code generated the function, just return the address.
248 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
251 // Otherwise we don't have it, do lazy compilation now.
253 // If lazy compilation is disabled, emit a useful error message and abort.
254 if (TheJIT->isLazyCompilationDisabled()) {
255 cerr << "LLVM JIT requested to do lazy compilation of function '"
256 << F->getName() << "' when lazy compiles are disabled!\n";
260 // We might like to remove the stub from the StubToFunction map.
261 // We can't do that! Multiple threads could be stuck, waiting to acquire the
262 // lock above. As soon as the 1st function finishes compiling the function,
263 // the next one will be released, and needs to be able to find the function
265 //JR.state.getStubToFunctionMap(locked).erase(I);
267 DOUT << "JIT: Lazily resolving function '" << F->getName()
268 << "' In stub ptr = " << Stub << " actual ptr = "
271 Result = TheJIT->getPointerToFunction(F);
274 // We don't need to reuse this stub in the future, as F is now compiled.
275 JR.state.getFunctionToStubMap(locked).erase(F);
277 // FIXME: We could rewrite all references to this stub if we knew them.
279 // What we will do is set the compiled function address to map to the
280 // same GOT entry as the stub so that later clients may update the GOT
281 // if they see it still using the stub address.
282 // Note: this is done so the Resolver doesn't have to manage GOT memory
283 // Do this without allocating map space if the target isn't using a GOT
284 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
285 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
290 //===----------------------------------------------------------------------===//
291 // Function Index Support
293 // On MacOS we generate an index of currently JIT'd functions so that
294 // performance tools can determine a symbol name and accurate code range for a
295 // PC value. Because performance tools are generally asynchronous, the code
296 // below is written with the hope that it could be interrupted at any time and
297 // have useful answers. However, we don't go crazy with atomic operations, we
298 // just do a "reasonable effort".
300 #define ENABLE_JIT_SYMBOL_TABLE 0
303 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
304 /// being added to an array of symbols. This indicates the name of the function
305 /// as well as the address range it occupies. This allows the client to map
306 /// from a PC value to the name of the function.
307 struct JitSymbolEntry {
308 const char *FnName; // FnName - a strdup'd string.
314 struct JitSymbolTable {
315 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
316 /// pointer is not used right now, but might be used in the future. Consider
317 /// it reserved for future use.
318 JitSymbolTable *NextPtr;
320 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
321 /// 'NumSymbols' symbols are valid.
322 JitSymbolEntry *Symbols;
324 /// NumSymbols - This indicates the number entries in the Symbols array that
328 /// NumAllocated - This indicates the amount of space we have in the Symbols
329 /// array. This is a private field that should not be read by external tools.
330 unsigned NumAllocated;
333 #if ENABLE_JIT_SYMBOL_TABLE
334 JitSymbolTable *__jitSymbolTable;
337 static void AddFunctionToSymbolTable(const char *FnName,
338 void *FnStart, intptr_t FnSize) {
339 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
340 JitSymbolTable **SymTabPtrPtr = 0;
341 #if !ENABLE_JIT_SYMBOL_TABLE
344 SymTabPtrPtr = &__jitSymbolTable;
347 // If this is the first entry in the symbol table, add the JitSymbolTable
349 if (*SymTabPtrPtr == 0) {
350 JitSymbolTable *New = new JitSymbolTable();
354 New->NumAllocated = 0;
358 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
360 // If we have space in the table, reallocate the table.
361 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
362 // If we don't have space, reallocate the table.
363 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
364 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
365 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
367 // Copy the old entries over.
368 memcpy(NewSymbols, OldSymbols,
369 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
371 // Swap the new symbols in, delete the old ones.
372 SymTabPtr->Symbols = NewSymbols;
373 SymTabPtr->NumAllocated = NewSize;
374 delete [] OldSymbols;
377 // Otherwise, we have enough space, just tack it onto the end of the array.
378 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
379 Entry.FnName = strdup(FnName);
380 Entry.FnStart = FnStart;
381 Entry.FnSize = FnSize;
382 ++SymTabPtr->NumSymbols;
385 static void RemoveFunctionFromSymbolTable(void *FnStart) {
386 assert(FnStart && "Invalid function pointer");
387 JitSymbolTable **SymTabPtrPtr = 0;
388 #if !ENABLE_JIT_SYMBOL_TABLE
391 SymTabPtrPtr = &__jitSymbolTable;
394 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
395 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
397 // Scan the table to find its index. The table is not sorted, so do a linear
400 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
401 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
403 // Once we have an index, we know to nuke this entry, overwrite it with the
404 // entry at the end of the array, making the last entry redundant.
405 const char *OldName = Symbols[Index].FnName;
406 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
407 free((void*)OldName);
409 // Drop the number of symbols in the table.
410 --SymTabPtr->NumSymbols;
412 // Finally, if we deleted the final symbol, deallocate the table itself.
413 if (SymTabPtr->NumSymbols != 0)
421 //===----------------------------------------------------------------------===//
425 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
426 /// used to output functions to memory for execution.
427 class JITEmitter : public MachineCodeEmitter {
428 JITMemoryManager *MemMgr;
430 // When outputting a function stub in the context of some other function, we
431 // save BufferBegin/BufferEnd/CurBufferPtr here.
432 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
434 /// Relocations - These are the relocations that the function needs, as
436 std::vector<MachineRelocation> Relocations;
438 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
439 /// It is filled in by the StartMachineBasicBlock callback and queried by
440 /// the getMachineBasicBlockAddress callback.
441 std::vector<intptr_t> MBBLocations;
443 /// ConstantPool - The constant pool for the current function.
445 MachineConstantPool *ConstantPool;
447 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
449 void *ConstantPoolBase;
451 /// JumpTable - The jump tables for the current function.
453 MachineJumpTableInfo *JumpTable;
455 /// JumpTableBase - A pointer to the first entry in the jump table.
459 /// Resolver - This contains info about the currently resolved functions.
460 JITResolver Resolver;
462 /// DE - The dwarf emitter for the jit.
465 /// LabelLocations - This vector is a mapping from Label ID's to their
467 std::vector<intptr_t> LabelLocations;
469 /// MMI - Machine module info for exception informations
470 MachineModuleInfo* MMI;
472 // GVSet - a set to keep track of which globals have been seen
473 std::set<const GlobalVariable*> GVSet;
476 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
477 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
478 if (jit.getJITInfo().needsGOT()) {
479 MemMgr->AllocateGOT();
480 DOUT << "JIT is managing a GOT\n";
483 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
487 if (ExceptionHandling) delete DE;
490 JITResolver &getJITResolver() { return Resolver; }
492 virtual void startFunction(MachineFunction &F);
493 virtual bool finishFunction(MachineFunction &F);
495 void emitConstantPool(MachineConstantPool *MCP);
496 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
497 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
499 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
500 unsigned Alignment = 1);
501 virtual void* finishFunctionStub(const GlobalValue *F);
503 virtual void addRelocation(const MachineRelocation &MR) {
504 Relocations.push_back(MR);
507 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
508 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
509 MBBLocations.resize((MBB->getNumber()+1)*2);
510 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
513 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
514 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
516 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
517 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
518 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
519 return MBBLocations[MBB->getNumber()];
522 /// deallocateMemForFunction - Deallocate all memory for the specified
524 void deallocateMemForFunction(Function *F) {
525 MemMgr->deallocateMemForFunction(F);
528 virtual void emitLabel(uint64_t LabelID) {
529 if (LabelLocations.size() <= LabelID)
530 LabelLocations.resize((LabelID+1)*2);
531 LabelLocations[LabelID] = getCurrentPCValue();
534 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
535 assert(LabelLocations.size() > (unsigned)LabelID &&
536 LabelLocations[LabelID] && "Label not emitted!");
537 return LabelLocations[LabelID];
540 virtual void setModuleInfo(MachineModuleInfo* Info) {
542 if (ExceptionHandling) DE->setModuleInfo(Info);
546 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
547 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
549 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
550 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
551 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
552 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
556 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
557 bool DoesntNeedStub) {
558 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
559 /// FIXME: If we straightened things out, this could actually emit the
560 /// global immediately instead of queuing it for codegen later!
561 return TheJIT->getOrEmitGlobalVariable(GV);
563 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
564 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal());
566 // If we have already compiled the function, return a pointer to its body.
567 Function *F = cast<Function>(V);
568 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
569 if (ResultPtr) return ResultPtr;
571 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
572 // If this is an external function pointer, we can force the JIT to
573 // 'compile' it, which really just adds it to the map.
575 return TheJIT->getPointerToFunction(F);
577 return Resolver.getFunctionStub(F);
580 // Okay, the function has not been compiled yet, if the target callback
581 // mechanism is capable of rewriting the instruction directly, prefer to do
582 // that instead of emitting a stub.
584 return Resolver.AddCallbackAtLocation(F, Reference);
586 // Otherwise, we have to emit a lazy resolving stub.
587 return Resolver.getFunctionStub(F);
590 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
591 bool DoesntNeedStub) {
592 // Make sure GV is emitted first.
593 // FIXME: For now, if the GV is an external function we force the JIT to
594 // compile it so the lazy pointer will contain the fully resolved address.
595 void *GVAddress = getPointerToGlobal(V, Reference, true);
596 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
599 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
600 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
601 if (Constants.empty()) return 0;
603 MachineConstantPoolEntry CPE = Constants.back();
604 unsigned Size = CPE.Offset;
605 const Type *Ty = CPE.isMachineConstantPoolEntry()
606 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
607 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
611 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
612 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
613 if (JT.empty()) return 0;
615 unsigned NumEntries = 0;
616 for (unsigned i = 0, e = JT.size(); i != e; ++i)
617 NumEntries += JT[i].MBBs.size();
619 unsigned EntrySize = MJTI->getEntrySize();
621 return NumEntries * EntrySize;
624 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
625 if (Alignment == 0) Alignment = 1;
626 // Since we do not know where the buffer will be allocated, be pessimistic.
627 return Size + Alignment;
630 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
631 /// into the running total Size.
633 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
634 const Type *ElTy = GV->getType()->getElementType();
635 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
637 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
638 DOUT << "Adding in size " << GVSize << " alignment " << GVAlign;
640 // Assume code section ends with worst possible alignment, so first
641 // variable needs maximal padding.
644 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
649 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
650 /// but are referenced from the constant; put them in GVSet and add their
651 /// size into the running total Size.
653 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
655 // If its undefined, return the garbage.
656 if (isa<UndefValue>(C))
659 // If the value is a ConstantExpr
660 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
661 Constant *Op0 = CE->getOperand(0);
662 switch (CE->getOpcode()) {
663 case Instruction::GetElementPtr:
664 case Instruction::Trunc:
665 case Instruction::ZExt:
666 case Instruction::SExt:
667 case Instruction::FPTrunc:
668 case Instruction::FPExt:
669 case Instruction::UIToFP:
670 case Instruction::SIToFP:
671 case Instruction::FPToUI:
672 case Instruction::FPToSI:
673 case Instruction::PtrToInt:
674 case Instruction::IntToPtr:
675 case Instruction::BitCast: {
676 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
679 case Instruction::Add:
680 case Instruction::Sub:
681 case Instruction::Mul:
682 case Instruction::UDiv:
683 case Instruction::SDiv:
684 case Instruction::URem:
685 case Instruction::SRem:
686 case Instruction::And:
687 case Instruction::Or:
688 case Instruction::Xor: {
689 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
690 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
694 cerr << "ConstantExpr not handled: " << *CE << "\n";
700 if (C->getType()->getTypeID() == Type::PointerTyID)
701 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
702 if (GVSet.insert(GV).second)
703 Size = addSizeOfGlobal(GV, Size);
708 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
709 /// but are referenced from the given initializer.
711 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
713 if (!isa<UndefValue>(Init) &&
714 !isa<ConstantVector>(Init) &&
715 !isa<ConstantAggregateZero>(Init) &&
716 !isa<ConstantArray>(Init) &&
717 !isa<ConstantStruct>(Init) &&
718 Init->getType()->isFirstClassType())
719 Size = addSizeOfGlobalsInConstantVal(Init, Size);
723 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
724 /// globals; then walk the initializers of those globals looking for more.
725 /// If their size has not been considered yet, add it into the running total
728 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
732 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
734 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
736 const TargetInstrDesc &Desc = I->getDesc();
737 const MachineInstr &MI = *I;
738 unsigned NumOps = Desc.getNumOperands();
739 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
740 const MachineOperand &MO = MI.getOperand(CurOp);
741 if (MO.isGlobalAddress()) {
742 GlobalValue* V = MO.getGlobal();
743 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
746 // If seen in previous function, it will have an entry here.
747 if (TheJIT->getPointerToGlobalIfAvailable(GV))
749 // If seen earlier in this function, it will have an entry here.
750 // FIXME: it should be possible to combine these tables, by
751 // assuming the addresses of the new globals in this module
752 // start at 0 (or something) and adjusting them after codegen
753 // complete. Another possibility is to grab a marker bit in GV.
754 if (GVSet.insert(GV).second)
755 // A variable as yet unseen. Add in its size.
756 Size = addSizeOfGlobal(GV, Size);
761 DOUT << "About to look through initializers\n";
762 // Look for more globals that are referenced only from initializers.
763 // GVSet.end is computed each time because the set can grow as we go.
764 for (std::set<const GlobalVariable *>::iterator I = GVSet.begin();
765 I != GVSet.end(); I++) {
766 const GlobalVariable* GV = *I;
767 if (GV->hasInitializer())
768 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
774 void JITEmitter::startFunction(MachineFunction &F) {
775 uintptr_t ActualSize = 0;
776 if (MemMgr->NeedsExactSize()) {
777 DOUT << "ExactSize\n";
778 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
779 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
780 MachineConstantPool *MCP = F.getConstantPool();
782 // Ensure the constant pool/jump table info is at least 4-byte aligned.
783 ActualSize = RoundUpToAlign(ActualSize, 16);
785 // Add the alignment of the constant pool
786 ActualSize = RoundUpToAlign(ActualSize,
787 1 << MCP->getConstantPoolAlignment());
789 // Add the constant pool size
790 ActualSize += GetConstantPoolSizeInBytes(MCP);
792 // Add the aligment of the jump table info
793 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
795 // Add the jump table size
796 ActualSize += GetJumpTableSizeInBytes(MJTI);
798 // Add the alignment for the function
799 ActualSize = RoundUpToAlign(ActualSize,
800 std::max(F.getFunction()->getAlignment(), 8U));
802 // Add the function size
803 ActualSize += TII->GetFunctionSizeInBytes(F);
805 DOUT << "ActualSize before globals " << ActualSize << "\n";
806 // Add the size of the globals that will be allocated after this function.
807 // These are all the ones referenced from this function that were not
808 // previously allocated.
809 ActualSize += GetSizeOfGlobalsInBytes(F);
810 DOUT << "ActualSize after globals " << ActualSize << "\n";
813 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
815 BufferEnd = BufferBegin+ActualSize;
817 // Ensure the constant pool/jump table info is at least 4-byte aligned.
820 emitConstantPool(F.getConstantPool());
821 initJumpTableInfo(F.getJumpTableInfo());
823 // About to start emitting the machine code for the function.
824 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
825 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
827 MBBLocations.clear();
830 bool JITEmitter::finishFunction(MachineFunction &F) {
831 if (CurBufferPtr == BufferEnd) {
832 // FIXME: Allocate more space, then try again.
833 cerr << "JIT: Ran out of space for generated machine code!\n";
837 emitJumpTableInfo(F.getJumpTableInfo());
839 // FnStart is the start of the text, not the start of the constant pool and
840 // other per-function data.
841 unsigned char *FnStart =
842 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
844 if (!Relocations.empty()) {
845 NumRelos += Relocations.size();
847 // Resolve the relocations to concrete pointers.
848 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
849 MachineRelocation &MR = Relocations[i];
852 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
854 // If the target REALLY wants a stub for this function, emit it now.
855 if (!MR.doesntNeedStub())
856 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
857 } else if (MR.isGlobalValue()) {
858 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
859 BufferBegin+MR.getMachineCodeOffset(),
860 MR.doesntNeedStub());
861 } else if (MR.isGlobalValueLazyPtr()) {
862 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
863 BufferBegin+MR.getMachineCodeOffset(),
864 MR.doesntNeedStub());
865 } else if (MR.isBasicBlock()) {
866 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
867 } else if (MR.isConstantPoolIndex()) {
868 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
870 assert(MR.isJumpTableIndex());
871 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
874 MR.setResultPointer(ResultPtr);
876 // if we are managing the GOT and the relocation wants an index,
878 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
879 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
881 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
882 DOUT << "GOT was out of date for " << ResultPtr
883 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
885 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
890 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
891 Relocations.size(), MemMgr->getGOTBase());
894 unsigned char *FnEnd = CurBufferPtr;
896 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
897 NumBytes += FnEnd-FnStart;
899 // Update the GOT entry for F to point to the new code.
900 if (MemMgr->isManagingGOT()) {
901 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
902 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
903 DOUT << "GOT was out of date for " << (void*)BufferBegin
904 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
905 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
909 // Invalidate the icache if necessary.
910 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
912 // Add it to the JIT symbol table if the host wants it.
913 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
914 FnStart, FnEnd-FnStart);
916 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
917 << "] Function: " << F.getFunction()->getName()
918 << ": " << (FnEnd-FnStart) << " bytes of text, "
919 << Relocations.size() << " relocations\n";
926 unsigned char* q = FnStart;
927 for (i=1; q!=FnEnd; q++, i++) {
929 DOUT << "0x" << (long)q << ": ";
930 DOUT<< (unsigned short)*q << " ";
935 if (sys::hasDisassembler())
936 DOUT << "Disassembled code:\n"
937 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
940 if (ExceptionHandling) {
941 uintptr_t ActualSize = 0;
942 SavedBufferBegin = BufferBegin;
943 SavedBufferEnd = BufferEnd;
944 SavedCurBufferPtr = CurBufferPtr;
946 if (MemMgr->NeedsExactSize()) {
947 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
950 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
952 BufferEnd = BufferBegin+ActualSize;
953 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
954 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
956 BufferBegin = SavedBufferBegin;
957 BufferEnd = SavedBufferEnd;
958 CurBufferPtr = SavedCurBufferPtr;
960 TheJIT->RegisterTable(FrameRegister);
967 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
968 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
969 if (Constants.empty()) return;
971 MachineConstantPoolEntry CPE = Constants.back();
972 unsigned Size = CPE.Offset;
973 const Type *Ty = CPE.isMachineConstantPoolEntry()
974 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
975 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
977 unsigned Align = 1 << MCP->getConstantPoolAlignment();
978 ConstantPoolBase = allocateSpace(Size, Align);
981 if (ConstantPoolBase == 0) return; // Buffer overflow.
983 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
984 << "] (size: " << Size << ", alignment: " << Align << ")\n";
986 // Initialize the memory for all of the constant pool entries.
987 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
988 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
989 if (Constants[i].isMachineConstantPoolEntry()) {
990 // FIXME: add support to lower machine constant pool values into bytes!
991 cerr << "Initialize memory with machine specific constant pool entry"
992 << " has not been implemented!\n";
995 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
996 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1000 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1001 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1002 if (JT.empty()) return;
1004 unsigned NumEntries = 0;
1005 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1006 NumEntries += JT[i].MBBs.size();
1008 unsigned EntrySize = MJTI->getEntrySize();
1010 // Just allocate space for all the jump tables now. We will fix up the actual
1011 // MBB entries in the tables after we emit the code for each block, since then
1012 // we will know the final locations of the MBBs in memory.
1014 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1017 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1018 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1019 if (JT.empty() || JumpTableBase == 0) return;
1021 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1022 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1023 // For each jump table, place the offset from the beginning of the table
1024 // to the target address.
1025 int *SlotPtr = (int*)JumpTableBase;
1027 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1028 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1029 // Store the offset of the basic block for this jump table slot in the
1030 // memory we allocated for the jump table in 'initJumpTableInfo'
1031 intptr_t Base = (intptr_t)SlotPtr;
1032 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1033 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1034 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1038 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1040 // For each jump table, map each target in the jump table to the address of
1041 // an emitted MachineBasicBlock.
1042 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1044 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1045 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1046 // Store the address of the basic block for this jump table slot in the
1047 // memory we allocated for the jump table in 'initJumpTableInfo'
1048 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1049 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1054 void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
1055 unsigned Alignment) {
1056 SavedBufferBegin = BufferBegin;
1057 SavedBufferEnd = BufferEnd;
1058 SavedCurBufferPtr = CurBufferPtr;
1060 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
1061 BufferEnd = BufferBegin+StubSize+1;
1064 void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
1065 NumBytes += getCurrentPCOffset();
1066 std::swap(SavedBufferBegin, BufferBegin);
1067 BufferEnd = SavedBufferEnd;
1068 CurBufferPtr = SavedCurBufferPtr;
1069 return SavedBufferBegin;
1072 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1073 // in the constant pool that was last emitted with the 'emitConstantPool'
1076 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1077 assert(ConstantNum < ConstantPool->getConstants().size() &&
1078 "Invalid ConstantPoolIndex!");
1079 return (intptr_t)ConstantPoolBase +
1080 ConstantPool->getConstants()[ConstantNum].Offset;
1083 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1084 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1086 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1087 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1088 assert(Index < JT.size() && "Invalid jump table index!");
1090 unsigned Offset = 0;
1091 unsigned EntrySize = JumpTable->getEntrySize();
1093 for (unsigned i = 0; i < Index; ++i)
1094 Offset += JT[i].MBBs.size();
1096 Offset *= EntrySize;
1098 return (intptr_t)((char *)JumpTableBase + Offset);
1101 //===----------------------------------------------------------------------===//
1102 // Public interface to this file
1103 //===----------------------------------------------------------------------===//
1105 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1106 return new JITEmitter(jit, JMM);
1109 // getPointerToNamedFunction - This function is used as a global wrapper to
1110 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1111 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1112 // need to resolve function(s) that are being mis-codegenerated, so we need to
1113 // resolve their addresses at runtime, and this is the way to do it.
1115 void *getPointerToNamedFunction(const char *Name) {
1116 if (Function *F = TheJIT->FindFunctionNamed(Name))
1117 return TheJIT->getPointerToFunction(F);
1118 return TheJIT->getPointerToNamedFunction(Name);
1122 // getPointerToFunctionOrStub - If the specified function has been
1123 // code-gen'd, return a pointer to the function. If not, compile it, or use
1124 // a stub to implement lazy compilation if available.
1126 void *JIT::getPointerToFunctionOrStub(Function *F) {
1127 // If we have already code generated the function, just return the address.
1128 if (void *Addr = getPointerToGlobalIfAvailable(F))
1131 // Get a stub if the target supports it.
1132 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
1133 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1134 return JE->getJITResolver().getFunctionStub(F);
1137 /// freeMachineCodeForFunction - release machine code memory for given Function.
1139 void JIT::freeMachineCodeForFunction(Function *F) {
1141 // Delete translation for this from the ExecutionEngine, so it will get
1142 // retranslated next time it is used.
1143 void *OldPtr = updateGlobalMapping(F, 0);
1146 RemoveFunctionFromSymbolTable(OldPtr);
1148 // Free the actual memory for the function body and related stuff.
1149 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
1150 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);