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