getJITStubForFunction is optional and unimplemented, just remove it.
[oota-llvm.git] / lib / Target / PowerPC / PPCCodeEmitter.cpp
1 //===-- PPC32CodeEmitter.cpp - JIT Code Emitter for PowerPC32 -----*- C++ -*-=//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 // This file defines the PowerPC 32-bit CodeEmitter and associated machinery to
11 // JIT-compile bytecode to native PowerPC.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC32JITInfo.h"
16 #include "PPC32TargetMachine.h"
17 #include "PowerPC.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Support/Debug.h"
24 using namespace llvm;
25
26 namespace {
27   class JITResolver {
28     MachineCodeEmitter &MCE;
29
30     // LazyCodeGenMap - Keep track of call sites for functions that are to be
31     // lazily resolved.
32     std::map<unsigned, Function*> LazyCodeGenMap;
33
34     // LazyResolverMap - Keep track of the lazy resolver created for a
35     // particular function so that we can reuse them if necessary.
36     std::map<Function*, unsigned> LazyResolverMap;
37
38   public:
39     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
40     unsigned getLazyResolver(Function *F);
41     unsigned addFunctionReference(unsigned Address, Function *F);
42     
43   private:
44     unsigned emitStubForFunction(Function *F);
45     static void CompilationCallback();
46     unsigned resolveFunctionReference(unsigned RetAddr);
47   };
48
49   static JITResolver &getResolver(MachineCodeEmitter &MCE) {
50     static JITResolver *TheJITResolver = 0;
51     if (TheJITResolver == 0)
52       TheJITResolver = new JITResolver(MCE);
53     return *TheJITResolver;
54   }
55 }
56
57 unsigned JITResolver::getLazyResolver(Function *F) {
58   std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
59   if (I != LazyResolverMap.end() && I->first == F) return I->second;
60
61   unsigned Stub = emitStubForFunction(F);
62   LazyResolverMap.insert(I, std::make_pair(F, Stub));
63   return Stub;
64 }
65
66 /// addFunctionReference - This method is called when we need to emit the
67 /// address of a function that has not yet been emitted, so we don't know the
68 /// address.  Instead, we emit a call to the CompilationCallback method, and
69 /// keep track of where we are.
70 ///
71 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
72   LazyCodeGenMap[Address] = F;
73   return (intptr_t)&JITResolver::CompilationCallback;
74 }
75
76 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
77   std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
78   assert(I != LazyCodeGenMap.end() && "Not in map!");
79   Function *F = I->second;
80   LazyCodeGenMap.erase(I);
81   return MCE.forceCompilationOf(F);
82 }
83
84 /// emitStubForFunction - This method is used by the JIT when it needs to emit
85 /// the address of a function for a function whose code has not yet been
86 /// generated.  In order to do this, it generates a stub which jumps to the lazy
87 /// function compiler, which will eventually get fixed to call the function
88 /// directly.
89 ///
90 unsigned JITResolver::emitStubForFunction(Function *F) {
91   std::cerr << "PPC32CodeEmitter::emitStubForFunction() unimplemented!\n";
92   abort();
93   return 0;
94 }
95
96 void JITResolver::CompilationCallback() {
97   std::cerr << "PPC32CodeEmitter: CompilationCallback() unimplemented!";
98   abort();
99 }
100
101 namespace {
102   class PPC32CodeEmitter : public MachineFunctionPass {
103     TargetMachine &TM;
104     MachineCodeEmitter &MCE;
105
106     // Tracks which instruction references which BasicBlock
107     std::vector<std::pair<const BasicBlock*,
108                           std::pair<unsigned*,MachineInstr*> > > BBRefs;
109     // Tracks where each BasicBlock starts
110     std::map<const BasicBlock*, long> BBLocations;
111
112     /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
113     ///
114     int64_t getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
115
116     unsigned getAddressOfExternalFunction(Function *F);
117
118   public:
119     PPC32CodeEmitter(TargetMachine &T, MachineCodeEmitter &M) 
120       : TM(T), MCE(M) {}
121
122     const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
123
124     /// runOnMachineFunction - emits the given MachineFunction to memory
125     ///
126     bool runOnMachineFunction(MachineFunction &MF);
127
128     /// emitBasicBlock - emits the given MachineBasicBlock to memory
129     ///
130     void emitBasicBlock(MachineBasicBlock &MBB);
131
132     /// emitWord - write a 32-bit word to memory at the current PC
133     ///
134     void emitWord(unsigned w) { MCE.emitWord(w); }
135     
136     /// getValueBit - return the particular bit of Val
137     ///
138     unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
139
140     /// getBinaryCodeForInstr - This function, generated by the
141     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
142     /// machine instructions.
143     ///
144     unsigned getBinaryCodeForInstr(MachineInstr &MI);
145   };
146 }
147
148 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
149 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
150 /// actually outputting the machine code and resolving things like the address
151 /// of functions.  This method should returns true if machine code emission is
152 /// not supported.
153 ///
154 bool PPC32TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
155                                                     MachineCodeEmitter &MCE) {
156   // Keep as `true' until this is a functional JIT to allow llvm-gcc to build
157   return true;
158
159   // Machine code emitter pass for PowerPC
160   PM.add(new PPC32CodeEmitter(*this, MCE)); 
161   // Delete machine code for this function after emitting it
162   PM.add(createMachineCodeDeleter());
163   return false;
164 }
165
166 bool PPC32CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
167   MCE.startFunction(MF);
168   MCE.emitConstantPool(MF.getConstantPool());
169   for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
170     emitBasicBlock(*BB);
171   MCE.finishFunction(MF);
172
173   // Resolve branches to BasicBlocks for the entire function
174   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
175     long Location = BBLocations[BBRefs[i].first];
176     unsigned *Ref = BBRefs[i].second.first;
177     MachineInstr *MI = BBRefs[i].second.second;
178     DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
179                     << " in instr: " << std::dec << *MI);
180     for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
181       MachineOperand &op = MI->getOperand(ii);
182       if (op.isPCRelativeDisp()) {
183         // the instruction's branch target is made such that it branches to
184         // PC + (branchTarget * 4), so undo that arithmetic here:
185         // Location is the target of the branch
186         // Ref is the location of the instruction, and hence the PC
187         int64_t branchTarget = (Location - (long)Ref) >> 2;
188         MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
189                                    branchTarget);
190         unsigned fixedInstr = PPC32CodeEmitter::getBinaryCodeForInstr(*MI);
191         MCE.emitWordAt(fixedInstr, Ref);
192         break;
193       }
194     }
195   }
196   BBRefs.clear();
197   BBLocations.clear();
198
199   return false;
200 }
201
202 void PPC32CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
203   BBLocations[MBB.getBasicBlock()] = MCE.getCurrentPCValue();
204   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
205     MachineInstr &MI = *I;
206     unsigned Opcode = MI.getOpcode();
207     if (Opcode == PPC::IMPLICIT_DEF) 
208       continue; // pseudo opcode, no side effects
209     else if (Opcode == PPC::MovePCtoLR) {
210       // This can be simplified: the resulting 32-bit code is 0x48000005
211       MachineInstr *MI = BuildMI(PPC::BL, 1).addImm(1);
212       emitWord(getBinaryCodeForInstr(*MI));
213       delete MI;
214     } else
215       emitWord(getBinaryCodeForInstr(*I));
216   }
217 }
218
219 unsigned PPC32CodeEmitter::getAddressOfExternalFunction(Function *F) {
220   static std::map<Function*, unsigned> ExternalFn2Addr;
221   std::map<Function*, unsigned>::iterator Addr = ExternalFn2Addr.find(F);
222
223   if (Addr == ExternalFn2Addr.end())
224     ExternalFn2Addr[F] = MCE.forceCompilationOf(F);
225   return ExternalFn2Addr[F];
226 }
227
228 static unsigned enumRegToMachineReg(unsigned enumReg) {
229   switch (enumReg) {
230   case PPC::R0 :  case PPC::F0 :  return  0;  
231   case PPC::R1 :  case PPC::F1 :  return  1; 
232   case PPC::R2 :  case PPC::F2 :  return  2;
233   case PPC::R3 :  case PPC::F3 :  return  3; 
234   case PPC::R4 :  case PPC::F4 :  return  4; 
235   case PPC::R5 :  case PPC::F5 :  return  5;
236   case PPC::R6 :  case PPC::F6 :  return  6; 
237   case PPC::R7 :  case PPC::F7 :  return  7; 
238   case PPC::R8 :  case PPC::F8 :  return  8;
239   case PPC::R9 :  case PPC::F9 :  return  9; 
240   case PPC::R10:  case PPC::F10:  return 10; 
241   case PPC::R11:  case PPC::F11:  return 11;
242   case PPC::R12:  case PPC::F12:  return 12; 
243   case PPC::R13:  case PPC::F13:  return 13; 
244   case PPC::R14:  case PPC::F14:  return 14;
245   case PPC::R15:  case PPC::F15:  return 15; 
246   case PPC::R16:  case PPC::F16:  return 16; 
247   case PPC::R17:  case PPC::F17:  return 17;
248   case PPC::R18:  case PPC::F18:  return 18; 
249   case PPC::R19:  case PPC::F19:  return 19; 
250   case PPC::R20:  case PPC::F20:  return 20;
251   case PPC::R21:  case PPC::F21:  return 21;
252   case PPC::R22:  case PPC::F22:  return 22; 
253   case PPC::R23:  case PPC::F23:  return 23; 
254   case PPC::R24:  case PPC::F24:  return 24;
255   case PPC::R25:  case PPC::F25:  return 25; 
256   case PPC::R26:  case PPC::F26:  return 26; 
257   case PPC::R27:  case PPC::F27:  return 27;
258   case PPC::R28:  case PPC::F28:  return 28; 
259   case PPC::R29:  case PPC::F29:  return 29; 
260   case PPC::R30:  case PPC::F30:  return 30;
261   case PPC::R31:  case PPC::F31:  return 31;
262   default:
263     std::cerr << "Unhandled reg in enumRegToRealReg!\n";
264     abort();
265   }
266 }
267
268 int64_t PPC32CodeEmitter::getMachineOpValue(MachineInstr &MI, 
269                                             MachineOperand &MO) {
270   int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
271                   // or things that get fixed up later by the JIT.
272   if (MO.isRegister()) {
273     rv = enumRegToMachineReg(MO.getReg());
274   } else if (MO.isImmediate()) {
275     rv = MO.getImmedValue();
276   } else if (MO.isGlobalAddress()) {
277     GlobalValue *GV = MO.getGlobal();
278     rv = MCE.getGlobalValueAddress(GV);
279     if (rv == 0) {
280       if (Function *F = dyn_cast<Function>(GV)) {
281         if (F->isExternal())
282           rv = getAddressOfExternalFunction(F);
283         else {
284           // Function has not yet been code generated!  Use lazy resolution.
285           getResolver(MCE).addFunctionReference(MCE.getCurrentPCValue(), F);
286           rv = getResolver(MCE).getLazyResolver(F);
287         }
288       } else if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
289         if (GVar->isExternal()) {
290           rv = MCE.getGlobalValueAddress(MO.getSymbolName());
291           if (!rv) {
292             std::cerr << "PPC32CodeEmitter: External global addr not found: " 
293                       << *GVar;
294             abort();
295           }
296         } else {
297           std::cerr << "PPC32CodeEmitter: global addr not found: " << *GVar;
298           abort();
299         }
300       }
301     }
302     if (MO.isPCRelative()) { // Global variable reference
303       rv = (rv - MCE.getCurrentPCValue()) >> 2;
304     }
305   } else if (MO.isMachineBasicBlock()) {
306     const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
307     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
308     BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
309   } else if (MO.isConstantPoolIndex()) {
310     unsigned index = MO.getConstantPoolIndex();
311     rv = MCE.getConstantPoolEntryAddress(index);
312   } else if (MO.isFrameIndex()) {
313     std::cerr << "PPC32CodeEmitter: error: Frame index unhandled!\n";
314     abort();
315   } else {
316     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
317     abort();
318   }
319
320   // Special treatment for global symbols: constants and vars
321   if (MO.isConstantPoolIndex() || MO.isGlobalAddress()) {
322     unsigned Opcode = MI.getOpcode();
323     int64_t MBBLoc = BBLocations[MI.getParent()->getBasicBlock()];
324     if (Opcode == PPC::LOADHiAddr) {
325       // LoadHiAddr wants hi16(addr - mbb)
326       rv = (rv - MBBLoc) >> 16;
327     } else if (Opcode == PPC::LWZ || Opcode == PPC::LA ||
328                Opcode == PPC::LFS || Opcode == PPC::LFD) {
329       // These load opcodes want lo16(addr - mbb)
330       rv = (rv - MBBLoc) & 0xffff;
331     }
332   }
333
334   return rv;
335 }
336
337 void PPC32JITInfo::replaceMachineCodeForFunction (void *Old, void *New) {
338   std::cerr << "PPC32JITInfo::replaceMachineCodeForFunction not implemented\n";
339   abort();
340 }
341
342 #include "PPC32GenCodeEmitter.inc"
343