Move some knowledge about registers out of the code emitter into the register info.
[oota-llvm.git] / lib / Target / PowerPC / PPCCodeEmitter.cpp
1 //===-- PPCCodeEmitter.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 "PPCTargetMachine.h"
16 #include "PPCRelocations.h"
17 #include "PPC.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include <iostream>
27 using namespace llvm;
28
29 namespace {
30   class PPCCodeEmitter : public MachineFunctionPass {
31     TargetMachine &TM;
32     MachineCodeEmitter &MCE;
33
34     // Tracks which instruction references which BasicBlock
35     std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs;
36     // Tracks where each BasicBlock starts
37     std::map<MachineBasicBlock*, long> BBLocations;
38
39     /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
40     ///
41     int getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
42
43   public:
44     PPCCodeEmitter(TargetMachine &T, MachineCodeEmitter &M)
45       : TM(T), MCE(M) {}
46
47     const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
48
49     /// runOnMachineFunction - emits the given MachineFunction to memory
50     ///
51     bool runOnMachineFunction(MachineFunction &MF);
52
53     /// emitBasicBlock - emits the given MachineBasicBlock to memory
54     ///
55     void emitBasicBlock(MachineBasicBlock &MBB);
56
57     /// emitWord - write a 32-bit word to memory at the current PC
58     ///
59     void emitWord(unsigned w) { MCE.emitWord(w); }
60
61     /// getValueBit - return the particular bit of Val
62     ///
63     unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
64
65     /// getBinaryCodeForInstr - This function, generated by the
66     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
67     /// machine instructions.
68     ///
69     unsigned getBinaryCodeForInstr(MachineInstr &MI);
70   };
71 }
72
73 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
74 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
75 /// actually outputting the machine code and resolving things like the address
76 /// of functions.  This method should returns true if machine code emission is
77 /// not supported.
78 ///
79 bool PPCTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
80                                                   MachineCodeEmitter &MCE) {
81   // Machine code emitter pass for PowerPC
82   PM.add(new PPCCodeEmitter(*this, MCE));
83   // Delete machine code for this function after emitting it
84   PM.add(createMachineCodeDeleter());
85   return false;
86 }
87
88 bool PPCCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
89   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
90           MF.getTarget().getRelocationModel() != Reloc::Static) &&
91          "JIT relocation model must be set to static or default!");
92   MCE.startFunction(MF);
93   MCE.emitConstantPool(MF.getConstantPool());
94   for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
95     emitBasicBlock(*BB);
96   MCE.finishFunction(MF);
97
98   // Resolve branches to BasicBlocks for the entire function
99   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
100     intptr_t Location = BBLocations[BBRefs[i].first];
101     unsigned *Ref = BBRefs[i].second;
102     DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location
103                     << "\n");
104     unsigned Instr = *Ref;
105     intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2;
106
107     switch (Instr >> 26) {
108     default: assert(0 && "Unknown branch user!");
109     case 18:  // This is B or BL
110       *Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2;
111       break;
112     case 16:  // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction
113       *Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2;
114       break;
115     }
116   }
117   BBRefs.clear();
118   BBLocations.clear();
119
120   return false;
121 }
122
123 void PPCCodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
124   BBLocations[&MBB] = MCE.getCurrentPCValue();
125   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
126     MachineInstr &MI = *I;
127     unsigned Opcode = MI.getOpcode();
128     switch (MI.getOpcode()) {
129     default:
130       emitWord(getBinaryCodeForInstr(*I));
131       break;
132     case PPC::IMPLICIT_DEF_GPR:
133     case PPC::IMPLICIT_DEF_F8:
134     case PPC::IMPLICIT_DEF_F4:
135     case PPC::IMPLICIT_DEF_VRRC:
136       break; // pseudo opcode, no side effects
137     case PPC::MovePCtoLR:
138       assert(0 && "CodeEmitter does not support MovePCtoLR instruction");
139       break;
140     }
141   }
142 }
143
144 int PPCCodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) {
145
146   int rv = 0; // Return value; defaults to 0 for unhandled cases
147                   // or things that get fixed up later by the JIT.
148   if (MO.isRegister()) {
149     rv = PPCRegisterInfo::getRegisterNumbering(MO.getReg());
150
151     // Special encoding for MTCRF and MFOCRF, which uses a bit mask for the
152     // register, not the register number directly.
153     if ((MI.getOpcode() == PPC::MTCRF || MI.getOpcode() == PPC::MFOCRF) &&
154         (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7)) {
155       rv = 0x80 >> rv;
156     }
157   } else if (MO.isImmediate()) {
158     rv = MO.getImmedValue();
159   } else if (MO.isGlobalAddress() || MO.isExternalSymbol()) {
160     bool isExternal = MO.isExternalSymbol() ||
161                       MO.getGlobal()->hasWeakLinkage() ||
162                       MO.getGlobal()->hasLinkOnceLinkage() ||
163                       (MO.getGlobal()->isExternal() &&
164                        !MO.getGlobal()->hasNotBeenReadFromBytecode());
165     unsigned Reloc = 0;
166     if (MI.getOpcode() == PPC::BL)
167       Reloc = PPC::reloc_pcrel_bx;
168     else {
169       switch (MI.getOpcode()) {
170       default: MI.dump(); assert(0 && "Unknown instruction for relocation!");
171       case PPC::LIS:
172         if (isExternal)
173           Reloc = PPC::reloc_absolute_ptr_high;   // Pointer to stub
174         else
175           Reloc = PPC::reloc_absolute_high;       // Pointer to symbol
176         break;
177       case PPC::LA:
178         assert(!isExternal && "Something in the ISEL changed\n");
179         Reloc = PPC::reloc_absolute_low;
180         break;
181       case PPC::LBZ:
182       case PPC::LHA:
183       case PPC::LHZ:
184       case PPC::LWZ:
185       case PPC::LFS:
186       case PPC::LFD:
187       case PPC::STB:
188       case PPC::STH:
189       case PPC::STW:
190       case PPC::STFS:
191       case PPC::STFD:
192         if (isExternal)
193           Reloc = PPC::reloc_absolute_ptr_low;
194         else
195           Reloc = PPC::reloc_absolute_low;
196         break;
197       }
198     }
199     if (MO.isGlobalAddress())
200       MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
201                                           Reloc, MO.getGlobal(), 0));
202     else
203       MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
204                                           Reloc, MO.getSymbolName(), 0));
205   } else if (MO.isMachineBasicBlock()) {
206     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
207     BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC));
208   } else if (MO.isConstantPoolIndex()) {
209     unsigned index = MO.getConstantPoolIndex();
210     unsigned Opcode = MI.getOpcode();
211     rv = MCE.getConstantPoolEntryAddress(index);
212     if (Opcode == PPC::LIS || Opcode == PPC::ADDIS) {
213       // lis wants hi16(addr)
214       if ((short)rv < 0) rv += 1 << 16;
215       rv >>= 16;
216     } else if (Opcode == PPC::LWZ || Opcode == PPC::LA ||
217                Opcode == PPC::LI ||
218                Opcode == PPC::LFS || Opcode == PPC::LFD) {
219       // These load opcodes want lo16(addr)
220       rv &= 0xffff;
221     } else {
222       assert(0 && "Unknown constant pool using instruction!");
223     }
224   } else {
225     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
226     abort();
227   }
228
229   return rv;
230 }
231
232 #include "PPCGenCodeEmitter.inc"
233