Simplify PHI node elimination significantly by doing it as a prepass to
[oota-llvm.git] / lib / CodeGen / RegAllocSimple.cpp
1 //===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
2 //
3 // This file implements a simple register allocator. *Very* simple.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/CodeGen/MachineFunction.h"
8 #include "llvm/CodeGen/MachineInstr.h"
9 #include "llvm/Target/MachineInstrInfo.h"
10 #include "llvm/Target/TargetMachine.h"
11 #include "Support/Statistic.h"
12 #include <iostream>
13 #include <set>
14
15 #if 0
16 /// PhysRegClassMap - Construct a mapping of physical register numbers to their
17 /// register classes.
18 ///
19 /// NOTE: This class will eventually be pulled out to somewhere shared.
20 ///
21 class PhysRegClassMap {
22   std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
23 public:
24   PhysRegClassMap(const MRegisterInfo *RI) {
25     for (MRegisterInfo::const_iterator I = RI->regclass_begin(),
26            E = RI->regclass_end(); I != E; ++I)
27       for (unsigned i=0; i < (*I)->getNumRegs(); ++i)
28         PhysReg2RegClassMap[(*I)->getRegister(i)] = *I;
29   }
30
31   const TargetRegisterClass *operator[](unsigned Reg) {
32     assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
33     return PhysReg2RegClassMap[Reg];
34   }
35
36   const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
37 };
38 #endif
39
40
41 namespace {
42   Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
43   Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
44
45   class RegAllocSimple : public FunctionPass {
46     TargetMachine &TM;
47     MachineFunction *MF;
48     const MRegisterInfo *RegInfo;
49     unsigned NumBytesAllocated;
50     
51     // Maps SSA Regs => offsets on the stack where these values are stored
52     std::map<unsigned, unsigned> VirtReg2OffsetMap;
53
54     // RegsUsed - Keep track of what registers are currently in use.
55     std::set<unsigned> 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
64     RegAllocSimple(TargetMachine &tm)
65       : TM(tm), RegInfo(tm.getRegisterInfo()) {
66       RegsUsed.insert(RegInfo->getFramePointer());
67       RegsUsed.insert(RegInfo->getStackPointer());
68
69       cleanupAfterFunction();
70     }
71
72     bool runOnFunction(Function &Fn) {
73       return runOnMachineFunction(MachineFunction::get(&Fn));
74     }
75
76     virtual const char *getPassName() const {
77       return "Simple Register Allocator";
78     }
79
80   private:
81     /// runOnMachineFunction - Register allocate the whole function
82     bool runOnMachineFunction(MachineFunction &Fn);
83
84     /// AllocateBasicBlock - Register allocate the specified basic block.
85     void AllocateBasicBlock(MachineBasicBlock &MBB);
86
87     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
88     /// in predecessor basic blocks.
89     void EliminatePHINodes(MachineBasicBlock &MBB);
90
91
92     /// getStackSpaceFor - This returns the offset of the specified virtual
93     /// register on the stack, allocating space if neccesary.
94     unsigned getStackSpaceFor(unsigned VirtReg, 
95                               const TargetRegisterClass *regClass);
96
97     /// Given a virtual register, return a compatible physical register that is
98     /// currently unused.
99     ///
100     /// Side effect: marks that register as being used until manually cleared
101     ///
102     unsigned getFreeReg(unsigned virtualReg);
103
104     /// Returns all `borrowed' registers back to the free pool
105     void clearAllRegs() {
106       RegClassIdx.clear();
107     }
108
109     /// Invalidates any references, real or implicit, to physical registers
110     ///
111     void invalidatePhysRegs(const MachineInstr *MI) {
112       unsigned Opcode = MI->getOpcode();
113       const MachineInstrDescriptor &Desc = TM.getInstrInfo().get(Opcode);
114       const unsigned *regs = Desc.ImplicitUses;
115       while (*regs)
116         RegsUsed.insert(*regs++);
117
118       regs = Desc.ImplicitDefs;
119       while (*regs)
120         RegsUsed.insert(*regs++);
121     }
122
123     void cleanupAfterFunction() {
124       VirtReg2OffsetMap.clear();
125       NumBytesAllocated = 4;   // FIXME: This is X86 specific
126     }
127
128     /// Moves value from memory into that register
129     MachineBasicBlock::iterator
130     moveUseToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
131                  unsigned VirtReg, unsigned &PhysReg);
132
133     /// Saves reg value on the stack (maps virtual register to stack value)
134     MachineBasicBlock::iterator
135     saveVirtRegToStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
136                        unsigned VirtReg, unsigned PhysReg);
137   };
138
139 }
140
141 /// getStackSpaceFor - This allocates space for the specified virtual
142 /// register to be held on the stack.
143 unsigned RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
144                                           const TargetRegisterClass *regClass) {
145   // Find the location VirtReg would belong...
146   std::map<unsigned, unsigned>::iterator I =
147     VirtReg2OffsetMap.lower_bound(VirtReg);
148
149   if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
150     return I->second;          // Already has space allocated?
151
152   unsigned RegSize = regClass->getDataSize();
153
154   // Align NumBytesAllocated.  We should be using TargetData alignment stuff
155   // to determine this, but we don't know the LLVM type associated with the
156   // virtual register.  Instead, just align to a multiple of the size for now.
157   NumBytesAllocated += RegSize-1;
158   NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
159   
160   // Assign the slot...
161   VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
162   
163   // Reserve the space!
164   NumBytesAllocated += RegSize;
165   return NumBytesAllocated-RegSize;
166 }
167
168 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
169   const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
170   
171   unsigned regIdx = RegClassIdx[regClass]++;
172   assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
173   unsigned physReg = regClass->getRegister(regIdx);
174
175   if (RegsUsed.find(physReg) == RegsUsed.end())
176     return physReg;
177   else
178     return getFreeReg(virtualReg);
179 }
180
181 MachineBasicBlock::iterator
182 RegAllocSimple::moveUseToReg (MachineBasicBlock &MBB,
183                               MachineBasicBlock::iterator I,
184                               unsigned VirtReg, unsigned &PhysReg)
185 {
186   const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
187   unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
188   PhysReg = getFreeReg(VirtReg);
189
190   // Add move instruction(s)
191   ++NumReloaded;
192   return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
193                                     RegInfo->getFramePointer(),
194                                     -stackOffset, regClass->getDataSize());
195 }
196
197 MachineBasicBlock::iterator
198 RegAllocSimple::saveVirtRegToStack (MachineBasicBlock &MBB,
199                                     MachineBasicBlock::iterator I,
200                                     unsigned VirtReg, unsigned PhysReg)
201 {
202   const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
203   unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
204
205   // Add move instruction(s)
206   ++NumSpilled;
207   return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
208                                      RegInfo->getFramePointer(),
209                                      -stackOffset, regClass->getDataSize());
210 }
211
212
213 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
214 /// predecessor basic blocks.
215 ///
216 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
217   const MachineInstrInfo &MII = TM.getInstrInfo();
218
219   while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
220     MachineInstr *MI = MBB.front();
221     // Unlink the PHI node from the basic block... but don't delete the PHI yet
222     MBB.erase(MBB.begin());
223     
224     DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
225     assert(MI->getOperand(0).isVirtualRegister() &&
226            "PHI node doesn't write virt reg?");
227
228     unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
229     
230     for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
231       MachineOperand &opVal = MI->getOperand(i-1);
232       
233       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
234       // source path the phi
235       MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
236
237       // Check to make sure we haven't already emitted the copy for this block.
238       // This can happen because PHI nodes may have multiple entries for the
239       // same basic block.  It doesn't matter which entry we use though, because
240       // all incoming values are guaranteed to be the same for a particular bb.
241       //
242       // Note that this is N^2 in the number of phi node entries, but since the
243       // # of entries is tiny, this is not a problem.
244       //
245       bool HaveNotEmitted = true;
246       for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
247         if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
248           HaveNotEmitted = false;
249           break;
250         }
251
252       if (HaveNotEmitted) {
253         MachineBasicBlock::iterator opI = opBlock.end();
254         MachineInstr *opMI = *--opI;
255         
256         // must backtrack over ALL the branches in the previous block
257         while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
258           opMI = *--opI;
259         
260         // move back to the first branch instruction so new instructions
261         // are inserted right in front of it and not in front of a non-branch
262         if (!MII.isBranch(opMI->getOpcode()))
263           ++opI;
264
265         unsigned dataSize = MF->getRegClass(virtualReg)->getDataSize();
266
267         // Retrieve the constant value from this op, move it to target
268         // register of the phi
269         if (opVal.isImmediate()) {
270           opI = RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
271                                      (unsigned) opVal.getImmedValue(),
272                                      dataSize);
273         } else {
274           opI = RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
275                                      opVal.getAllocatedRegNum(), dataSize);
276         }
277       }
278     }
279     
280     // really delete the PHI instruction now!
281     delete MI;
282   }
283 }
284
285
286 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
287   // loop over each instruction
288   for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
289     // Made to combat the incorrect allocation of r2 = add r1, r1
290     std::map<unsigned, unsigned> Virt2PhysRegMap;
291
292     MachineInstr *MI = *I;
293     
294     // a preliminary pass that will invalidate any registers that
295     // are used by the instruction (including implicit uses)
296     invalidatePhysRegs(MI);
297     
298     // Loop over uses, move from memory into registers
299     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
300       MachineOperand &op = MI->getOperand(i);
301       
302       if (op.isVirtualRegister()) {
303         unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
304         DEBUG(std::cerr << "op: " << op << "\n");
305         DEBUG(std::cerr << "\t inst[" << i << "]: ";
306               MI->print(std::cerr, TM));
307         
308         // make sure the same virtual register maps to the same physical
309         // register in any given instruction
310         unsigned physReg = Virt2PhysRegMap[virtualReg];
311         if (physReg == 0) {
312           if (op.opIsDef()) {
313             if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
314               // must be same register number as the first operand
315               // This maps a = b + c into b += c, and saves b into a's spot
316               assert(MI->getOperand(1).isRegister()  &&
317                      MI->getOperand(1).getAllocatedRegNum() &&
318                      MI->getOperand(1).opIsUse() &&
319                      "Two address instruction invalid!");
320
321               physReg = MI->getOperand(1).getAllocatedRegNum();
322             } else {
323               physReg = getFreeReg(virtualReg);
324             }
325             I = --saveVirtRegToStack(MBB, ++I, virtualReg, physReg);
326           } else {
327             I = moveUseToReg(MBB, I, virtualReg, physReg);
328           }
329           Virt2PhysRegMap[virtualReg] = physReg;
330         }
331         MI->SetMachineOperandReg(i, physReg);
332         DEBUG(std::cerr << "virt: " << virtualReg << 
333               ", phys: " << op.getAllocatedRegNum() << "\n");
334       }
335     }
336     clearAllRegs();
337   }
338 }
339
340 /// runOnMachineFunction - Register allocate the whole function
341 ///
342 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
343   DEBUG(std::cerr << "Machine Function " << "\n");
344   MF = &Fn;
345
346   // First pass: eliminate PHI instructions by inserting copies into predecessor
347   // blocks.
348   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
349        MBB != MBBe; ++MBB)
350     EliminatePHINodes(*MBB);
351
352   // Loop over all of the basic blocks, eliminating virtual register references
353   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
354        MBB != MBBe; ++MBB)
355     AllocateBasicBlock(*MBB);
356
357   // Add prologue to the function...
358   RegInfo->emitPrologue(Fn, NumBytesAllocated);
359
360   const MachineInstrInfo &MII = TM.getInstrInfo();
361
362   // Add epilogue to restore the callee-save registers in each exiting block
363   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
364        MBB != MBBe; ++MBB) {
365     // If last instruction is a return instruction, add an epilogue
366     if (MII.isReturn(MBB->back()->getOpcode()))
367       RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
368   }
369
370   cleanupAfterFunction();
371   return true;
372 }
373
374 Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
375   return new RegAllocSimple(TM);
376 }