1 //===-- RegAllocSimple.cpp - A simple generic register allocator ----------===//
3 // This file implements a simple register allocator. *Very* simple: It immediate
4 // spills every value right after it is computed, and it reloads all used
5 // operands from the spill area to temporary registers before each instruction.
6 // It does not keep values in registers across instructions.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineFunctionPass.h"
11 #include "llvm/CodeGen/MachineInstr.h"
12 #include "llvm/CodeGen/SSARegMap.h"
13 #include "llvm/CodeGen/MachineFrameInfo.h"
14 #include "llvm/Target/MachineInstrInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "Support/Statistic.h"
20 Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
21 Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
23 class RegAllocSimple : public MachineFunctionPass {
25 const TargetMachine *TM;
26 const MRegisterInfo *RegInfo;
28 // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
29 // these values are spilled
30 std::map<unsigned, int> StackSlotForVirtReg;
32 // RegsUsed - Keep track of what registers are currently in use. This is a
34 std::vector<bool> RegsUsed;
36 // RegClassIdx - Maps RegClass => which index we can take a register
37 // from. Since this is a simple register allocator, when we need a register
38 // of a certain class, we just take the next available one.
39 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
42 virtual const char *getPassName() const {
43 return "Simple Register Allocator";
46 /// runOnMachineFunction - Register allocate the whole function
47 bool runOnMachineFunction(MachineFunction &Fn);
50 /// AllocateBasicBlock - Register allocate the specified basic block.
51 void AllocateBasicBlock(MachineBasicBlock &MBB);
53 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
54 /// in predecessor basic blocks.
55 void EliminatePHINodes(MachineBasicBlock &MBB);
57 /// getStackSpaceFor - This returns the offset of the specified virtual
58 /// register on the stack, allocating space if neccesary.
59 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
61 /// Given a virtual register, return a compatible physical register that is
64 /// Side effect: marks that register as being used until manually cleared
66 unsigned getFreeReg(unsigned virtualReg);
68 /// Moves value from memory into that register
69 unsigned reloadVirtReg(MachineBasicBlock &MBB,
70 MachineBasicBlock::iterator &I, unsigned VirtReg);
72 /// Saves reg value on the stack (maps virtual register to stack value)
73 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
74 unsigned VirtReg, unsigned PhysReg);
79 /// getStackSpaceFor - This allocates space for the specified virtual
80 /// register to be held on the stack.
81 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
82 const TargetRegisterClass *RC) {
83 // Find the location VirtReg would belong...
84 std::map<unsigned, int>::iterator I =
85 StackSlotForVirtReg.lower_bound(VirtReg);
87 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
88 return I->second; // Already has space allocated?
90 // Allocate a new stack object for this spill location...
92 MF->getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment());
95 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
100 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
101 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
102 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
103 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
106 unsigned regIdx = RegClassIdx[RC]++;
107 assert(RI+regIdx != RE && "Not enough registers!");
108 unsigned PhysReg = *(RI+regIdx);
110 if (!RegsUsed[PhysReg])
115 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
116 MachineBasicBlock::iterator &I,
118 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
119 int FrameIdx = getStackSpaceFor(VirtReg, RC);
120 unsigned PhysReg = getFreeReg(VirtReg);
122 // Add move instruction(s)
124 RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
128 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
129 MachineBasicBlock::iterator &I,
130 unsigned VirtReg, unsigned PhysReg) {
131 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
132 int FrameIdx = getStackSpaceFor(VirtReg, RC);
134 // Add move instruction(s)
136 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIdx, RC);
140 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
141 /// predecessor basic blocks.
143 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
144 const MachineInstrInfo &MII = TM->getInstrInfo();
146 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
147 MachineInstr *MI = MBB.front();
148 // Unlink the PHI node from the basic block... but don't delete the PHI yet
149 MBB.erase(MBB.begin());
151 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
152 assert(MI->getOperand(0).isVirtualRegister() &&
153 "PHI node doesn't write virt reg?");
155 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
157 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
158 MachineOperand &opVal = MI->getOperand(i-1);
160 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
161 // source path the phi
162 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
164 // Check to make sure we haven't already emitted the copy for this block.
165 // This can happen because PHI nodes may have multiple entries for the
166 // same basic block. It doesn't matter which entry we use though, because
167 // all incoming values are guaranteed to be the same for a particular bb.
169 // Note that this is N^2 in the number of phi node entries, but since the
170 // # of entries is tiny, this is not a problem.
172 bool HaveNotEmitted = true;
173 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
174 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
175 HaveNotEmitted = false;
179 if (HaveNotEmitted) {
180 MachineBasicBlock::iterator opI = opBlock.end();
181 MachineInstr *opMI = *--opI;
183 // must backtrack over ALL the branches in the previous block
184 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
187 // move back to the first branch instruction so new instructions
188 // are inserted right in front of it and not in front of a non-branch
190 if (!MII.isBranch(opMI->getOpcode()))
193 const TargetRegisterClass *RC =
194 MF->getSSARegMap()->getRegClass(virtualReg);
196 assert(opVal.isVirtualRegister() &&
197 "Machine PHI Operands must all be virtual registers!");
198 RegInfo->copyRegToReg(opBlock, opI, virtualReg, opVal.getReg(), RC);
202 // really delete the PHI instruction now!
208 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
209 // loop over each instruction
210 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
211 // Made to combat the incorrect allocation of r2 = add r1, r1
212 std::map<unsigned, unsigned> Virt2PhysRegMap;
214 MachineInstr *MI = *I;
216 RegsUsed.resize(MRegisterInfo::FirstVirtualRegister);
218 // a preliminary pass that will invalidate any registers that
219 // are used by the instruction (including implicit uses)
220 unsigned Opcode = MI->getOpcode();
221 const MachineInstrDescriptor &Desc = TM->getInstrInfo().get(Opcode);
222 if (const unsigned *Regs = Desc.ImplicitUses)
224 RegsUsed[*Regs++] = true;
226 if (const unsigned *Regs = Desc.ImplicitDefs)
228 RegsUsed[*Regs++] = true;
230 // Loop over uses, move from memory into registers
231 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
232 MachineOperand &op = MI->getOperand(i);
234 if (op.isVirtualRegister()) {
235 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
236 DEBUG(std::cerr << "op: " << op << "\n");
237 DEBUG(std::cerr << "\t inst[" << i << "]: ";
238 MI->print(std::cerr, *TM));
240 // make sure the same virtual register maps to the same physical
241 // register in any given instruction
242 unsigned physReg = Virt2PhysRegMap[virtualReg];
245 if (TM->getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
246 // must be same register number as the first operand
247 // This maps a = b + c into b += c, and saves b into a's spot
248 assert(MI->getOperand(1).isRegister() &&
249 MI->getOperand(1).getAllocatedRegNum() &&
250 MI->getOperand(1).opIsUse() &&
251 "Two address instruction invalid!");
253 physReg = MI->getOperand(1).getAllocatedRegNum();
255 physReg = getFreeReg(virtualReg);
258 spillVirtReg(MBB, I, virtualReg, physReg);
261 physReg = reloadVirtReg(MBB, I, virtualReg);
262 Virt2PhysRegMap[virtualReg] = physReg;
265 MI->SetMachineOperandReg(i, physReg);
266 DEBUG(std::cerr << "virt: " << virtualReg <<
267 ", phys: " << op.getAllocatedRegNum() << "\n");
276 /// runOnMachineFunction - Register allocate the whole function
278 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
279 DEBUG(std::cerr << "Machine Function " << "\n");
281 TM = &MF->getTarget();
282 RegInfo = TM->getRegisterInfo();
284 // First pass: eliminate PHI instructions by inserting copies into predecessor
286 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
288 EliminatePHINodes(*MBB);
290 // Loop over all of the basic blocks, eliminating virtual register references
291 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
293 AllocateBasicBlock(*MBB);
295 StackSlotForVirtReg.clear();
299 Pass *createSimpleRegisterAllocator() {
300 return new RegAllocSimple();