LLVM API Documentation

RegAllocSimple.cpp

Go to the documentation of this file.
00001 //===-- RegAllocSimple.cpp - A simple generic register allocator ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a simple register allocator. *Very* simple: It immediate
00011 // spills every value right after it is computed, and it reloads all used
00012 // operands from the spill area to temporary registers before each instruction.
00013 // It does not keep values in registers across instructions.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define DEBUG_TYPE "regalloc"
00018 #include "llvm/CodeGen/Passes.h"
00019 #include "llvm/CodeGen/MachineFunctionPass.h"
00020 #include "llvm/CodeGen/MachineInstr.h"
00021 #include "llvm/CodeGen/SSARegMap.h"
00022 #include "llvm/CodeGen/MachineFrameInfo.h"
00023 #include "llvm/Target/TargetInstrInfo.h"
00024 #include "llvm/Target/TargetMachine.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/ADT/STLExtras.h"
00028 #include <iostream>
00029 using namespace llvm;
00030 
00031 namespace {
00032   Statistic<> NumStores("ra-simple", "Number of stores added");
00033   Statistic<> NumLoads ("ra-simple", "Number of loads added");
00034 
00035   class RegAllocSimple : public MachineFunctionPass {
00036     MachineFunction *MF;
00037     const TargetMachine *TM;
00038     const MRegisterInfo *RegInfo;
00039     bool *PhysRegsEverUsed;
00040 
00041     // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
00042     // these values are spilled
00043     std::map<unsigned, int> StackSlotForVirtReg;
00044 
00045     // RegsUsed - Keep track of what registers are currently in use.  This is a
00046     // bitset.
00047     std::vector<bool> RegsUsed;
00048 
00049     // RegClassIdx - Maps RegClass => which index we can take a register
00050     // from. Since this is a simple register allocator, when we need a register
00051     // of a certain class, we just take the next available one.
00052     std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
00053 
00054   public:
00055     virtual const char *getPassName() const {
00056       return "Simple Register Allocator";
00057     }
00058 
00059     /// runOnMachineFunction - Register allocate the whole function
00060     bool runOnMachineFunction(MachineFunction &Fn);
00061 
00062     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00063       AU.addRequiredID(PHIEliminationID);           // Eliminate PHI nodes
00064       MachineFunctionPass::getAnalysisUsage(AU);
00065     }
00066   private:
00067     /// AllocateBasicBlock - Register allocate the specified basic block.
00068     void AllocateBasicBlock(MachineBasicBlock &MBB);
00069 
00070     /// getStackSpaceFor - This returns the offset of the specified virtual
00071     /// register on the stack, allocating space if necessary.
00072     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
00073 
00074     /// Given a virtual register, return a compatible physical register that is
00075     /// currently unused.
00076     ///
00077     /// Side effect: marks that register as being used until manually cleared
00078     ///
00079     unsigned getFreeReg(unsigned virtualReg);
00080 
00081     /// Moves value from memory into that register
00082     unsigned reloadVirtReg(MachineBasicBlock &MBB,
00083                            MachineBasicBlock::iterator I, unsigned VirtReg);
00084 
00085     /// Saves reg value on the stack (maps virtual register to stack value)
00086     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
00087                       unsigned VirtReg, unsigned PhysReg);
00088   };
00089 
00090 }
00091 
00092 /// getStackSpaceFor - This allocates space for the specified virtual
00093 /// register to be held on the stack.
00094 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
00095                                      const TargetRegisterClass *RC) {
00096   // Find the location VirtReg would belong...
00097   std::map<unsigned, int>::iterator I =
00098     StackSlotForVirtReg.lower_bound(VirtReg);
00099 
00100   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
00101     return I->second;          // Already has space allocated?
00102 
00103   // Allocate a new stack object for this spill location...
00104   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
00105                                                        RC->getAlignment());
00106 
00107   // Assign the slot...
00108   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
00109 
00110   return FrameIdx;
00111 }
00112 
00113 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
00114   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
00115   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
00116   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
00117 
00118   while (1) {
00119     unsigned regIdx = RegClassIdx[RC]++;
00120     assert(RI+regIdx != RE && "Not enough registers!");
00121     unsigned PhysReg = *(RI+regIdx);
00122 
00123     if (!RegsUsed[PhysReg]) {
00124       PhysRegsEverUsed[PhysReg] = true;
00125       return PhysReg;
00126     }
00127   }
00128 }
00129 
00130 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
00131                                        MachineBasicBlock::iterator I,
00132                                        unsigned VirtReg) {
00133   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
00134   int FrameIdx = getStackSpaceFor(VirtReg, RC);
00135   unsigned PhysReg = getFreeReg(VirtReg);
00136 
00137   // Add move instruction(s)
00138   ++NumLoads;
00139   RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
00140   return PhysReg;
00141 }
00142 
00143 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
00144                                   MachineBasicBlock::iterator I,
00145                                   unsigned VirtReg, unsigned PhysReg) {
00146   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
00147   int FrameIdx = getStackSpaceFor(VirtReg, RC);
00148 
00149   // Add move instruction(s)
00150   ++NumStores;
00151   RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIdx, RC);
00152 }
00153 
00154 
00155 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
00156   // loop over each instruction
00157   for (MachineBasicBlock::iterator MI = MBB.begin(); MI != MBB.end(); ++MI) {
00158     // Made to combat the incorrect allocation of r2 = add r1, r1
00159     std::map<unsigned, unsigned> Virt2PhysRegMap;
00160 
00161     RegsUsed.resize(RegInfo->getNumRegs());
00162 
00163     // This is a preliminary pass that will invalidate any registers that are
00164     // used by the instruction (including implicit uses).
00165     unsigned Opcode = MI->getOpcode();
00166     const TargetInstrDescriptor &Desc = TM->getInstrInfo()->get(Opcode);
00167     const unsigned *Regs;
00168     for (Regs = Desc.ImplicitUses; *Regs; ++Regs)
00169       RegsUsed[*Regs] = true;
00170 
00171     for (Regs = Desc.ImplicitDefs; *Regs; ++Regs) {
00172       RegsUsed[*Regs] = true;
00173       PhysRegsEverUsed[*Regs] = true;
00174     }
00175 
00176     // Loop over uses, move from memory into registers.
00177     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
00178       MachineOperand &op = MI->getOperand(i);
00179 
00180       if (op.isRegister() && op.getReg() &&
00181           MRegisterInfo::isVirtualRegister(op.getReg())) {
00182         unsigned virtualReg = (unsigned) op.getReg();
00183         DEBUG(std::cerr << "op: " << op << "\n");
00184         DEBUG(std::cerr << "\t inst[" << i << "]: ";
00185               MI->print(std::cerr, TM));
00186 
00187         // make sure the same virtual register maps to the same physical
00188         // register in any given instruction
00189         unsigned physReg = Virt2PhysRegMap[virtualReg];
00190         if (physReg == 0) {
00191           if (op.isDef()) {
00192             if (!TM->getInstrInfo()->isTwoAddrInstr(MI->getOpcode()) || i) {
00193               physReg = getFreeReg(virtualReg);
00194             } else {
00195               // must be same register number as the first operand
00196               // This maps a = b + c into b += c, and saves b into a's spot
00197               assert(MI->getOperand(1).isRegister()  &&
00198                      MI->getOperand(1).getReg() &&
00199                      MI->getOperand(1).isUse() &&
00200                      "Two address instruction invalid!");
00201 
00202               physReg = MI->getOperand(1).getReg();
00203               spillVirtReg(MBB, next(MI), virtualReg, physReg);
00204               MI->getOperand(1).setDef();
00205               MI->RemoveOperand(0);
00206               break; // This is the last operand to process
00207             }
00208             spillVirtReg(MBB, next(MI), virtualReg, physReg);
00209           } else {
00210             physReg = reloadVirtReg(MBB, MI, virtualReg);
00211             Virt2PhysRegMap[virtualReg] = physReg;
00212           }
00213         }
00214         MI->SetMachineOperandReg(i, physReg);
00215         DEBUG(std::cerr << "virt: " << virtualReg <<
00216               ", phys: " << op.getReg() << "\n");
00217       }
00218     }
00219     RegClassIdx.clear();
00220     RegsUsed.clear();
00221   }
00222 }
00223 
00224 
00225 /// runOnMachineFunction - Register allocate the whole function
00226 ///
00227 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
00228   DEBUG(std::cerr << "Machine Function " << "\n");
00229   MF = &Fn;
00230   TM = &MF->getTarget();
00231   RegInfo = TM->getRegisterInfo();
00232 
00233   PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
00234   std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
00235   Fn.setUsedPhysRegs(PhysRegsEverUsed);
00236 
00237   // Loop over all of the basic blocks, eliminating virtual register references
00238   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
00239        MBB != MBBe; ++MBB)
00240     AllocateBasicBlock(*MBB);
00241 
00242   StackSlotForVirtReg.clear();
00243   return true;
00244 }
00245 
00246 FunctionPass *llvm::createSimpleRegisterAllocator() {
00247   return new RegAllocSimple();
00248 }