1 //===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RABasic function pass, which provides a minimal
11 // implementation of the basic register allocator.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "LiveIntervalUnion.h"
17 #include "RegAllocBase.h"
18 #include "RenderMachineFunction.h"
20 #include "VirtRegMap.h"
21 #include "VirtRegRewriter.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Function.h"
25 #include "llvm/PassAnalysisSupport.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveStackAnalysis.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/RegAllocRegistry.h"
35 #include "llvm/CodeGen/RegisterCoalescer.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/ADT/SparseBitVector.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
52 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
53 createBasicRegisterAllocator);
55 // Temporary verification option until we can put verification inside
58 VerifyRegAlloc("verify-regalloc",
59 cl::desc("Verify live intervals before renaming"));
63 class PhysicalRegisterDescription : public AbstractRegisterDescription {
64 const TargetRegisterInfo *TRI;
66 PhysicalRegisterDescription(const TargetRegisterInfo *T): TRI(T) {}
67 virtual const char *getName(unsigned Reg) const { return TRI->getName(Reg); }
70 /// RABasic provides a minimal implementation of the basic register allocation
71 /// algorithm. It prioritizes live virtual registers by spill weight and spills
72 /// whenever a register is unavailable. This is not practical in production but
73 /// provides a useful baseline both for measuring other allocators and comparing
74 /// the speed of the basic algorithm against other styles of allocators.
75 class RABasic : public MachineFunctionPass, public RegAllocBase
79 const TargetMachine *TM;
80 MachineRegisterInfo *MRI;
82 BitVector ReservedRegs;
86 RenderMachineFunction *RMF;
89 std::auto_ptr<Spiller> SpillerInstance;
94 /// Return the pass name.
95 virtual const char* getPassName() const {
96 return "Basic Register Allocator";
99 /// RABasic analysis usage.
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
102 virtual void releaseMemory();
104 virtual Spiller &spiller() { return *SpillerInstance; }
106 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
107 SmallVectorImpl<LiveInterval*> &SplitVRegs);
109 /// Perform register allocation.
110 virtual bool runOnMachineFunction(MachineFunction &mf);
115 void addMBBLiveIns();
118 char RABasic::ID = 0;
120 } // end anonymous namespace
122 RABasic::RABasic(): MachineFunctionPass(ID) {
123 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
124 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
125 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
126 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
127 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
128 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
129 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
130 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
131 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
132 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
135 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.setPreservesCFG();
137 AU.addRequired<AliasAnalysis>();
138 AU.addPreserved<AliasAnalysis>();
139 AU.addRequired<LiveIntervals>();
140 AU.addPreserved<SlotIndexes>();
142 AU.addRequiredID(StrongPHIEliminationID);
143 AU.addRequiredTransitive<RegisterCoalescer>();
144 AU.addRequired<CalculateSpillWeights>();
145 AU.addRequired<LiveStacks>();
146 AU.addPreserved<LiveStacks>();
147 AU.addRequiredID(MachineDominatorsID);
148 AU.addPreservedID(MachineDominatorsID);
149 AU.addRequired<MachineLoopInfo>();
150 AU.addPreserved<MachineLoopInfo>();
151 AU.addRequired<VirtRegMap>();
152 AU.addPreserved<VirtRegMap>();
153 DEBUG(AU.addRequired<RenderMachineFunction>());
154 MachineFunctionPass::getAnalysisUsage(AU);
157 void RABasic::releaseMemory() {
158 SpillerInstance.reset(0);
159 RegAllocBase::releaseMemory();
163 // Verify each LiveIntervalUnion.
164 void RegAllocBase::verify() {
165 LiveVirtRegBitSet VisitedVRegs;
166 OwningArrayPtr<LiveVirtRegBitSet>
167 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
169 // Verify disjoint unions.
170 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
171 DEBUG(PhysicalRegisterDescription PRD(TRI);
172 PhysReg2LiveUnion[PhysReg].dump(&PRD));
173 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
174 PhysReg2LiveUnion[PhysReg].verify(VRegs);
175 // Union + intersection test could be done efficiently in one pass, but
176 // don't add a method to SparseBitVector unless we really need it.
177 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
178 VisitedVRegs |= VRegs;
181 // Verify vreg coverage.
182 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
183 liItr != liEnd; ++liItr) {
184 unsigned reg = liItr->first;
185 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
186 if (!VRM->hasPhys(reg)) continue; // spilled?
187 unsigned PhysReg = VRM->getPhys(reg);
188 if (!unionVRegs[PhysReg].test(reg)) {
189 dbgs() << "LiveVirtReg " << reg << " not in union " <<
190 TRI->getName(PhysReg) << "\n";
191 llvm_unreachable("unallocated live vreg");
194 // FIXME: I'm not sure how to verify spilled intervals.
198 //===----------------------------------------------------------------------===//
199 // RegAllocBase Implementation
200 //===----------------------------------------------------------------------===//
202 // Instantiate a LiveIntervalUnion for each physical register.
203 void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
207 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
208 for (unsigned r = 0; r != NRegs; ++r)
209 new(Array + r) LiveIntervalUnion(r, allocator);
212 void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
213 LiveIntervals &lis) {
217 PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
218 // Cache an interferece query for each physical reg
219 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
222 void RegAllocBase::LiveUnionArray::clear() {
225 for (unsigned r = 0; r != NumRegs; ++r)
226 Array[r].~LiveIntervalUnion();
232 void RegAllocBase::releaseMemory() {
233 PhysReg2LiveUnion.clear();
237 /// This class defines a queue of live virtual registers prioritized by spill
238 /// weight. The heaviest vreg is popped first.
240 /// Currently, this is trivial wrapper that gives us an opaque type in the
241 /// header, but we may later give it a virtual interface for register allocators
242 /// to override the priority queue comparator.
243 class LiveVirtRegQueue {
244 typedef std::priority_queue
245 <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority>
250 // Is the queue empty?
251 bool empty() { return PQ.empty(); }
253 // Get the highest priority lvr (top + pop)
254 LiveInterval *get() {
255 LiveInterval *VirtReg = PQ.top();
259 // Add this lvr to the queue
260 void push(LiveInterval *VirtReg) {
264 } // end namespace llvm
266 // Visit all the live virtual registers. If they are already assigned to a
267 // physical register, unify them with the corresponding LiveIntervalUnion,
268 // otherwise push them on the priority queue for later assignment.
269 void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &VirtRegQ) {
270 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
271 unsigned RegNum = I->first;
272 LiveInterval &VirtReg = *I->second;
273 if (TargetRegisterInfo::isPhysicalRegister(RegNum)) {
274 PhysReg2LiveUnion[RegNum].unify(VirtReg);
277 VirtRegQ.push(&VirtReg);
282 // Top-level driver to manage the queue of unassigned VirtRegs and call the
283 // selectOrSplit implementation.
284 void RegAllocBase::allocatePhysRegs() {
286 // Push each vreg onto a queue or "precolor" by adding it to a physreg union.
287 LiveVirtRegQueue VirtRegQ;
288 seedLiveVirtRegs(VirtRegQ);
290 // Continue assigning vregs one at a time to available physical registers.
291 while (!VirtRegQ.empty()) {
292 // Pop the highest priority vreg.
293 LiveInterval *VirtReg = VirtRegQ.get();
295 // selectOrSplit requests the allocator to return an available physical
296 // register if possible and populate a list of new live intervals that
297 // result from splitting.
298 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
299 VirtRegVec SplitVRegs;
300 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
302 if (AvailablePhysReg) {
303 DEBUG(dbgs() << "allocating: " << TRI->getName(AvailablePhysReg) <<
304 " " << *VirtReg << '\n');
305 assert(!VRM->hasPhys(VirtReg->reg) && "duplicate vreg in union");
306 VRM->assignVirt2Phys(VirtReg->reg, AvailablePhysReg);
307 PhysReg2LiveUnion[AvailablePhysReg].unify(*VirtReg);
309 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
311 LiveInterval* SplitVirtReg = *I;
312 if (SplitVirtReg->empty()) continue;
313 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
314 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
315 "expect split value in virtual register");
316 VirtRegQ.push(SplitVirtReg);
321 // Check if this live virtual register interferes with a physical register. If
322 // not, then check for interference on each register that aliases with the
323 // physical register. Return the interfering register.
324 unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
326 if (query(VirtReg, PhysReg).checkInterference())
328 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
329 if (query(VirtReg, *AliasI).checkInterference())
335 // Helper for spillInteferences() that spills all interfering vregs currently
336 // assigned to this physical register.
337 void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
338 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
339 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
340 assert(Q.seenAllInterferences() && "need collectInterferences()");
341 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
343 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
344 E = PendingSpills.end(); I != E; ++I) {
345 LiveInterval &SpilledVReg = **I;
346 DEBUG(dbgs() << "extracting from " <<
347 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
349 // Deallocate the interfering vreg by removing it from the union.
350 // A LiveInterval instance may not be in a union during modification!
351 PhysReg2LiveUnion[PhysReg].extract(SpilledVReg);
353 // Clear the vreg assignment.
354 VRM->clearVirt(SpilledVReg.reg);
356 // Spill the extracted interval.
357 spiller().spill(&SpilledVReg, SplitVRegs, PendingSpills);
359 // After extracting segments, the query's results are invalid. But keep the
360 // contents valid until we're done accessing pendingSpills.
364 // Spill or split all live virtual registers currently unified under PhysReg
365 // that interfere with VirtReg. The newly spilled or split live intervals are
366 // returned by appending them to SplitVRegs.
368 RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
369 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
370 // Record each interference and determine if all are spillable before mutating
371 // either the union or live intervals.
373 // Collect interferences assigned to the requested physical register.
374 LiveIntervalUnion::Query &QPreg = query(VirtReg, PhysReg);
375 unsigned NumInterferences = QPreg.collectInterferingVRegs();
376 if (QPreg.seenUnspillableVReg()) {
379 // Collect interferences assigned to any alias of the physical register.
380 for (const unsigned *asI = TRI->getAliasSet(PhysReg); *asI; ++asI) {
381 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
382 NumInterferences += QAlias.collectInterferingVRegs();
383 if (QAlias.seenUnspillableVReg()) {
387 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
388 " interferences with " << VirtReg << "\n");
389 assert(NumInterferences > 0 && "expect interference");
391 // Spill each interfering vreg allocated to PhysReg or an alias.
392 spillReg(VirtReg, PhysReg, SplitVRegs);
393 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI)
394 spillReg(VirtReg, *AliasI, SplitVRegs);
398 //===----------------------------------------------------------------------===//
399 // RABasic Implementation
400 //===----------------------------------------------------------------------===//
402 // Driver for the register assignment and splitting heuristics.
403 // Manages iteration over the LiveIntervalUnions.
405 // This is a minimal implementation of register assignment and splitting that
406 // spills whenever we run out of registers.
408 // selectOrSplit can only be called once per live virtual register. We then do a
409 // single interference test for each register the correct class until we find an
410 // available register. So, the number of interference tests in the worst case is
411 // |vregs| * |machineregs|. And since the number of interference tests is
412 // minimal, there is no value in caching them outside the scope of
414 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
415 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
416 // Populate a list of physical register spill candidates.
417 SmallVector<unsigned, 8> PhysRegSpillCands;
419 // Check for an available register in this class.
420 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
421 DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
423 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
424 E = TRC->allocation_order_end(*MF);
427 unsigned PhysReg = *I;
428 if (ReservedRegs.test(PhysReg)) continue;
430 // Check interference and as a side effect, intialize queries for this
431 // VirtReg and its aliases.
432 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
433 if (interfReg == 0) {
434 // Found an available register.
437 LiveInterval *interferingVirtReg =
438 Queries[interfReg].firstInterference().liveUnionPos().value();
440 // The current VirtReg must either spillable, or one of its interferences
441 // must have less spill weight.
442 if (interferingVirtReg->weight < VirtReg.weight ) {
443 PhysRegSpillCands.push_back(PhysReg);
446 // Try to spill another interfering reg with less spill weight.
448 // FIXME: RAGreedy will sort this list by spill weight.
449 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
450 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
452 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
454 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
455 "Interference after spill.");
456 // Tell the caller to allocate to this newly freed physical register.
459 // No other spill candidates were found, so spill the current VirtReg.
460 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
461 SmallVector<LiveInterval*, 1> pendingSpills;
463 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
465 // The live virtual register requesting allocation was spilled, so tell
466 // the caller not to allocate anything during this round.
470 // Add newly allocated physical registers to the MBB live in sets.
471 void RABasic::addMBBLiveIns() {
472 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
474 MachineBasicBlock &entryMBB = *MF->begin();
476 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
477 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
479 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(),
480 SegEnd = LiveUnion.end();
481 SI != SegEnd; ++SI) {
483 // Find the set of basic blocks which this range is live into...
485 if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
487 // And add the physreg for this interval to their live-in sets.
488 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
490 MachineBasicBlock *MBB = *I;
491 if (MBB == &entryMBB) continue;
492 if (MBB->isLiveIn(PhysReg)) continue;
493 MBB->addLiveIn(PhysReg);
499 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
500 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
501 << "********** Function: "
502 << ((Value*)mf.getFunction())->getName() << '\n');
505 TM = &mf.getTarget();
506 MRI = &mf.getRegInfo();
508 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
510 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
511 RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
512 getAnalysis<LiveIntervals>());
514 ReservedRegs = TRI->getReservedRegs(*MF);
516 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
522 // Diagnostic output before rewriting
523 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
525 // optional HTML output
526 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
528 // FIXME: Verification currently must run before VirtRegRewriter. We should
529 // make the rewriter a separate pass and override verifyAnalysis instead. When
530 // that happens, verification naturally falls under VerifyMachineCode.
532 if (VerifyRegAlloc) {
533 // Verify accuracy of LiveIntervals. The standard machine code verifier
534 // ensures that each LiveIntervals covers all uses of the virtual reg.
536 // FIXME: MachineVerifier is badly broken when using the standard
537 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
538 // inline spiller, some tests fail to verify because the coalescer does not
539 // always generate verifiable code.
542 // Verify that LiveIntervals are partitioned into unions and disjoint within
549 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
550 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
552 // The pass output is in VirtRegMap. Release all the transient data.
558 FunctionPass* llvm::createBasicRegisterAllocator()
560 return new RABasic();