blob: 49a205aec5d036a7a1f223dd91fffaa07ca37cc4 [file] [log] [blame]
Misha Brukman07218672002-11-22 22:44:32 +00001//===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
2//
3// This file implements a simple register allocator. *Very* simple.
4//
5//===----------------------------------------------------------------------===//
6
Misha Brukman07218672002-11-22 22:44:32 +00007#include "llvm/CodeGen/MachineFunction.h"
Chris Lattnerabe8dd52002-12-15 18:19:24 +00008#include "llvm/CodeGen/MachineInstr.h"
Misha Brukmandd46e2a2002-12-04 23:58:08 +00009#include "llvm/Target/MachineInstrInfo.h"
Misha Brukman07218672002-11-22 22:44:32 +000010#include "llvm/Target/TargetMachine.h"
Misha Brukman07218672002-11-22 22:44:32 +000011#include "Support/Statistic.h"
Chris Lattnerabe8dd52002-12-15 18:19:24 +000012#include <iostream>
Misha Brukman07218672002-11-22 22:44:32 +000013
Chris Lattnerdd444f92002-12-15 18:38:59 +000014/// PhysRegClassMap - Construct a mapping of physical register numbers to their
15/// register classes.
16///
17/// NOTE: This class will eventually be pulled out to somewhere shared.
18///
19class PhysRegClassMap {
20 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
21public:
22 PhysRegClassMap(const MRegisterInfo *RI) {
23 for (MRegisterInfo::const_iterator I = RI->regclass_begin(),
24 E = RI->regclass_end(); I != E; ++I)
25 for (unsigned i=0; i < (*I)->getNumRegs(); ++i)
26 PhysReg2RegClassMap[(*I)->getRegister(i)] = *I;
27 }
28
29 const TargetRegisterClass *operator[](unsigned Reg) {
30 assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
31 return PhysReg2RegClassMap[Reg];
32 }
33
34 const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
35};
36
37
Misha Brukman59b3eed2002-12-13 10:42:31 +000038namespace {
Misha Brukman07218672002-11-22 22:44:32 +000039 struct RegAllocSimple : public FunctionPass {
40 TargetMachine &TM;
Misha Brukman07218672002-11-22 22:44:32 +000041 MachineFunction *MF;
Misha Brukman07218672002-11-22 22:44:32 +000042 const MRegisterInfo *RegInfo;
Chris Lattner9593fb12002-12-15 19:07:34 +000043 unsigned NumBytesAllocated;
Misha Brukman07218672002-11-22 22:44:32 +000044
45 // Maps SSA Regs => offsets on the stack where these values are stored
Chris Lattnerad44bd92002-12-15 18:15:24 +000046 std::map<unsigned, unsigned> VirtReg2OffsetMap;
Misha Brukman07218672002-11-22 22:44:32 +000047
48 // Maps SSA Regs => physical regs
49 std::map<unsigned, unsigned> SSA2PhysRegMap;
Misha Brukmandc2ec002002-12-03 23:15:19 +000050
51 // Maps physical register to their register classes
Chris Lattnerdd444f92002-12-15 18:38:59 +000052 PhysRegClassMap PhysRegClasses;
Misha Brukmand1bedcc2002-12-12 23:20:31 +000053
54 // Made to combat the incorrect allocation of r2 = add r1, r1
55 std::map<unsigned, unsigned> VirtReg2PhysRegMap;
Misha Brukman07218672002-11-22 22:44:32 +000056
57 // Maps RegClass => which index we can take a register from. Since this is a
58 // simple register allocator, when we need a register of a certain class, we
59 // just take the next available one.
60 std::map<unsigned, unsigned> RegsUsed;
61 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
62
Chris Lattnerc2db1a92002-12-15 19:51:14 +000063 RegAllocSimple(TargetMachine &tm)
64 : TM(tm), RegInfo(tm.getRegisterInfo()), PhysRegClasses(RegInfo) {
Misha Brukman07218672002-11-22 22:44:32 +000065 RegsUsed[RegInfo->getFramePointer()] = 1;
66 RegsUsed[RegInfo->getStackPointer()] = 1;
Misha Brukmancea22452002-12-13 04:34:02 +000067
68 cleanupAfterFunction();
Misha Brukman07218672002-11-22 22:44:32 +000069 }
70
71 bool isAvailableReg(unsigned Reg) {
72 // assert(Reg < MRegisterInfo::FirstVirtualReg && "...");
73 return RegsUsed.find(Reg) == RegsUsed.end();
74 }
75
Chris Lattnerc2db1a92002-12-15 19:51:14 +000076 /// allocateStackSpaceFor - This allocates space for the specified virtual
77 /// register to be held on the stack.
Misha Brukmanf514d512002-12-02 21:11:58 +000078 unsigned allocateStackSpaceFor(unsigned VirtReg,
79 const TargetRegisterClass *regClass);
80
Misha Brukman07218672002-11-22 22:44:32 +000081 /// Given size (in bytes), returns a register that is currently unused
82 /// Side effect: marks that register as being used until manually cleared
83 unsigned getFreeReg(unsigned virtualReg);
84
85 /// Returns all `borrowed' registers back to the free pool
86 void clearAllRegs() {
Chris Lattnerc2db1a92002-12-15 19:51:14 +000087 RegClassIdx.clear();
Misha Brukman07218672002-11-22 22:44:32 +000088 }
89
Misha Brukman972b03f2002-12-13 11:33:22 +000090 /// Invalidates any references, real or implicit, to physical registers
91 ///
92 void invalidatePhysRegs(const MachineInstr *MI) {
93 unsigned Opcode = MI->getOpcode();
94 const MachineInstrInfo &MII = TM.getInstrInfo();
95 const MachineInstrDescriptor &Desc = MII.get(Opcode);
96 const unsigned *regs = Desc.ImplicitUses;
97 while (*regs)
98 RegsUsed[*regs++] = 1;
99
100 regs = Desc.ImplicitDefs;
101 while (*regs)
102 RegsUsed[*regs++] = 1;
Misha Brukman972b03f2002-12-13 11:33:22 +0000103 }
104
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000105 void cleanupAfterFunction() {
Chris Lattnerad44bd92002-12-15 18:15:24 +0000106 VirtReg2OffsetMap.clear();
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000107 SSA2PhysRegMap.clear();
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000108 NumBytesAllocated = 4; // FIXME: This is X86 specific
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000109 }
110
Misha Brukman07218672002-11-22 22:44:32 +0000111 /// Moves value from memory into that register
112 MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000113 moveUseToReg (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000114 MachineBasicBlock::iterator I, unsigned VirtReg,
Misha Brukman07218672002-11-22 22:44:32 +0000115 unsigned &PhysReg);
116
117 /// Saves reg value on the stack (maps virtual register to stack value)
118 MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000119 saveVirtRegToStack (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000120 MachineBasicBlock::iterator I, unsigned VirtReg,
Misha Brukmandc2ec002002-12-03 23:15:19 +0000121 unsigned PhysReg);
122
123 MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000124 savePhysRegToStack (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000125 MachineBasicBlock::iterator I, unsigned PhysReg);
Misha Brukman07218672002-11-22 22:44:32 +0000126
127 /// runOnFunction - Top level implementation of instruction selection for
128 /// the entire function.
129 ///
130 bool runOnMachineFunction(MachineFunction &Fn);
131
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000132 /// AllocateBasicBlock - Register allocate the specified basic block.
133 void AllocateBasicBlock(MachineBasicBlock &MBB);
134
135 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
136 /// in predecessor basic blocks.
137 void EliminatePHINodes(MachineBasicBlock &MBB);
138
Misha Brukman07218672002-11-22 22:44:32 +0000139 bool runOnFunction(Function &Fn) {
140 return runOnMachineFunction(MachineFunction::get(&Fn));
141 }
142 };
143
Misha Brukman59b3eed2002-12-13 10:42:31 +0000144}
Misha Brukman07218672002-11-22 22:44:32 +0000145
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000146/// allocateStackSpaceFor - This allocates space for the specified virtual
147/// register to be held on the stack.
Misha Brukmanf514d512002-12-02 21:11:58 +0000148unsigned RegAllocSimple::allocateStackSpaceFor(unsigned VirtReg,
149 const TargetRegisterClass *regClass)
150{
Chris Lattnerad44bd92002-12-15 18:15:24 +0000151 if (VirtReg2OffsetMap.find(VirtReg) == VirtReg2OffsetMap.end()) {
Chris Lattner9593fb12002-12-15 19:07:34 +0000152 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...
Chris Lattnerad44bd92002-12-15 18:15:24 +0000161 VirtReg2OffsetMap[VirtReg] = NumBytesAllocated;
Chris Lattner9593fb12002-12-15 19:07:34 +0000162
163 // Reserve the space!
164 NumBytesAllocated += RegSize;
Misha Brukmanf514d512002-12-02 21:11:58 +0000165 }
Chris Lattnerad44bd92002-12-15 18:15:24 +0000166 return VirtReg2OffsetMap[VirtReg];
Misha Brukmanf514d512002-12-02 21:11:58 +0000167}
168
Misha Brukman07218672002-11-22 22:44:32 +0000169unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
170 const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
171 unsigned physReg;
172 assert(regClass);
173 if (RegClassIdx.find(regClass) != RegClassIdx.end()) {
174 unsigned regIdx = RegClassIdx[regClass]++;
175 assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
176 physReg = regClass->getRegister(regIdx);
177 } else {
178 physReg = regClass->getRegister(0);
179 // assert(physReg < regClass->getNumRegs() && "No registers in class!");
180 RegClassIdx[regClass] = 1;
181 }
182
183 if (isAvailableReg(physReg))
184 return physReg;
185 else {
186 return getFreeReg(virtualReg);
187 }
188}
189
190MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000191RegAllocSimple::moveUseToReg (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000192 MachineBasicBlock::iterator I,
Misha Brukman07218672002-11-22 22:44:32 +0000193 unsigned VirtReg, unsigned &PhysReg)
194{
195 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
196 assert(regClass);
197
Misha Brukmanf514d512002-12-02 21:11:58 +0000198 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
Misha Brukman07218672002-11-22 22:44:32 +0000199 PhysReg = getFreeReg(VirtReg);
200
Misha Brukmanf514d512002-12-02 21:11:58 +0000201 // Add move instruction(s)
Chris Lattner198ab642002-12-15 20:06:35 +0000202 return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
Misha Brukmanf514d512002-12-02 21:11:58 +0000203 RegInfo->getFramePointer(),
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000204 -stackOffset, regClass->getDataSize());
Misha Brukman07218672002-11-22 22:44:32 +0000205}
206
207MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000208RegAllocSimple::saveVirtRegToStack (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000209 MachineBasicBlock::iterator I,
Misha Brukmandc2ec002002-12-03 23:15:19 +0000210 unsigned VirtReg, unsigned PhysReg)
Misha Brukman07218672002-11-22 22:44:32 +0000211{
212 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
213 assert(regClass);
Misha Brukman07218672002-11-22 22:44:32 +0000214
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000215 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
Misha Brukmanf514d512002-12-02 21:11:58 +0000216
Misha Brukman07218672002-11-22 22:44:32 +0000217 // Add move instruction(s)
Chris Lattner198ab642002-12-15 20:06:35 +0000218 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
Misha Brukman07218672002-11-22 22:44:32 +0000219 RegInfo->getFramePointer(),
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000220 -stackOffset, regClass->getDataSize());
Misha Brukman07218672002-11-22 22:44:32 +0000221}
222
Misha Brukmandc2ec002002-12-03 23:15:19 +0000223MachineBasicBlock::iterator
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000224RegAllocSimple::savePhysRegToStack (MachineBasicBlock &MBB,
Misha Brukman203b7692002-12-13 09:54:36 +0000225 MachineBasicBlock::iterator I,
Misha Brukmandc2ec002002-12-03 23:15:19 +0000226 unsigned PhysReg)
227{
228 const TargetRegisterClass* regClass = MF->getRegClass(PhysReg);
229 assert(regClass);
230
231 unsigned offset = allocateStackSpaceFor(PhysReg, regClass);
232
233 // Add move instruction(s)
Chris Lattner198ab642002-12-15 20:06:35 +0000234 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
Misha Brukmandc2ec002002-12-03 23:15:19 +0000235 RegInfo->getFramePointer(),
236 offset, regClass->getDataSize());
237}
238
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000239/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
240/// predecessor basic blocks.
241void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
242 while (MBB.front()->getOpcode() == 0) {
243 MachineInstr *MI = MBB.front();
244 // get rid of the phi
245 MBB.erase(MBB.begin());
246
247 // a preliminary pass that will invalidate any registers that
248 // are used by the instruction (including implicit uses)
249 invalidatePhysRegs(MI);
250
251 DEBUG(std::cerr << "num invalid regs: " << RegsUsed.size() << "\n");
252
253 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
254 MachineOperand &targetReg = MI->getOperand(0);
255
256 // If it's a virtual register, allocate a physical one
257 // otherwise, just use whatever register is there now
258 // note: it MUST be a register -- we're assigning to it
259 unsigned virtualReg = (unsigned) targetReg.getAllocatedRegNum();
260 unsigned physReg;
261 if (targetReg.isVirtualRegister()) {
262 physReg = getFreeReg(virtualReg);
263 } else {
264 physReg = virtualReg;
265 }
266
267 // Find the register class of the target register: should be the
268 // same as the values we're trying to store there
269 const TargetRegisterClass* regClass = PhysRegClasses[physReg];
270 assert(regClass && "Target register class not found!");
271 unsigned dataSize = regClass->getDataSize();
272
273 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
274 MachineOperand &opVal = MI->getOperand(i-1);
275
276 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
277 // source path the phi
278 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
279 MachineBasicBlock::iterator opI = opBlock.end();
280 MachineInstr *opMI = *--opI;
281 const MachineInstrInfo &MII = TM.getInstrInfo();
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000282
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000283 // must backtrack over ALL the branches in the previous block, until no
284 // more
285 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
286 opMI = *--opI;
287
288 // move back to the first branch instruction so new instructions
289 // are inserted right in front of it and not in front of a non-branch
290 if (!MII.isBranch(opMI->getOpcode()))
291 ++opI;
292
293 // Retrieve the constant value from this op, move it to target
294 // register of the phi
295 if (opVal.isImmediate()) {
Chris Lattner198ab642002-12-15 20:06:35 +0000296 opI = RegInfo->moveImm2Reg(opBlock, opI, physReg,
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000297 (unsigned) opVal.getImmedValue(),
298 dataSize);
299 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
300 } else {
301 // Allocate a physical register and add a move in the BB
302 unsigned opVirtualReg = (unsigned) opVal.getAllocatedRegNum();
303 unsigned opPhysReg; // = getFreeReg(opVirtualReg);
304 opI = moveUseToReg(opBlock, opI, opVirtualReg, physReg);
305 //opI = RegInfo->moveReg2Reg(opBlock, opI, physReg, opPhysReg,
306 // dataSize);
307 // Save that register value to the stack of the TARGET REG
308 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
309 }
310
311 // make regs available to other instructions
312 clearAllRegs();
313 }
314
315 // really delete the instruction
316 delete MI;
317 }
318}
319
320
321void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
322 // Handle PHI instructions specially: add moves to each pred block
323 EliminatePHINodes(MBB);
324
325 //loop over each basic block
326 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
327 MachineInstr *MI = *I;
328
329 // a preliminary pass that will invalidate any registers that
330 // are used by the instruction (including implicit uses)
331 invalidatePhysRegs(MI);
332
333 // Loop over uses, move from memory into registers
334 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
335 MachineOperand &op = MI->getOperand(i);
336
337 if (op.isImmediate()) {
338 DEBUG(std::cerr << "const\n");
339 } else if (op.isVirtualRegister()) {
340 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
341 DEBUG(std::cerr << "op: " << op << "\n");
342 DEBUG(std::cerr << "\t inst[" << i << "]: ";
343 MI->print(std::cerr, TM));
344
345 // make sure the same virtual register maps to the same physical
346 // register in any given instruction
347 unsigned physReg;
348 if (VirtReg2PhysRegMap.find(virtualReg) != VirtReg2PhysRegMap.end()) {
349 physReg = VirtReg2PhysRegMap[virtualReg];
350 } else {
351 if (op.opIsDef()) {
352 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
353 // must be same register number as the first operand
354 // This maps a = b + c into b += c, and saves b into a's spot
355 physReg = (unsigned) MI->getOperand(1).getAllocatedRegNum();
356 } else {
357 physReg = getFreeReg(virtualReg);
358 }
359 MachineBasicBlock::iterator J = I;
360 J = saveVirtRegToStack(MBB, ++J, virtualReg, physReg);
361 I = --J;
362 } else {
363 I = moveUseToReg(MBB, I, virtualReg, physReg);
364 }
365 VirtReg2PhysRegMap[virtualReg] = physReg;
366 }
367 MI->SetMachineOperandReg(i, physReg);
368 DEBUG(std::cerr << "virt: " << virtualReg <<
369 ", phys: " << op.getAllocatedRegNum() << "\n");
370 }
371 }
372
373 clearAllRegs();
374 VirtReg2PhysRegMap.clear();
375 }
376}
377
378bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
Misha Brukman07218672002-11-22 22:44:32 +0000379 DEBUG(std::cerr << "Machine Function " << "\n");
380 MF = &Fn;
Misha Brukmandc2ec002002-12-03 23:15:19 +0000381
Misha Brukman07218672002-11-22 22:44:32 +0000382 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
383 MBB != MBBe; ++MBB)
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000384 AllocateBasicBlock(*MBB);
Misha Brukman07218672002-11-22 22:44:32 +0000385
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000386 // add prologue we should preserve callee-save registers...
Chris Lattner198ab642002-12-15 20:06:35 +0000387 RegInfo->emitPrologue(Fn, NumBytesAllocated);
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000388
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000389 const MachineInstrInfo &MII = TM.getInstrInfo();
390
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000391 // add epilogue to restore the callee-save registers
392 // loop over the basic block
393 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000394 MBB != MBBe; ++MBB) {
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000395 // check if last instruction is a RET
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000396 MachineBasicBlock::iterator I = MBB->end();
397 MachineInstr *MI = *--I;
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000398 if (MII.isReturn(MI->getOpcode())) {
399 // this block has a return instruction, add epilogue
Chris Lattner198ab642002-12-15 20:06:35 +0000400 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
Misha Brukmandd46e2a2002-12-04 23:58:08 +0000401 }
402 }
Misha Brukman07218672002-11-22 22:44:32 +0000403
Chris Lattnerc2db1a92002-12-15 19:51:14 +0000404 cleanupAfterFunction();
Misha Brukman07218672002-11-22 22:44:32 +0000405 return false; // We never modify the LLVM itself.
406}
407
408Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
409 return new RegAllocSimple(TM);
410}