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