1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the RABasic function pass, which provides a minimal 11 // implementation of the basic register allocator. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/Passes.h" 16 #include "AllocationOrder.h" 17 #include "LiveDebugVariables.h" 18 #include "RegAllocBase.h" 19 #include "Spiller.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/CodeGen/CalcSpillWeights.h" 22 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 23 #include "llvm/CodeGen/LiveRangeEdit.h" 24 #include "llvm/CodeGen/LiveRegMatrix.h" 25 #include "llvm/CodeGen/LiveStackAnalysis.h" 26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 27 #include "llvm/CodeGen/MachineFunctionPass.h" 28 #include "llvm/CodeGen/MachineInstr.h" 29 #include "llvm/CodeGen/MachineLoopInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/RegAllocRegistry.h" 32 #include "llvm/CodeGen/VirtRegMap.h" 33 #include "llvm/PassAnalysisSupport.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetRegisterInfo.h" 37 #include <cstdlib> 38 #include <queue> 39 40 using namespace llvm; 41 42 #define DEBUG_TYPE "regalloc" 43 44 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", 45 createBasicRegisterAllocator); 46 47 namespace { 48 struct CompSpillWeight { 49 bool operator()(LiveInterval *A, LiveInterval *B) const { 50 return A->weight < B->weight; 51 } 52 }; 53 } 54 55 namespace { 56 /// RABasic provides a minimal implementation of the basic register allocation 57 /// algorithm. It prioritizes live virtual registers by spill weight and spills 58 /// whenever a register is unavailable. This is not practical in production but 59 /// provides a useful baseline both for measuring other allocators and comparing 60 /// the speed of the basic algorithm against other styles of allocators. 61 class RABasic : public MachineFunctionPass, public RegAllocBase 62 { 63 // context 64 MachineFunction *MF; 65 66 // state 67 std::unique_ptr<Spiller> SpillerInstance; 68 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>, 69 CompSpillWeight> Queue; 70 71 // Scratch space. Allocated here to avoid repeated malloc calls in 72 // selectOrSplit(). 73 BitVector UsableRegs; 74 75 public: 76 RABasic(); 77 78 /// Return the pass name. 79 const char* getPassName() const override { 80 return "Basic Register Allocator"; 81 } 82 83 /// RABasic analysis usage. 84 void getAnalysisUsage(AnalysisUsage &AU) const override; 85 86 void releaseMemory() override; 87 88 Spiller &spiller() override { return *SpillerInstance; } 89 90 void enqueue(LiveInterval *LI) override { 91 Queue.push(LI); 92 } 93 94 LiveInterval *dequeue() override { 95 if (Queue.empty()) 96 return nullptr; 97 LiveInterval *LI = Queue.top(); 98 Queue.pop(); 99 return LI; 100 } 101 102 unsigned selectOrSplit(LiveInterval &VirtReg, 103 SmallVectorImpl<unsigned> &SplitVRegs) override; 104 105 /// Perform register allocation. 106 bool runOnMachineFunction(MachineFunction &mf) override; 107 108 MachineFunctionProperties getRequiredProperties() const override { 109 return MachineFunctionProperties().set( 110 MachineFunctionProperties::Property::NoPHIs); 111 } 112 113 // Helper for spilling all live virtual registers currently unified under preg 114 // that interfere with the most recently queried lvr. Return true if spilling 115 // was successful, and append any new spilled/split intervals to splitLVRs. 116 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, 117 SmallVectorImpl<unsigned> &SplitVRegs); 118 119 static char ID; 120 }; 121 122 char RABasic::ID = 0; 123 124 } // end anonymous namespace 125 126 RABasic::RABasic(): MachineFunctionPass(ID) { 127 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 128 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); 129 initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); 130 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 131 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); 132 initializeLiveStacksPass(*PassRegistry::getPassRegistry()); 133 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry()); 134 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry()); 135 initializeVirtRegMapPass(*PassRegistry::getPassRegistry()); 136 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry()); 137 } 138 139 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const { 140 AU.setPreservesCFG(); 141 AU.addRequired<AAResultsWrapperPass>(); 142 AU.addPreserved<AAResultsWrapperPass>(); 143 AU.addRequired<LiveIntervals>(); 144 AU.addPreserved<LiveIntervals>(); 145 AU.addPreserved<SlotIndexes>(); 146 AU.addRequired<LiveDebugVariables>(); 147 AU.addPreserved<LiveDebugVariables>(); 148 AU.addRequired<LiveStacks>(); 149 AU.addPreserved<LiveStacks>(); 150 AU.addRequired<MachineBlockFrequencyInfo>(); 151 AU.addPreserved<MachineBlockFrequencyInfo>(); 152 AU.addRequiredID(MachineDominatorsID); 153 AU.addPreservedID(MachineDominatorsID); 154 AU.addRequired<MachineLoopInfo>(); 155 AU.addPreserved<MachineLoopInfo>(); 156 AU.addRequired<VirtRegMap>(); 157 AU.addPreserved<VirtRegMap>(); 158 AU.addRequired<LiveRegMatrix>(); 159 AU.addPreserved<LiveRegMatrix>(); 160 MachineFunctionPass::getAnalysisUsage(AU); 161 } 162 163 void RABasic::releaseMemory() { 164 SpillerInstance.reset(); 165 } 166 167 168 // Spill or split all live virtual registers currently unified under PhysReg 169 // that interfere with VirtReg. The newly spilled or split live intervals are 170 // returned by appending them to SplitVRegs. 171 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, 172 SmallVectorImpl<unsigned> &SplitVRegs) { 173 // Record each interference and determine if all are spillable before mutating 174 // either the union or live intervals. 175 SmallVector<LiveInterval*, 8> Intfs; 176 177 // Collect interferences assigned to any alias of the physical register. 178 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 179 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 180 Q.collectInterferingVRegs(); 181 if (Q.seenUnspillableVReg()) 182 return false; 183 for (unsigned i = Q.interferingVRegs().size(); i; --i) { 184 LiveInterval *Intf = Q.interferingVRegs()[i - 1]; 185 if (!Intf->isSpillable() || Intf->weight > VirtReg.weight) 186 return false; 187 Intfs.push_back(Intf); 188 } 189 } 190 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) << 191 " interferences with " << VirtReg << "\n"); 192 assert(!Intfs.empty() && "expected interference"); 193 194 // Spill each interfering vreg allocated to PhysReg or an alias. 195 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) { 196 LiveInterval &Spill = *Intfs[i]; 197 198 // Skip duplicates. 199 if (!VRM->hasPhys(Spill.reg)) 200 continue; 201 202 // Deallocate the interfering vreg by removing it from the union. 203 // A LiveInterval instance may not be in a union during modification! 204 Matrix->unassign(Spill); 205 206 // Spill the extracted interval. 207 LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, nullptr, &DeadRemats); 208 spiller().spill(LRE); 209 } 210 return true; 211 } 212 213 // Driver for the register assignment and splitting heuristics. 214 // Manages iteration over the LiveIntervalUnions. 215 // 216 // This is a minimal implementation of register assignment and splitting that 217 // spills whenever we run out of registers. 218 // 219 // selectOrSplit can only be called once per live virtual register. We then do a 220 // single interference test for each register the correct class until we find an 221 // available register. So, the number of interference tests in the worst case is 222 // |vregs| * |machineregs|. And since the number of interference tests is 223 // minimal, there is no value in caching them outside the scope of 224 // selectOrSplit(). 225 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg, 226 SmallVectorImpl<unsigned> &SplitVRegs) { 227 // Populate a list of physical register spill candidates. 228 SmallVector<unsigned, 8> PhysRegSpillCands; 229 230 // Check for an available register in this class. 231 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix); 232 while (unsigned PhysReg = Order.next()) { 233 // Check for interference in PhysReg 234 switch (Matrix->checkInterference(VirtReg, PhysReg)) { 235 case LiveRegMatrix::IK_Free: 236 // PhysReg is available, allocate it. 237 return PhysReg; 238 239 case LiveRegMatrix::IK_VirtReg: 240 // Only virtual registers in the way, we may be able to spill them. 241 PhysRegSpillCands.push_back(PhysReg); 242 continue; 243 244 default: 245 // RegMask or RegUnit interference. 246 continue; 247 } 248 } 249 250 // Try to spill another interfering reg with less spill weight. 251 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(), 252 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) { 253 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) 254 continue; 255 256 assert(!Matrix->checkInterference(VirtReg, *PhysRegI) && 257 "Interference after spill."); 258 // Tell the caller to allocate to this newly freed physical register. 259 return *PhysRegI; 260 } 261 262 // No other spill candidates were found, so spill the current VirtReg. 263 DEBUG(dbgs() << "spilling: " << VirtReg << '\n'); 264 if (!VirtReg.isSpillable()) 265 return ~0u; 266 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, nullptr, &DeadRemats); 267 spiller().spill(LRE); 268 269 // The live virtual register requesting allocation was spilled, so tell 270 // the caller not to allocate anything during this round. 271 return 0; 272 } 273 274 bool RABasic::runOnMachineFunction(MachineFunction &mf) { 275 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n" 276 << "********** Function: " 277 << mf.getName() << '\n'); 278 279 MF = &mf; 280 RegAllocBase::init(getAnalysis<VirtRegMap>(), 281 getAnalysis<LiveIntervals>(), 282 getAnalysis<LiveRegMatrix>()); 283 284 calculateSpillWeightsAndHints(*LIS, *MF, VRM, 285 getAnalysis<MachineLoopInfo>(), 286 getAnalysis<MachineBlockFrequencyInfo>()); 287 288 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM)); 289 290 allocatePhysRegs(); 291 postOptimization(); 292 293 // Diagnostic output before rewriting 294 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n"); 295 296 releaseMemory(); 297 return true; 298 } 299 300 FunctionPass* llvm::createBasicRegisterAllocator() 301 { 302 return new RABasic(); 303 } 304