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