1 //===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
3 // This file implements a simple register allocator. *Very* simple.
5 //===----------------------------------------------------------------------===//
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"
15 struct RegAllocSimple : public FunctionPass {
17 MachineBasicBlock *CurrMBB;
20 const MRegisterInfo *RegInfo;
21 unsigned NumBytesAllocated, ByteAlignment;
23 // Maps SSA Regs => offsets on the stack where these values are stored
24 std::map<unsigned, unsigned> VirtReg2OffsetMap;
26 // Maps SSA Regs => physical regs
27 std::map<unsigned, unsigned> SSA2PhysRegMap;
29 // Maps physical register to their register classes
30 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
32 // Made to combat the incorrect allocation of r2 = add r1, r1
33 std::map<unsigned, unsigned> VirtReg2PhysRegMap;
35 // Maps RegClass => which index we can take a register from. Since this is a
36 // simple register allocator, when we need a register of a certain class, we
37 // just take the next available one.
38 std::map<unsigned, unsigned> RegsUsed;
39 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
41 RegAllocSimple(TargetMachine &tm) : TM(tm), CurrMBB(0), maxOffset(0),
42 RegInfo(tm.getRegisterInfo()),
45 // build reverse mapping for physReg -> register class
46 RegInfo->buildReg2RegClassMap(PhysReg2RegClassMap);
48 RegsUsed[RegInfo->getFramePointer()] = 1;
49 RegsUsed[RegInfo->getStackPointer()] = 1;
51 cleanupAfterFunction();
54 bool isAvailableReg(unsigned Reg) {
55 // assert(Reg < MRegisterInfo::FirstVirtualReg && "...");
56 return RegsUsed.find(Reg) == RegsUsed.end();
60 unsigned allocateStackSpaceFor(unsigned VirtReg,
61 const TargetRegisterClass *regClass);
63 /// Given size (in bytes), returns a register that is currently unused
64 /// Side effect: marks that register as being used until manually cleared
65 unsigned getFreeReg(unsigned virtualReg);
67 /// Returns all `borrowed' registers back to the free pool
72 /// Invalidates any references, real or implicit, to physical registers
74 void invalidatePhysRegs(const MachineInstr *MI) {
75 unsigned Opcode = MI->getOpcode();
76 const MachineInstrInfo &MII = TM.getInstrInfo();
77 const MachineInstrDescriptor &Desc = MII.get(Opcode);
78 const unsigned *regs = Desc.ImplicitUses;
80 RegsUsed[*regs++] = 1;
82 regs = Desc.ImplicitDefs;
84 RegsUsed[*regs++] = 1;
87 void cleanupAfterFunction() {
88 VirtReg2OffsetMap.clear();
89 SSA2PhysRegMap.clear();
90 NumBytesAllocated = ByteAlignment;
93 /// Moves value from memory into that register
94 MachineBasicBlock::iterator
95 moveUseToReg (MachineBasicBlock *MBB,
96 MachineBasicBlock::iterator I, unsigned VirtReg,
99 /// Saves reg value on the stack (maps virtual register to stack value)
100 MachineBasicBlock::iterator
101 saveVirtRegToStack (MachineBasicBlock *MBB,
102 MachineBasicBlock::iterator I, unsigned VirtReg,
105 MachineBasicBlock::iterator
106 savePhysRegToStack (MachineBasicBlock *MBB,
107 MachineBasicBlock::iterator I, unsigned PhysReg);
109 /// runOnFunction - Top level implementation of instruction selection for
110 /// the entire function.
112 bool runOnMachineFunction(MachineFunction &Fn);
114 bool runOnFunction(Function &Fn) {
115 return runOnMachineFunction(MachineFunction::get(&Fn));
121 unsigned RegAllocSimple::allocateStackSpaceFor(unsigned VirtReg,
122 const TargetRegisterClass *regClass)
124 if (VirtReg2OffsetMap.find(VirtReg) == VirtReg2OffsetMap.end()) {
126 unsigned size = regClass->getDataSize();
127 unsigned over = NumBytesAllocated - (NumBytesAllocated % ByteAlignment);
128 if (size >= ByteAlignment - over) {
129 // need to pad by (ByteAlignment - over)
130 NumBytesAllocated += ByteAlignment - over;
132 VirtReg2OffsetMap[VirtReg] = NumBytesAllocated;
133 NumBytesAllocated += size;
135 // FIXME: forcing each arg to take 4 bytes on the stack
136 VirtReg2OffsetMap[VirtReg] = NumBytesAllocated;
137 NumBytesAllocated += ByteAlignment;
139 return VirtReg2OffsetMap[VirtReg];
142 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
143 const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
146 if (RegClassIdx.find(regClass) != RegClassIdx.end()) {
147 unsigned regIdx = RegClassIdx[regClass]++;
148 assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
149 physReg = regClass->getRegister(regIdx);
151 physReg = regClass->getRegister(0);
152 // assert(physReg < regClass->getNumRegs() && "No registers in class!");
153 RegClassIdx[regClass] = 1;
156 if (isAvailableReg(physReg))
159 return getFreeReg(virtualReg);
163 MachineBasicBlock::iterator
164 RegAllocSimple::moveUseToReg (MachineBasicBlock *MBB,
165 MachineBasicBlock::iterator I,
166 unsigned VirtReg, unsigned &PhysReg)
168 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
171 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
172 PhysReg = getFreeReg(VirtReg);
174 // Add move instruction(s)
175 return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
176 RegInfo->getFramePointer(),
177 -stackOffset, regClass->getDataSize());
180 MachineBasicBlock::iterator
181 RegAllocSimple::saveVirtRegToStack (MachineBasicBlock *MBB,
182 MachineBasicBlock::iterator I,
183 unsigned VirtReg, unsigned PhysReg)
185 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
188 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
190 // Add move instruction(s)
191 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
192 RegInfo->getFramePointer(),
193 -stackOffset, regClass->getDataSize());
196 MachineBasicBlock::iterator
197 RegAllocSimple::savePhysRegToStack (MachineBasicBlock *MBB,
198 MachineBasicBlock::iterator I,
201 const TargetRegisterClass* regClass = MF->getRegClass(PhysReg);
204 unsigned offset = allocateStackSpaceFor(PhysReg, regClass);
206 // Add move instruction(s)
207 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
208 RegInfo->getFramePointer(),
209 offset, regClass->getDataSize());
212 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
213 cleanupAfterFunction();
215 unsigned virtualReg, physReg;
216 DEBUG(std::cerr << "Machine Function " << "\n");
219 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
224 // Handle PHI instructions specially: add moves to each pred block
225 while (MBB->front()->getOpcode() == 0) {
226 MachineInstr *MI = MBB->front();
227 // get rid of the phi
228 MBB->erase(MBB->begin());
230 // a preliminary pass that will invalidate any registers that
231 // are used by the instruction (including implicit uses)
232 invalidatePhysRegs(MI);
234 DEBUG(std::cerr << "num invalid regs: " << RegsUsed.size() << "\n");
236 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
237 MachineOperand &targetReg = MI->getOperand(0);
239 // If it's a virtual register, allocate a physical one
240 // otherwise, just use whatever register is there now
241 // note: it MUST be a register -- we're assigning to it
242 virtualReg = (unsigned) targetReg.getAllocatedRegNum();
243 if (targetReg.isVirtualRegister()) {
244 physReg = getFreeReg(virtualReg);
246 physReg = virtualReg;
249 // Find the register class of the target register: should be the
250 // same as the values we're trying to store there
251 const TargetRegisterClass* regClass = PhysReg2RegClassMap[physReg];
252 assert(regClass && "Target register class not found!");
253 unsigned dataSize = regClass->getDataSize();
255 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
256 MachineOperand &opVal = MI->getOperand(i-1);
258 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
259 // source path the phi
260 MachineBasicBlock *opBlock = MI->getOperand(i).getMachineBasicBlock();
261 MachineBasicBlock::iterator opI = opBlock->end();
262 MachineInstr *opMI = *(--opI);
263 const MachineInstrInfo &MII = TM.getInstrInfo();
264 // must backtrack over ALL the branches in the previous block, until no more
265 while ((MII.isBranch(opMI->getOpcode()) || MII.isReturn(opMI->getOpcode()))
266 && opI != opBlock->begin())
270 // move back to the first branch instruction so new instructions
271 // are inserted right in front of it and not in front of a non-branch
275 // Retrieve the constant value from this op, move it to target
276 // register of the phi
277 if (opVal.getType() == MachineOperand::MO_SignExtendedImmed ||
278 opVal.getType() == MachineOperand::MO_UnextendedImmed)
280 opI = RegInfo->moveImm2Reg(opBlock, opI, physReg,
281 (unsigned) opVal.getImmedValue(),
283 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
285 // Allocate a physical register and add a move in the BB
286 unsigned opVirtualReg = (unsigned) opVal.getAllocatedRegNum();
287 unsigned opPhysReg; // = getFreeReg(opVirtualReg);
288 opI = moveUseToReg(opBlock, opI, opVirtualReg, physReg);
289 //opI = RegInfo->moveReg2Reg(opBlock, opI, physReg, opPhysReg,
291 // Save that register value to the stack of the TARGET REG
292 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
295 // make regs available to other instructions
299 // really delete the instruction
303 //loop over each basic block
304 for (MachineBasicBlock::iterator I = MBB->begin(); I != MBB->end(); ++I)
306 MachineInstr *MI = *I;
308 // a preliminary pass that will invalidate any registers that
309 // are used by the instruction (including implicit uses)
310 invalidatePhysRegs(MI);
312 // Loop over uses, move from memory into registers
313 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
314 MachineOperand &op = MI->getOperand(i);
316 if (op.getType() == MachineOperand::MO_SignExtendedImmed ||
317 op.getType() == MachineOperand::MO_UnextendedImmed)
319 DEBUG(std::cerr << "const\n");
320 } else if (op.isVirtualRegister()) {
321 virtualReg = (unsigned) op.getAllocatedRegNum();
322 DEBUG(std::cerr << "op: " << op << "\n");
323 DEBUG(std::cerr << "\t inst[" << i << "]: ";
324 MI->print(std::cerr, TM));
326 // make sure the same virtual register maps to the same physical
327 // register in any given instruction
328 if (VirtReg2PhysRegMap.find(virtualReg) != VirtReg2PhysRegMap.end()) {
329 physReg = VirtReg2PhysRegMap[virtualReg];
332 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
333 // must be same register number as the first operand
334 // This maps a = b + c into b += c, and saves b into a's spot
335 physReg = (unsigned) MI->getOperand(1).getAllocatedRegNum();
337 physReg = getFreeReg(virtualReg);
339 MachineBasicBlock::iterator J = I;
340 J = saveVirtRegToStack(CurrMBB, ++J, virtualReg, physReg);
343 I = moveUseToReg(CurrMBB, I, virtualReg, physReg);
345 VirtReg2PhysRegMap[virtualReg] = physReg;
347 MI->SetMachineOperandReg(i, physReg);
348 DEBUG(std::cerr << "virt: " << virtualReg <<
349 ", phys: " << op.getAllocatedRegNum() << "\n");
354 VirtReg2PhysRegMap.clear();
359 // add prologue we should preserve callee-save registers...
360 MachineFunction::iterator Fi = Fn.begin();
361 MachineBasicBlock *MBB = Fi;
362 MachineBasicBlock::iterator MBBi = MBB->begin();
363 RegInfo->emitPrologue(MBB, MBBi, NumBytesAllocated);
365 // add epilogue to restore the callee-save registers
366 // loop over the basic block
367 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
370 // check if last instruction is a RET
371 MachineBasicBlock::iterator I = (*MBB).end();
372 MachineInstr *MI = *(--I);
373 const MachineInstrInfo &MII = TM.getInstrInfo();
374 if (MII.isReturn(MI->getOpcode())) {
375 // this block has a return instruction, add epilogue
376 RegInfo->emitEpilogue(MBB, I, NumBytesAllocated);
380 return false; // We never modify the LLVM itself.
383 Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
384 return new RegAllocSimple(TM);