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