Move some more instruction creation methods from RegisterInfo into InstrInfo.
[oota-llvm.git] / lib / CodeGen / RegAllocSimple.cpp
1 //===-- RegAllocSimple.cpp - A simple generic register allocator ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple register allocator. *Very* simple: It immediate
11 // spills every value right after it is computed, and it reloads all used
12 // operands from the spill area to temporary registers before each instruction.
13 // It does not keep values in registers across instructions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "regalloc"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 using namespace llvm;
31
32 STATISTIC(NumStores, "Number of stores added");
33 STATISTIC(NumLoads , "Number of loads added");
34
35 namespace {
36   static RegisterRegAlloc
37     simpleRegAlloc("simple", "  simple register allocator",
38                    createSimpleRegisterAllocator);
39
40   class VISIBILITY_HIDDEN RegAllocSimple : public MachineFunctionPass {
41   public:
42     static char ID;
43     RegAllocSimple() : MachineFunctionPass((intptr_t)&ID) {}
44   private:
45     MachineFunction *MF;
46     const TargetMachine *TM;
47     const MRegisterInfo *MRI;
48
49     // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
50     // these values are spilled
51     std::map<unsigned, int> StackSlotForVirtReg;
52
53     // RegsUsed - Keep track of what registers are currently in use.  This is a
54     // bitset.
55     std::vector<bool> RegsUsed;
56
57     // RegClassIdx - Maps RegClass => which index we can take a register
58     // from. Since this is a simple register allocator, when we need a register
59     // of a certain class, we just take the next available one.
60     std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
61
62   public:
63     virtual const char *getPassName() const {
64       return "Simple Register Allocator";
65     }
66
67     /// runOnMachineFunction - Register allocate the whole function
68     bool runOnMachineFunction(MachineFunction &Fn);
69
70     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71       AU.addRequiredID(PHIEliminationID);           // Eliminate PHI nodes
72       MachineFunctionPass::getAnalysisUsage(AU);
73     }
74   private:
75     /// AllocateBasicBlock - Register allocate the specified basic block.
76     void AllocateBasicBlock(MachineBasicBlock &MBB);
77
78     /// getStackSpaceFor - This returns the offset of the specified virtual
79     /// register on the stack, allocating space if necessary.
80     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
81
82     /// Given a virtual register, return a compatible physical register that is
83     /// currently unused.
84     ///
85     /// Side effect: marks that register as being used until manually cleared
86     ///
87     unsigned getFreeReg(unsigned virtualReg);
88
89     /// Moves value from memory into that register
90     unsigned reloadVirtReg(MachineBasicBlock &MBB,
91                            MachineBasicBlock::iterator I, unsigned VirtReg);
92
93     /// Saves reg value on the stack (maps virtual register to stack value)
94     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
95                       unsigned VirtReg, unsigned PhysReg);
96   };
97   char RegAllocSimple::ID = 0;
98 }
99
100 /// getStackSpaceFor - This allocates space for the specified virtual
101 /// register to be held on the stack.
102 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
103                                      const TargetRegisterClass *RC) {
104   // Find the location VirtReg would belong...
105   std::map<unsigned, int>::iterator I =
106     StackSlotForVirtReg.lower_bound(VirtReg);
107
108   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
109     return I->second;          // Already has space allocated?
110
111   // Allocate a new stack object for this spill location...
112   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
113                                                        RC->getAlignment());
114
115   // Assign the slot...
116   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
117
118   return FrameIdx;
119 }
120
121 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
122   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtualReg);
123   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
124   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
125
126   while (1) {
127     unsigned regIdx = RegClassIdx[RC]++;
128     assert(RI+regIdx != RE && "Not enough registers!");
129     unsigned PhysReg = *(RI+regIdx);
130
131     if (!RegsUsed[PhysReg]) {
132       MF->getRegInfo().setPhysRegUsed(PhysReg);
133       return PhysReg;
134     }
135   }
136 }
137
138 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
139                                        MachineBasicBlock::iterator I,
140                                        unsigned VirtReg) {
141   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(VirtReg);
142   int FrameIdx = getStackSpaceFor(VirtReg, RC);
143   unsigned PhysReg = getFreeReg(VirtReg);
144
145   // Add move instruction(s)
146   ++NumLoads;
147   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
148   TII->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
149   return PhysReg;
150 }
151
152 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
153                                   MachineBasicBlock::iterator I,
154                                   unsigned VirtReg, unsigned PhysReg) {
155   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(VirtReg);
156   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
157   
158   int FrameIdx = getStackSpaceFor(VirtReg, RC);
159
160   // Add move instruction(s)
161   ++NumStores;
162   TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIdx, RC);
163 }
164
165
166 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
167   // loop over each instruction
168   for (MachineBasicBlock::iterator MI = MBB.begin(); MI != MBB.end(); ++MI) {
169     // Made to combat the incorrect allocation of r2 = add r1, r1
170     std::map<unsigned, unsigned> Virt2PhysRegMap;
171
172     RegsUsed.resize(MRI->getNumRegs());
173
174     // This is a preliminary pass that will invalidate any registers that are
175     // used by the instruction (including implicit uses).
176     unsigned Opcode = MI->getOpcode();
177     const TargetInstrDescriptor &Desc = TM->getInstrInfo()->get(Opcode);
178     const unsigned *Regs;
179     if (Desc.ImplicitUses) {
180       for (Regs = Desc.ImplicitUses; *Regs; ++Regs)
181         RegsUsed[*Regs] = true;
182     }
183
184     if (Desc.ImplicitDefs) {
185       for (Regs = Desc.ImplicitDefs; *Regs; ++Regs) {
186         RegsUsed[*Regs] = true;
187         MF->getRegInfo().setPhysRegUsed(*Regs);
188       }
189     }
190
191     // Loop over uses, move from memory into registers.
192     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
193       MachineOperand &op = MI->getOperand(i);
194
195       if (op.isRegister() && op.getReg() &&
196           MRegisterInfo::isVirtualRegister(op.getReg())) {
197         unsigned virtualReg = (unsigned) op.getReg();
198         DOUT << "op: " << op << "\n";
199         DOUT << "\t inst[" << i << "]: ";
200         DEBUG(MI->print(*cerr.stream(), TM));
201
202         // make sure the same virtual register maps to the same physical
203         // register in any given instruction
204         unsigned physReg = Virt2PhysRegMap[virtualReg];
205         if (physReg == 0) {
206           if (op.isDef()) {
207             int TiedOp = MI->getInstrDescriptor()->findTiedToSrcOperand(i);
208             if (TiedOp == -1) {
209               physReg = getFreeReg(virtualReg);
210             } else {
211               // must be same register number as the source operand that is 
212               // tied to. This maps a = b + c into b = b + c, and saves b into
213               // a's spot.
214               assert(MI->getOperand(TiedOp).isRegister()  &&
215                      MI->getOperand(TiedOp).getReg() &&
216                      MI->getOperand(TiedOp).isUse() &&
217                      "Two address instruction invalid!");
218
219               physReg = MI->getOperand(TiedOp).getReg();
220             }
221             spillVirtReg(MBB, next(MI), virtualReg, physReg);
222           } else {
223             physReg = reloadVirtReg(MBB, MI, virtualReg);
224             Virt2PhysRegMap[virtualReg] = physReg;
225           }
226         }
227         MI->getOperand(i).setReg(physReg);
228         DOUT << "virt: " << virtualReg << ", phys: " << op.getReg() << "\n";
229       }
230     }
231     RegClassIdx.clear();
232     RegsUsed.clear();
233   }
234 }
235
236
237 /// runOnMachineFunction - Register allocate the whole function
238 ///
239 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
240   DOUT << "Machine Function\n";
241   MF = &Fn;
242   TM = &MF->getTarget();
243   MRI = TM->getRegisterInfo();
244
245   // Loop over all of the basic blocks, eliminating virtual register references
246   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
247        MBB != MBBe; ++MBB)
248     AllocateBasicBlock(*MBB);
249
250   StackSlotForVirtReg.clear();
251   return true;
252 }
253
254 FunctionPass *llvm::createSimpleRegisterAllocator() {
255   return new RegAllocSimple();
256 }