1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
3 // This register allocator allocates registers to a basic block at a time,
4 // attempting to keep values in registers and reusing registers as appropriate.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/MachineFunction.h"
9 #include "llvm/CodeGen/MachineInstr.h"
10 #include "llvm/Target/MachineInstrInfo.h"
11 #include "llvm/Target/TargetMachine.h"
12 #include "Support/Statistic.h"
15 /// PhysRegClassMap - Construct a mapping of physical register numbers to their
18 /// NOTE: This class will eventually be pulled out to somewhere shared.
20 class PhysRegClassMap {
21 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
23 PhysRegClassMap(const MRegisterInfo *RI) {
24 for (MRegisterInfo::const_iterator I = RI->regclass_begin(),
25 E = RI->regclass_end(); I != E; ++I)
26 for (unsigned i=0; i < (*I)->getNumRegs(); ++i)
27 PhysReg2RegClassMap[(*I)->getRegister(i)] = *I;
30 const TargetRegisterClass *operator[](unsigned Reg) {
31 assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
32 return PhysReg2RegClassMap[Reg];
35 const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
39 Statistic<> NumSpilled ("ra-local", "Number of registers spilled");
40 Statistic<> NumReloaded("ra-local", "Number of registers reloaded");
42 class RA : public FunctionPass {
45 const MRegisterInfo *RegInfo;
46 unsigned NumBytesAllocated;
47 PhysRegClassMap PhysRegClasses;
49 // Maps SSA Regs => offsets on the stack where these values are stored
50 std::map<unsigned, unsigned> VirtReg2OffsetMap;
52 // Virt2PhysRegMap - This map contains entries for each virtual register
53 // that is currently available in a physical register.
55 std::map<unsigned, unsigned> Virt2PhysRegMap;
57 // PhysRegsUsed - This map contains entries for each physical register that
58 // currently has a value (ie, it is in Virt2PhysRegMap). The value mapped
59 // to is the virtual register corresponding to the physical register (the
60 // inverse of the Virt2PhysRegMap), or 0. The value is set to 0 if this
61 // register is pinned because it is used by a future instruction.
63 std::map<unsigned, unsigned> PhysRegsUsed;
65 // PhysRegsUseOrder - This contains a list of the physical registers that
66 // currently have a virtual register value in them. This list provides an
67 // ordering of registers, imposing a reallocation order. This list is only
68 // used if all registers are allocated and we have to spill one, in which
69 // case we spill the least recently used register. Entries at the front of
70 // the list are the least recently used registers, entries at the back are
71 // the most recently used.
73 std::vector<unsigned> PhysRegsUseOrder;
75 void MarkPhysRegRecentlyUsed(unsigned Reg) {
76 assert(std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg) !=
77 PhysRegsUseOrder.end() && "Register isn't used yet!");
78 if (PhysRegsUseOrder.back() != Reg) {
79 for (unsigned i = PhysRegsUseOrder.size(); ; --i)
80 if (PhysRegsUseOrder[i-1] == Reg) { // remove from middle
81 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
82 PhysRegsUseOrder.push_back(Reg); // Add it to the end of the list
91 : TM(tm), RegInfo(tm.getRegisterInfo()), PhysRegClasses(RegInfo) {
92 cleanupAfterFunction();
95 bool runOnFunction(Function &Fn) {
96 return runOnMachineFunction(MachineFunction::get(&Fn));
99 virtual const char *getPassName() const {
100 return "Local Register Allocator";
104 /// runOnMachineFunction - Register allocate the whole function
105 bool runOnMachineFunction(MachineFunction &Fn);
107 /// AllocateBasicBlock - Register allocate the specified basic block.
108 void AllocateBasicBlock(MachineBasicBlock &MBB);
110 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
111 /// in predecessor basic blocks.
112 void EliminatePHINodes(MachineBasicBlock &MBB);
114 /// isAllocatableRegister - A register may be used by the program if it's
115 /// not the stack or frame pointer.
116 bool isAllocatableRegister(unsigned R) const {
117 unsigned FP = RegInfo->getFramePointer(), SP = RegInfo->getStackPointer();
118 // Don't allocate the Frame or Stack pointers
119 if (R == FP || R == SP)
122 // Check to see if this register aliases the stack or frame pointer...
123 if (const unsigned *AliasSet = RegInfo->getAliasSet(R)) {
124 for (unsigned i = 0; AliasSet[i]; ++i)
125 if (AliasSet[i] == FP || AliasSet[i] == SP)
131 /// getStackSpaceFor - This returns the offset of the specified virtual
132 /// register on the stack, allocating space if neccesary.
133 unsigned getStackSpaceFor(unsigned VirtReg,
134 const TargetRegisterClass *regClass);
136 void cleanupAfterFunction() {
137 VirtReg2OffsetMap.clear();
138 NumBytesAllocated = 4; // FIXME: This is X86 specific
142 /// spillVirtReg - This method spills the value specified by PhysReg into
143 /// the virtual register slot specified by VirtReg. It then updates the RA
144 /// data structures to indicate the fact that PhysReg is now available.
146 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
147 unsigned VirtReg, unsigned PhysReg);
149 /// spillPhysReg - This method spills the specified physical register into
150 /// the virtual register slot associated with it.
152 void spillPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
154 assert(PhysRegsUsed.find(PhysReg) != PhysRegsUsed.end() &&
155 "Physical register is not used: cannot spill it!");
156 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
159 void AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
162 /// getFreeReg - Find a physical register to hold the specified virtual
163 /// register. If all compatible physical registers are used, this method
164 /// spills the last used virtual register to the stack, and uses that
167 unsigned getFreeReg(MachineBasicBlock &MBB,
168 MachineBasicBlock::iterator &I,
169 unsigned virtualReg);
171 /// reloadVirtReg - This method loads the specified virtual register into a
172 /// physical register, returning the physical register chosen. This updates
173 /// the regalloc data structures to reflect the fact that the virtual reg is
174 /// now alive in a physical register, and the previous one isn't.
176 unsigned reloadVirtReg(MachineBasicBlock &MBB,
177 MachineBasicBlock::iterator &I, unsigned VirtReg);
182 /// getStackSpaceFor - This allocates space for the specified virtual
183 /// register to be held on the stack.
184 unsigned RA::getStackSpaceFor(unsigned VirtReg,
185 const TargetRegisterClass *RegClass) {
186 // Find the location VirtReg would belong...
187 std::map<unsigned, unsigned>::iterator I =
188 VirtReg2OffsetMap.lower_bound(VirtReg);
190 if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
191 return I->second; // Already has space allocated?
193 unsigned RegSize = RegClass->getDataSize();
195 // Align NumBytesAllocated. We should be using TargetData alignment stuff
196 // to determine this, but we don't know the LLVM type associated with the
197 // virtual register. Instead, just align to a multiple of the size for now.
198 NumBytesAllocated += RegSize-1;
199 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
201 // Assign the slot...
202 VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
204 // Reserve the space!
205 NumBytesAllocated += RegSize;
206 return NumBytesAllocated-RegSize;
209 /// spillVirtReg - This method spills the value specified by PhysReg into the
210 /// virtual register slot specified by VirtReg. It then updates the RA data
211 /// structures to indicate the fact that PhysReg is now available.
213 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
214 unsigned VirtReg, unsigned PhysReg) {
215 // If this is just a marker register, we don't need to spill it.
217 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
218 unsigned stackOffset = getStackSpaceFor(VirtReg, RegClass);
220 // Add move instruction(s)
221 I = RegInfo->storeReg2RegOffset(MBB, I, PhysReg, RegInfo->getFramePointer(),
222 -stackOffset, RegClass->getDataSize());
223 ++NumSpilled; // Update statistics
224 Virt2PhysRegMap.erase(VirtReg); // VirtReg no longer available
226 PhysRegsUsed.erase(PhysReg); // PhyReg no longer used
228 std::vector<unsigned>::iterator It =
229 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
230 assert(It != PhysRegsUseOrder.end() &&
231 "Spilled a physical register, but it was not in use list!");
232 PhysRegsUseOrder.erase(It);
235 /// getFreeReg - Find a physical register to hold the specified virtual
236 /// register. If all compatible physical registers are used, this method spills
237 /// the last used virtual register to the stack, and uses that register.
239 unsigned RA::getFreeReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
241 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
242 unsigned PhysReg = 0;
244 for (TargetRegisterClass::iterator It = RegClass->begin(),E = RegClass->end();
247 if (PhysRegsUsed.find(R) == PhysRegsUsed.end()) // Is reg unused?
248 if (isAllocatableRegister(R)) {
249 // Found an unused register!
255 // If we didn't find an unused register, scavange one now!
258 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
259 while (PhysRegClasses[PhysRegsUseOrder[i]] != RegClass) {
261 assert(i != PhysRegsUseOrder.size() &&
262 "Couldn't find a register of the appropriate class!");
265 // At this point PhysRegsUseOrder[i] is the least recently used register of
266 // compatible register class. Spill it to memory and reap its remains.
267 PhysReg = PhysRegsUseOrder[i];
268 spillPhysReg(MBB, I, PhysReg);
271 // If the selected register aliases any other registers, we must make sure to
272 // spill them as well...
273 if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg))
274 for (unsigned i = 0; AliasSet[i]; ++i)
275 if (PhysRegsUsed.count(AliasSet[i])) // Spill aliased register...
276 spillPhysReg(MBB, I, AliasSet[i]);
279 // Now that we know which register we need to assign this to, do it now!
280 AssignVirtToPhysReg(VirtReg, PhysReg);
284 void RA::AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
285 assert(PhysRegsUsed.find(PhysReg) == PhysRegsUsed.end() &&
286 "Phys reg already assigned!");
287 // Update information to note the fact that this register was just used, and
289 PhysRegsUsed[PhysReg] = VirtReg;
290 Virt2PhysRegMap[VirtReg] = PhysReg;
291 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
295 /// reloadVirtReg - This method loads the specified virtual register into a
296 /// physical register, returning the physical register chosen. This updates the
297 /// regalloc data structures to reflect the fact that the virtual reg is now
298 /// alive in a physical register, and the previous one isn't.
300 unsigned RA::reloadVirtReg(MachineBasicBlock &MBB,
301 MachineBasicBlock::iterator &I,
303 std::map<unsigned, unsigned>::iterator It = Virt2PhysRegMap.find(VirtReg);
304 if (It != Virt2PhysRegMap.end()) {
305 MarkPhysRegRecentlyUsed(It->second);
306 return It->second; // Already have this value available!
309 unsigned PhysReg = getFreeReg(MBB, I, VirtReg);
311 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
312 unsigned StackOffset = getStackSpaceFor(VirtReg, RegClass);
314 // Add move instruction(s)
315 I = RegInfo->loadRegOffset2Reg(MBB, I, PhysReg, RegInfo->getFramePointer(),
316 -StackOffset, RegClass->getDataSize());
317 ++NumReloaded; // Update statistics
321 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
322 /// predecessor basic blocks.
324 void RA::EliminatePHINodes(MachineBasicBlock &MBB) {
325 const MachineInstrInfo &MII = TM.getInstrInfo();
327 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
328 MachineInstr *MI = MBB.front();
329 // Unlink the PHI node from the basic block... but don't delete the PHI yet
330 MBB.erase(MBB.begin());
332 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
333 assert(MI->getOperand(0).isVirtualRegister() &&
334 "PHI node doesn't write virt reg?");
336 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
338 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
339 MachineOperand &opVal = MI->getOperand(i-1);
341 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
342 // source path the phi
343 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
345 // Check to make sure we haven't already emitted the copy for this block.
346 // This can happen because PHI nodes may have multiple entries for the
347 // same basic block. It doesn't matter which entry we use though, because
348 // all incoming values are guaranteed to be the same for a particular bb.
350 // Note that this is N^2 in the number of phi node entries, but since the
351 // # of entries is tiny, this is not a problem.
353 bool HaveNotEmitted = true;
354 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
355 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
356 HaveNotEmitted = false;
360 if (HaveNotEmitted) {
361 MachineBasicBlock::iterator opI = opBlock.end();
362 MachineInstr *opMI = *--opI;
364 // must backtrack over ALL the branches in the previous block
365 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
368 // move back to the first branch instruction so new instructions
369 // are inserted right in front of it and not in front of a non-branch
370 if (!MII.isBranch(opMI->getOpcode()))
373 unsigned dataSize = MF->getRegClass(virtualReg)->getDataSize();
375 // Retrieve the constant value from this op, move it to target
376 // register of the phi
377 if (opVal.isImmediate()) {
378 opI = RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
379 (unsigned) opVal.getImmedValue(),
382 opI = RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
383 opVal.getAllocatedRegNum(), dataSize);
388 // really delete the PHI instruction now!
393 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
394 // loop over each instruction
395 MachineBasicBlock::iterator I = MBB.begin();
396 for (; I != MBB.end(); ++I) {
397 MachineInstr *MI = *I;
399 // Loop over all of the operands of the instruction, spilling registers that
400 // are defined, and marking explicit destinations in the PhysRegsUsed map.
401 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
402 if (MI->getOperand(i).opIsDef() &&
403 MI->getOperand(i).isPhysicalRegister()) {
404 unsigned Reg = MI->getOperand(i).getAllocatedRegNum();
405 unsigned VMap = PhysRegsUsed[Reg];
406 if (VMap) { // Spill the value in this register...
407 spillVirtReg(MBB, I, VMap, Reg);
408 PhysRegsUsed[Reg] = 0; // It's free now, and it's reserved
410 PhysRegsUseOrder.push_back(Reg);
413 // FIXME: Loop over the implicit defs, spilling them, as above.
416 // FIXME: Loop over the implicit uses, making sure that they are at the head
417 // of the use order list, so they don't get reallocated.
419 // Loop over all of the operands again, getting the used operands into
420 // registers. This has the potiential to spill incoming values because we
421 // are out of registers.
423 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
424 if (MI->getOperand(i).opIsUse() &&
425 MI->getOperand(i).isVirtualRegister()) {
426 unsigned VirtSrcReg = MI->getOperand(i).getAllocatedRegNum();
427 unsigned PhysSrcReg = reloadVirtReg(MBB, I, VirtSrcReg);
428 MI->SetMachineOperandReg(i, PhysSrcReg); // Assign the input register
431 // Okay, we have allocated all of the source operands and spilled any values
432 // that would be destroyed by defs of this instruction. Loop over the
433 // implicit defs and assign them to a register, spilling the incoming value
434 // if we need to scavange a register.
436 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
437 if (MI->getOperand(i).opIsDef() &&
438 !MI->getOperand(i).isPhysicalRegister()) {
439 unsigned DestVirtReg = MI->getOperand(i).getAllocatedRegNum();
440 unsigned DestPhysReg;
442 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
443 // must be same register number as the first operand
444 // This maps a = b + c into b += c, and saves b into a's spot
445 assert(MI->getOperand(1).isRegister() &&
446 MI->getOperand(1).getAllocatedRegNum() &&
447 MI->getOperand(1).opIsUse() &&
448 "Two address instruction invalid!");
449 DestPhysReg = MI->getOperand(1).getAllocatedRegNum();
451 // Spill the incoming value, because we are about to change the
452 // register contents.
453 spillPhysReg(MBB, I, DestPhysReg);
454 AssignVirtToPhysReg(DestVirtReg, DestPhysReg);
456 DestPhysReg = getFreeReg(MBB, I, DestVirtReg);
458 MI->SetMachineOperandReg(i, DestPhysReg); // Assign the output register
462 // Rewind the iterator to point to the first flow control instruction...
463 const MachineInstrInfo &MII = TM.getInstrInfo();
467 } while ((MII.isReturn((*I)->getOpcode()) ||
468 MII.isBranch((*I)->getOpcode())) && I != MBB.begin());
470 if (!MII.isReturn((*I)->getOpcode()) && !MII.isBranch((*I)->getOpcode()))
473 // Spill all physical registers holding virtual registers now.
474 while (!PhysRegsUsed.empty())
475 spillVirtReg(MBB, I, PhysRegsUsed.begin()->second,
476 PhysRegsUsed.begin()->first);
478 assert(Virt2PhysRegMap.empty() && "Virtual registers still in phys regs?");
479 assert(PhysRegsUseOrder.empty() && "Physical regs still allocated?");
482 /// runOnMachineFunction - Register allocate the whole function
484 bool RA::runOnMachineFunction(MachineFunction &Fn) {
485 DEBUG(std::cerr << "Machine Function " << "\n");
488 // First pass: eliminate PHI instructions by inserting copies into predecessor
490 // FIXME: In this pass, count how many uses of each VReg exist!
491 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
493 EliminatePHINodes(*MBB);
495 // Loop over all of the basic blocks, eliminating virtual register references
496 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
498 AllocateBasicBlock(*MBB);
500 // Round stack allocation up to a nice alignment to keep the stack aligned
501 // FIXME: This is X86 specific! Move to frame manager
502 NumBytesAllocated = (NumBytesAllocated + 3) & ~3;
504 // Add prologue to the function...
505 RegInfo->emitPrologue(Fn, NumBytesAllocated);
507 const MachineInstrInfo &MII = TM.getInstrInfo();
509 // Add epilogue to restore the callee-save registers in each exiting block
510 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
511 MBB != MBBe; ++MBB) {
512 // If last instruction is a return instruction, add an epilogue
513 if (MII.isReturn(MBB->back()->getOpcode()))
514 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
517 cleanupAfterFunction();
521 Pass *createLocalRegisterAllocator(TargetMachine &TM) {