add some helpers
[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 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 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/SSARegMap.h"
22 #include "llvm/CodeGen/MachineFrameInfo.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     MachineFunction *MF;
42     const TargetMachine *TM;
43     const MRegisterInfo *RegInfo;
44
45     // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
46     // these values are spilled
47     std::map<unsigned, int> StackSlotForVirtReg;
48
49     // RegsUsed - Keep track of what registers are currently in use.  This is a
50     // bitset.
51     std::vector<bool> RegsUsed;
52
53     // RegClassIdx - Maps RegClass => which index we can take a register
54     // from. Since this is a simple register allocator, when we need a register
55     // of a certain class, we just take the next available one.
56     std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
57
58   public:
59     virtual const char *getPassName() const {
60       return "Simple Register Allocator";
61     }
62
63     /// runOnMachineFunction - Register allocate the whole function
64     bool runOnMachineFunction(MachineFunction &Fn);
65
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequiredID(PHIEliminationID);           // Eliminate PHI nodes
68       MachineFunctionPass::getAnalysisUsage(AU);
69     }
70   private:
71     /// AllocateBasicBlock - Register allocate the specified basic block.
72     void AllocateBasicBlock(MachineBasicBlock &MBB);
73
74     /// getStackSpaceFor - This returns the offset of the specified virtual
75     /// register on the stack, allocating space if necessary.
76     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
77
78     /// Given a virtual register, return a compatible physical register that is
79     /// currently unused.
80     ///
81     /// Side effect: marks that register as being used until manually cleared
82     ///
83     unsigned getFreeReg(unsigned virtualReg);
84
85     /// Moves value from memory into that register
86     unsigned reloadVirtReg(MachineBasicBlock &MBB,
87                            MachineBasicBlock::iterator I, unsigned VirtReg);
88
89     /// Saves reg value on the stack (maps virtual register to stack value)
90     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
91                       unsigned VirtReg, unsigned PhysReg);
92   };
93
94 }
95
96 /// getStackSpaceFor - This allocates space for the specified virtual
97 /// register to be held on the stack.
98 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
99                                      const TargetRegisterClass *RC) {
100   // Find the location VirtReg would belong...
101   std::map<unsigned, int>::iterator I =
102     StackSlotForVirtReg.lower_bound(VirtReg);
103
104   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
105     return I->second;          // Already has space allocated?
106
107   // Allocate a new stack object for this spill location...
108   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
109                                                        RC->getAlignment());
110
111   // Assign the slot...
112   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
113
114   return FrameIdx;
115 }
116
117 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
118   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
119   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
120   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
121
122   while (1) {
123     unsigned regIdx = RegClassIdx[RC]++;
124     assert(RI+regIdx != RE && "Not enough registers!");
125     unsigned PhysReg = *(RI+regIdx);
126
127     if (!RegsUsed[PhysReg]) {
128       MF->setPhysRegUsed(PhysReg);
129       return PhysReg;
130     }
131   }
132 }
133
134 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
135                                        MachineBasicBlock::iterator I,
136                                        unsigned VirtReg) {
137   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
138   int FrameIdx = getStackSpaceFor(VirtReg, RC);
139   unsigned PhysReg = getFreeReg(VirtReg);
140
141   // Add move instruction(s)
142   ++NumLoads;
143   RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
144   return PhysReg;
145 }
146
147 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
148                                   MachineBasicBlock::iterator I,
149                                   unsigned VirtReg, unsigned PhysReg) {
150   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
151   int FrameIdx = getStackSpaceFor(VirtReg, RC);
152
153   // Add move instruction(s)
154   ++NumStores;
155   RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIdx, RC);
156 }
157
158
159 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
160   // loop over each instruction
161   for (MachineBasicBlock::iterator MI = MBB.begin(); MI != MBB.end(); ++MI) {
162     // Made to combat the incorrect allocation of r2 = add r1, r1
163     std::map<unsigned, unsigned> Virt2PhysRegMap;
164
165     RegsUsed.resize(RegInfo->getNumRegs());
166
167     // This is a preliminary pass that will invalidate any registers that are
168     // used by the instruction (including implicit uses).
169     unsigned Opcode = MI->getOpcode();
170     const TargetInstrDescriptor &Desc = TM->getInstrInfo()->get(Opcode);
171     const unsigned *Regs;
172     if (Desc.ImplicitUses) {
173       for (Regs = Desc.ImplicitUses; *Regs; ++Regs)
174         RegsUsed[*Regs] = true;
175     }
176
177     if (Desc.ImplicitDefs) {
178       for (Regs = Desc.ImplicitDefs; *Regs; ++Regs) {
179         RegsUsed[*Regs] = true;
180         MF->setPhysRegUsed(*Regs);
181       }
182     }
183
184     // Loop over uses, move from memory into registers.
185     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
186       MachineOperand &op = MI->getOperand(i);
187
188       if (op.isRegister() && op.getReg() &&
189           MRegisterInfo::isVirtualRegister(op.getReg())) {
190         unsigned virtualReg = (unsigned) op.getReg();
191         DOUT << "op: " << op << "\n";
192         DOUT << "\t inst[" << i << "]: ";
193         DEBUG(MI->print(*cerr.stream(), TM));
194
195         // make sure the same virtual register maps to the same physical
196         // register in any given instruction
197         unsigned physReg = Virt2PhysRegMap[virtualReg];
198         if (physReg == 0) {
199           if (op.isDef()) {
200             int TiedOp = MI->getInstrDescriptor()->findTiedToSrcOperand(i);
201             if (TiedOp == -1) {
202               physReg = getFreeReg(virtualReg);
203             } else {
204               // must be same register number as the source operand that is 
205               // tied to. This maps a = b + c into b = b + c, and saves b into
206               // a's spot.
207               assert(MI->getOperand(TiedOp).isRegister()  &&
208                      MI->getOperand(TiedOp).getReg() &&
209                      MI->getOperand(TiedOp).isUse() &&
210                      "Two address instruction invalid!");
211
212               physReg = MI->getOperand(TiedOp).getReg();
213             }
214             spillVirtReg(MBB, next(MI), virtualReg, physReg);
215           } else {
216             physReg = reloadVirtReg(MBB, MI, virtualReg);
217             Virt2PhysRegMap[virtualReg] = physReg;
218           }
219         }
220         MI->getOperand(i).setReg(physReg);
221         DOUT << "virt: " << virtualReg << ", phys: " << op.getReg() << "\n";
222       }
223     }
224     RegClassIdx.clear();
225     RegsUsed.clear();
226   }
227 }
228
229
230 /// runOnMachineFunction - Register allocate the whole function
231 ///
232 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
233   DOUT << "Machine Function\n";
234   MF = &Fn;
235   TM = &MF->getTarget();
236   RegInfo = TM->getRegisterInfo();
237
238   // Loop over all of the basic blocks, eliminating virtual register references
239   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
240        MBB != MBBe; ++MBB)
241     AllocateBasicBlock(*MBB);
242
243   StackSlotForVirtReg.clear();
244   return true;
245 }
246
247 FunctionPass *llvm::createSimpleRegisterAllocator() {
248   return new RegAllocSimple();
249 }