1234353Sdim//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim// This file defines the RABasic function pass, which provides a minimal
11218885Sdim// implementation of the basic register allocator.
12218885Sdim//
13218885Sdim//===----------------------------------------------------------------------===//
14218885Sdim
15218885Sdim#define DEBUG_TYPE "regalloc"
16249423Sdim#include "llvm/CodeGen/Passes.h"
17239462Sdim#include "AllocationOrder.h"
18249423Sdim#include "LiveDebugVariables.h"
19223017Sdim#include "RegAllocBase.h"
20218885Sdim#include "Spiller.h"
21218885Sdim#include "llvm/Analysis/AliasAnalysis.h"
22218885Sdim#include "llvm/CodeGen/CalcSpillWeights.h"
23218885Sdim#include "llvm/CodeGen/LiveIntervalAnalysis.h"
24234353Sdim#include "llvm/CodeGen/LiveRangeEdit.h"
25249423Sdim#include "llvm/CodeGen/LiveRegMatrix.h"
26218885Sdim#include "llvm/CodeGen/LiveStackAnalysis.h"
27263508Sdim#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
28218885Sdim#include "llvm/CodeGen/MachineFunctionPass.h"
29218885Sdim#include "llvm/CodeGen/MachineInstr.h"
30218885Sdim#include "llvm/CodeGen/MachineLoopInfo.h"
31218885Sdim#include "llvm/CodeGen/MachineRegisterInfo.h"
32218885Sdim#include "llvm/CodeGen/RegAllocRegistry.h"
33249423Sdim#include "llvm/CodeGen/VirtRegMap.h"
34249423Sdim#include "llvm/PassAnalysisSupport.h"
35249423Sdim#include "llvm/Support/Debug.h"
36249423Sdim#include "llvm/Support/raw_ostream.h"
37218885Sdim#include "llvm/Target/TargetMachine.h"
38218885Sdim#include "llvm/Target/TargetRegisterInfo.h"
39218885Sdim#include <cstdlib>
40219077Sdim#include <queue>
41218885Sdim
42218885Sdimusing namespace llvm;
43218885Sdim
44218885Sdimstatic RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
45218885Sdim                                      createBasicRegisterAllocator);
46218885Sdim
47218885Sdimnamespace {
48219077Sdim  struct CompSpillWeight {
49219077Sdim    bool operator()(LiveInterval *A, LiveInterval *B) const {
50219077Sdim      return A->weight < B->weight;
51219077Sdim    }
52219077Sdim  };
53219077Sdim}
54219077Sdim
55219077Sdimnamespace {
56218885Sdim/// RABasic provides a minimal implementation of the basic register allocation
57218885Sdim/// algorithm. It prioritizes live virtual registers by spill weight and spills
58218885Sdim/// whenever a register is unavailable. This is not practical in production but
59218885Sdim/// provides a useful baseline both for measuring other allocators and comparing
60218885Sdim/// the speed of the basic algorithm against other styles of allocators.
61218885Sdimclass RABasic : public MachineFunctionPass, public RegAllocBase
62218885Sdim{
63218885Sdim  // context
64218885Sdim  MachineFunction *MF;
65218885Sdim
66218885Sdim  // state
67251662Sdim  OwningPtr<Spiller> SpillerInstance;
68219077Sdim  std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
69219077Sdim                      CompSpillWeight> Queue;
70234353Sdim
71234353Sdim  // Scratch space.  Allocated here to avoid repeated malloc calls in
72234353Sdim  // selectOrSplit().
73234353Sdim  BitVector UsableRegs;
74234353Sdim
75218885Sdimpublic:
76218885Sdim  RABasic();
77218885Sdim
78218885Sdim  /// Return the pass name.
79218885Sdim  virtual const char* getPassName() const {
80218885Sdim    return "Basic Register Allocator";
81218885Sdim  }
82218885Sdim
83218885Sdim  /// RABasic analysis usage.
84218885Sdim  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
85218885Sdim
86218885Sdim  virtual void releaseMemory();
87218885Sdim
88218885Sdim  virtual Spiller &spiller() { return *SpillerInstance; }
89218885Sdim
90218885Sdim  virtual float getPriority(LiveInterval *LI) { return LI->weight; }
91218885Sdim
92219077Sdim  virtual void enqueue(LiveInterval *LI) {
93219077Sdim    Queue.push(LI);
94219077Sdim  }
95219077Sdim
96219077Sdim  virtual LiveInterval *dequeue() {
97219077Sdim    if (Queue.empty())
98219077Sdim      return 0;
99219077Sdim    LiveInterval *LI = Queue.top();
100219077Sdim    Queue.pop();
101219077Sdim    return LI;
102219077Sdim  }
103219077Sdim
104218885Sdim  virtual unsigned selectOrSplit(LiveInterval &VirtReg,
105263508Sdim                                 SmallVectorImpl<unsigned> &SplitVRegs);
106218885Sdim
107218885Sdim  /// Perform register allocation.
108218885Sdim  virtual bool runOnMachineFunction(MachineFunction &mf);
109218885Sdim
110234353Sdim  // Helper for spilling all live virtual registers currently unified under preg
111234353Sdim  // that interfere with the most recently queried lvr.  Return true if spilling
112234353Sdim  // was successful, and append any new spilled/split intervals to splitLVRs.
113234353Sdim  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
114263508Sdim                          SmallVectorImpl<unsigned> &SplitVRegs);
115234353Sdim
116218885Sdim  static char ID;
117218885Sdim};
118218885Sdim
119218885Sdimchar RABasic::ID = 0;
120218885Sdim
121218885Sdim} // end anonymous namespace
122218885Sdim
123218885SdimRABasic::RABasic(): MachineFunctionPass(ID) {
124221345Sdim  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
125218885Sdim  initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
126218885Sdim  initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
127224145Sdim  initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
128234353Sdim  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
129218885Sdim  initializeLiveStacksPass(*PassRegistry::getPassRegistry());
130218885Sdim  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
131218885Sdim  initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
132218885Sdim  initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
133239462Sdim  initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
134218885Sdim}
135218885Sdim
136218885Sdimvoid RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
137218885Sdim  AU.setPreservesCFG();
138218885Sdim  AU.addRequired<AliasAnalysis>();
139218885Sdim  AU.addPreserved<AliasAnalysis>();
140218885Sdim  AU.addRequired<LiveIntervals>();
141239462Sdim  AU.addPreserved<LiveIntervals>();
142218885Sdim  AU.addPreserved<SlotIndexes>();
143221345Sdim  AU.addRequired<LiveDebugVariables>();
144221345Sdim  AU.addPreserved<LiveDebugVariables>();
145218885Sdim  AU.addRequired<LiveStacks>();
146218885Sdim  AU.addPreserved<LiveStacks>();
147263508Sdim  AU.addRequired<MachineBlockFrequencyInfo>();
148263508Sdim  AU.addPreserved<MachineBlockFrequencyInfo>();
149218885Sdim  AU.addRequiredID(MachineDominatorsID);
150218885Sdim  AU.addPreservedID(MachineDominatorsID);
151218885Sdim  AU.addRequired<MachineLoopInfo>();
152218885Sdim  AU.addPreserved<MachineLoopInfo>();
153218885Sdim  AU.addRequired<VirtRegMap>();
154218885Sdim  AU.addPreserved<VirtRegMap>();
155239462Sdim  AU.addRequired<LiveRegMatrix>();
156239462Sdim  AU.addPreserved<LiveRegMatrix>();
157218885Sdim  MachineFunctionPass::getAnalysisUsage(AU);
158218885Sdim}
159218885Sdim
160218885Sdimvoid RABasic::releaseMemory() {
161218885Sdim  SpillerInstance.reset(0);
162218885Sdim}
163218885Sdim
164218885Sdim
165218885Sdim// Spill or split all live virtual registers currently unified under PhysReg
166218885Sdim// that interfere with VirtReg. The newly spilled or split live intervals are
167218885Sdim// returned by appending them to SplitVRegs.
168234353Sdimbool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
169263508Sdim                                 SmallVectorImpl<unsigned> &SplitVRegs) {
170218885Sdim  // Record each interference and determine if all are spillable before mutating
171218885Sdim  // either the union or live intervals.
172239462Sdim  SmallVector<LiveInterval*, 8> Intfs;
173239462Sdim
174218885Sdim  // Collect interferences assigned to any alias of the physical register.
175239462Sdim  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
176239462Sdim    LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
177239462Sdim    Q.collectInterferingVRegs();
178239462Sdim    if (Q.seenUnspillableVReg())
179218885Sdim      return false;
180239462Sdim    for (unsigned i = Q.interferingVRegs().size(); i; --i) {
181239462Sdim      LiveInterval *Intf = Q.interferingVRegs()[i - 1];
182239462Sdim      if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
183239462Sdim        return false;
184239462Sdim      Intfs.push_back(Intf);
185218885Sdim    }
186218885Sdim  }
187218885Sdim  DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
188218885Sdim        " interferences with " << VirtReg << "\n");
189239462Sdim  assert(!Intfs.empty() && "expected interference");
190218885Sdim
191218885Sdim  // Spill each interfering vreg allocated to PhysReg or an alias.
192239462Sdim  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
193239462Sdim    LiveInterval &Spill = *Intfs[i];
194239462Sdim
195239462Sdim    // Skip duplicates.
196239462Sdim    if (!VRM->hasPhys(Spill.reg))
197239462Sdim      continue;
198239462Sdim
199239462Sdim    // Deallocate the interfering vreg by removing it from the union.
200239462Sdim    // A LiveInterval instance may not be in a union during modification!
201239462Sdim    Matrix->unassign(Spill);
202239462Sdim
203239462Sdim    // Spill the extracted interval.
204239462Sdim    LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
205239462Sdim    spiller().spill(LRE);
206239462Sdim  }
207218885Sdim  return true;
208218885Sdim}
209218885Sdim
210218885Sdim// Driver for the register assignment and splitting heuristics.
211218885Sdim// Manages iteration over the LiveIntervalUnions.
212218885Sdim//
213218885Sdim// This is a minimal implementation of register assignment and splitting that
214218885Sdim// spills whenever we run out of registers.
215218885Sdim//
216218885Sdim// selectOrSplit can only be called once per live virtual register. We then do a
217218885Sdim// single interference test for each register the correct class until we find an
218218885Sdim// available register. So, the number of interference tests in the worst case is
219218885Sdim// |vregs| * |machineregs|. And since the number of interference tests is
220218885Sdim// minimal, there is no value in caching them outside the scope of
221218885Sdim// selectOrSplit().
222218885Sdimunsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
223263508Sdim                                SmallVectorImpl<unsigned> &SplitVRegs) {
224218885Sdim  // Populate a list of physical register spill candidates.
225218885Sdim  SmallVector<unsigned, 8> PhysRegSpillCands;
226218885Sdim
227218885Sdim  // Check for an available register in this class.
228239462Sdim  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
229239462Sdim  while (unsigned PhysReg = Order.next()) {
230239462Sdim    // Check for interference in PhysReg
231239462Sdim    switch (Matrix->checkInterference(VirtReg, PhysReg)) {
232239462Sdim    case LiveRegMatrix::IK_Free:
233239462Sdim      // PhysReg is available, allocate it.
234239462Sdim      return PhysReg;
235218885Sdim
236239462Sdim    case LiveRegMatrix::IK_VirtReg:
237239462Sdim      // Only virtual registers in the way, we may be able to spill them.
238239462Sdim      PhysRegSpillCands.push_back(PhysReg);
239234353Sdim      continue;
240234353Sdim
241239462Sdim    default:
242239462Sdim      // RegMask or RegUnit interference.
243239462Sdim      continue;
244218885Sdim    }
245239462Sdim  }
246218885Sdim
247218885Sdim  // Try to spill another interfering reg with less spill weight.
248218885Sdim  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
249239462Sdim       PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
250239462Sdim    if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
251239462Sdim      continue;
252218885Sdim
253239462Sdim    assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
254218885Sdim           "Interference after spill.");
255218885Sdim    // Tell the caller to allocate to this newly freed physical register.
256218885Sdim    return *PhysRegI;
257218885Sdim  }
258223017Sdim
259218885Sdim  // No other spill candidates were found, so spill the current VirtReg.
260218885Sdim  DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
261223017Sdim  if (!VirtReg.isSpillable())
262223017Sdim    return ~0u;
263239462Sdim  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
264221345Sdim  spiller().spill(LRE);
265218885Sdim
266218885Sdim  // The live virtual register requesting allocation was spilled, so tell
267218885Sdim  // the caller not to allocate anything during this round.
268218885Sdim  return 0;
269218885Sdim}
270218885Sdim
271218885Sdimbool RABasic::runOnMachineFunction(MachineFunction &mf) {
272218885Sdim  DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
273218885Sdim               << "********** Function: "
274243830Sdim               << mf.getName() << '\n');
275218885Sdim
276218885Sdim  MF = &mf;
277239462Sdim  RegAllocBase::init(getAnalysis<VirtRegMap>(),
278239462Sdim                     getAnalysis<LiveIntervals>(),
279239462Sdim                     getAnalysis<LiveRegMatrix>());
280263508Sdim
281263508Sdim  calculateSpillWeightsAndHints(*LIS, *MF,
282263508Sdim                                getAnalysis<MachineLoopInfo>(),
283263508Sdim                                getAnalysis<MachineBlockFrequencyInfo>());
284263508Sdim
285221345Sdim  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
286218885Sdim
287218885Sdim  allocatePhysRegs();
288218885Sdim
289218885Sdim  // Diagnostic output before rewriting
290218885Sdim  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
291218885Sdim
292218885Sdim  releaseMemory();
293218885Sdim  return true;
294218885Sdim}
295218885Sdim
296218885SdimFunctionPass* llvm::createBasicRegisterAllocator()
297218885Sdim{
298218885Sdim  return new RABasic();
299218885Sdim}
300