LLVM API Documentation

RegAllocBasic.cpp
Go to the documentation of this file.
00001 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the RABasic function pass, which provides a minimal
00011 // implementation of the basic register allocator.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "AllocationOrder.h"
00017 #include "LiveDebugVariables.h"
00018 #include "RegAllocBase.h"
00019 #include "Spiller.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/CodeGen/CalcSpillWeights.h"
00022 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00023 #include "llvm/CodeGen/LiveRangeEdit.h"
00024 #include "llvm/CodeGen/LiveRegMatrix.h"
00025 #include "llvm/CodeGen/LiveStackAnalysis.h"
00026 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00027 #include "llvm/CodeGen/MachineFunctionPass.h"
00028 #include "llvm/CodeGen/MachineInstr.h"
00029 #include "llvm/CodeGen/MachineLoopInfo.h"
00030 #include "llvm/CodeGen/MachineRegisterInfo.h"
00031 #include "llvm/CodeGen/RegAllocRegistry.h"
00032 #include "llvm/CodeGen/VirtRegMap.h"
00033 #include "llvm/PassAnalysisSupport.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include "llvm/Target/TargetRegisterInfo.h"
00038 #include <cstdlib>
00039 #include <queue>
00040 
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "regalloc"
00044 
00045 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
00046                                       createBasicRegisterAllocator);
00047 
00048 namespace {
00049   struct CompSpillWeight {
00050     bool operator()(LiveInterval *A, LiveInterval *B) const {
00051       return A->weight < B->weight;
00052     }
00053   };
00054 }
00055 
00056 namespace {
00057 /// RABasic provides a minimal implementation of the basic register allocation
00058 /// algorithm. It prioritizes live virtual registers by spill weight and spills
00059 /// whenever a register is unavailable. This is not practical in production but
00060 /// provides a useful baseline both for measuring other allocators and comparing
00061 /// the speed of the basic algorithm against other styles of allocators.
00062 class RABasic : public MachineFunctionPass, public RegAllocBase
00063 {
00064   // context
00065   MachineFunction *MF;
00066 
00067   // state
00068   std::unique_ptr<Spiller> SpillerInstance;
00069   std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
00070                       CompSpillWeight> Queue;
00071 
00072   // Scratch space.  Allocated here to avoid repeated malloc calls in
00073   // selectOrSplit().
00074   BitVector UsableRegs;
00075 
00076 public:
00077   RABasic();
00078 
00079   /// Return the pass name.
00080   const char* getPassName() const override {
00081     return "Basic Register Allocator";
00082   }
00083 
00084   /// RABasic analysis usage.
00085   void getAnalysisUsage(AnalysisUsage &AU) const override;
00086 
00087   void releaseMemory() override;
00088 
00089   Spiller &spiller() override { return *SpillerInstance; }
00090 
00091   void enqueue(LiveInterval *LI) override {
00092     Queue.push(LI);
00093   }
00094 
00095   LiveInterval *dequeue() override {
00096     if (Queue.empty())
00097       return nullptr;
00098     LiveInterval *LI = Queue.top();
00099     Queue.pop();
00100     return LI;
00101   }
00102 
00103   unsigned selectOrSplit(LiveInterval &VirtReg,
00104                          SmallVectorImpl<unsigned> &SplitVRegs) override;
00105 
00106   /// Perform register allocation.
00107   bool runOnMachineFunction(MachineFunction &mf) override;
00108 
00109   // Helper for spilling all live virtual registers currently unified under preg
00110   // that interfere with the most recently queried lvr.  Return true if spilling
00111   // was successful, and append any new spilled/split intervals to splitLVRs.
00112   bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
00113                           SmallVectorImpl<unsigned> &SplitVRegs);
00114 
00115   static char ID;
00116 };
00117 
00118 char RABasic::ID = 0;
00119 
00120 } // end anonymous namespace
00121 
00122 RABasic::RABasic(): MachineFunctionPass(ID) {
00123   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
00124   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
00125   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
00126   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
00127   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
00128   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
00129   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
00130   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
00131   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
00132   initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
00133 }
00134 
00135 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
00136   AU.setPreservesCFG();
00137   AU.addRequired<AliasAnalysis>();
00138   AU.addPreserved<AliasAnalysis>();
00139   AU.addRequired<LiveIntervals>();
00140   AU.addPreserved<LiveIntervals>();
00141   AU.addPreserved<SlotIndexes>();
00142   AU.addRequired<LiveDebugVariables>();
00143   AU.addPreserved<LiveDebugVariables>();
00144   AU.addRequired<LiveStacks>();
00145   AU.addPreserved<LiveStacks>();
00146   AU.addRequired<MachineBlockFrequencyInfo>();
00147   AU.addPreserved<MachineBlockFrequencyInfo>();
00148   AU.addRequiredID(MachineDominatorsID);
00149   AU.addPreservedID(MachineDominatorsID);
00150   AU.addRequired<MachineLoopInfo>();
00151   AU.addPreserved<MachineLoopInfo>();
00152   AU.addRequired<VirtRegMap>();
00153   AU.addPreserved<VirtRegMap>();
00154   AU.addRequired<LiveRegMatrix>();
00155   AU.addPreserved<LiveRegMatrix>();
00156   MachineFunctionPass::getAnalysisUsage(AU);
00157 }
00158 
00159 void RABasic::releaseMemory() {
00160   SpillerInstance.reset();
00161 }
00162 
00163 
00164 // Spill or split all live virtual registers currently unified under PhysReg
00165 // that interfere with VirtReg. The newly spilled or split live intervals are
00166 // returned by appending them to SplitVRegs.
00167 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
00168                                  SmallVectorImpl<unsigned> &SplitVRegs) {
00169   // Record each interference and determine if all are spillable before mutating
00170   // either the union or live intervals.
00171   SmallVector<LiveInterval*, 8> Intfs;
00172 
00173   // Collect interferences assigned to any alias of the physical register.
00174   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
00175     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
00176     Q.collectInterferingVRegs();
00177     if (Q.seenUnspillableVReg())
00178       return false;
00179     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
00180       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
00181       if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
00182         return false;
00183       Intfs.push_back(Intf);
00184     }
00185   }
00186   DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
00187         " interferences with " << VirtReg << "\n");
00188   assert(!Intfs.empty() && "expected interference");
00189 
00190   // Spill each interfering vreg allocated to PhysReg or an alias.
00191   for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
00192     LiveInterval &Spill = *Intfs[i];
00193 
00194     // Skip duplicates.
00195     if (!VRM->hasPhys(Spill.reg))
00196       continue;
00197 
00198     // Deallocate the interfering vreg by removing it from the union.
00199     // A LiveInterval instance may not be in a union during modification!
00200     Matrix->unassign(Spill);
00201 
00202     // Spill the extracted interval.
00203     LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
00204     spiller().spill(LRE);
00205   }
00206   return true;
00207 }
00208 
00209 // Driver for the register assignment and splitting heuristics.
00210 // Manages iteration over the LiveIntervalUnions.
00211 //
00212 // This is a minimal implementation of register assignment and splitting that
00213 // spills whenever we run out of registers.
00214 //
00215 // selectOrSplit can only be called once per live virtual register. We then do a
00216 // single interference test for each register the correct class until we find an
00217 // available register. So, the number of interference tests in the worst case is
00218 // |vregs| * |machineregs|. And since the number of interference tests is
00219 // minimal, there is no value in caching them outside the scope of
00220 // selectOrSplit().
00221 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
00222                                 SmallVectorImpl<unsigned> &SplitVRegs) {
00223   // Populate a list of physical register spill candidates.
00224   SmallVector<unsigned, 8> PhysRegSpillCands;
00225 
00226   // Check for an available register in this class.
00227   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
00228   while (unsigned PhysReg = Order.next()) {
00229     // Check for interference in PhysReg
00230     switch (Matrix->checkInterference(VirtReg, PhysReg)) {
00231     case LiveRegMatrix::IK_Free:
00232       // PhysReg is available, allocate it.
00233       return PhysReg;
00234 
00235     case LiveRegMatrix::IK_VirtReg:
00236       // Only virtual registers in the way, we may be able to spill them.
00237       PhysRegSpillCands.push_back(PhysReg);
00238       continue;
00239 
00240     default:
00241       // RegMask or RegUnit interference.
00242       continue;
00243     }
00244   }
00245 
00246   // Try to spill another interfering reg with less spill weight.
00247   for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
00248        PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
00249     if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
00250       continue;
00251 
00252     assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
00253            "Interference after spill.");
00254     // Tell the caller to allocate to this newly freed physical register.
00255     return *PhysRegI;
00256   }
00257 
00258   // No other spill candidates were found, so spill the current VirtReg.
00259   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
00260   if (!VirtReg.isSpillable())
00261     return ~0u;
00262   LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
00263   spiller().spill(LRE);
00264 
00265   // The live virtual register requesting allocation was spilled, so tell
00266   // the caller not to allocate anything during this round.
00267   return 0;
00268 }
00269 
00270 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
00271   DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
00272                << "********** Function: "
00273                << mf.getName() << '\n');
00274 
00275   MF = &mf;
00276   RegAllocBase::init(getAnalysis<VirtRegMap>(),
00277                      getAnalysis<LiveIntervals>(),
00278                      getAnalysis<LiveRegMatrix>());
00279 
00280   calculateSpillWeightsAndHints(*LIS, *MF,
00281                                 getAnalysis<MachineLoopInfo>(),
00282                                 getAnalysis<MachineBlockFrequencyInfo>());
00283 
00284   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
00285 
00286   allocatePhysRegs();
00287 
00288   // Diagnostic output before rewriting
00289   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
00290 
00291   releaseMemory();
00292   return true;
00293 }
00294 
00295 FunctionPass* llvm::createBasicRegisterAllocator()
00296 {
00297   return new RABasic();
00298 }