LLVM  3.7.0
RegAllocBasic.cpp
Go to the documentation of this file.
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"
34 #include "llvm/Support/Debug.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",
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  // Helper for spilling all live virtual registers currently unified under preg
109  // that interfere with the most recently queried lvr. Return true if spilling
110  // was successful, and append any new spilled/split intervals to splitLVRs.
111  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
112  SmallVectorImpl<unsigned> &SplitVRegs);
113 
114  static char ID;
115 };
116 
117 char RABasic::ID = 0;
118 
119 } // end anonymous namespace
120 
121 RABasic::RABasic(): MachineFunctionPass(ID) {
122  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
123  initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
124  initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
125  initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
126  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
127  initializeLiveStacksPass(*PassRegistry::getPassRegistry());
128  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
129  initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
130  initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
131  initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
132 }
133 
134 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
135  AU.setPreservesCFG();
143  AU.addRequired<LiveStacks>();
144  AU.addPreserved<LiveStacks>();
151  AU.addRequired<VirtRegMap>();
152  AU.addPreserved<VirtRegMap>();
155  MachineFunctionPass::getAnalysisUsage(AU);
156 }
157 
158 void RABasic::releaseMemory() {
159  SpillerInstance.reset();
160 }
161 
162 
163 // Spill or split all live virtual registers currently unified under PhysReg
164 // that interfere with VirtReg. The newly spilled or split live intervals are
165 // returned by appending them to SplitVRegs.
166 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
167  SmallVectorImpl<unsigned> &SplitVRegs) {
168  // Record each interference and determine if all are spillable before mutating
169  // either the union or live intervals.
171 
172  // Collect interferences assigned to any alias of the physical register.
173  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
174  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
176  if (Q.seenUnspillableVReg())
177  return false;
178  for (unsigned i = Q.interferingVRegs().size(); i; --i) {
179  LiveInterval *Intf = Q.interferingVRegs()[i - 1];
180  if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
181  return false;
182  Intfs.push_back(Intf);
183  }
184  }
185  DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
186  " interferences with " << VirtReg << "\n");
187  assert(!Intfs.empty() && "expected interference");
188 
189  // Spill each interfering vreg allocated to PhysReg or an alias.
190  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
191  LiveInterval &Spill = *Intfs[i];
192 
193  // Skip duplicates.
194  if (!VRM->hasPhys(Spill.reg))
195  continue;
196 
197  // Deallocate the interfering vreg by removing it from the union.
198  // A LiveInterval instance may not be in a union during modification!
199  Matrix->unassign(Spill);
200 
201  // Spill the extracted interval.
202  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
203  spiller().spill(LRE);
204  }
205  return true;
206 }
207 
208 // Driver for the register assignment and splitting heuristics.
209 // Manages iteration over the LiveIntervalUnions.
210 //
211 // This is a minimal implementation of register assignment and splitting that
212 // spills whenever we run out of registers.
213 //
214 // selectOrSplit can only be called once per live virtual register. We then do a
215 // single interference test for each register the correct class until we find an
216 // available register. So, the number of interference tests in the worst case is
217 // |vregs| * |machineregs|. And since the number of interference tests is
218 // minimal, there is no value in caching them outside the scope of
219 // selectOrSplit().
220 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
221  SmallVectorImpl<unsigned> &SplitVRegs) {
222  // Populate a list of physical register spill candidates.
223  SmallVector<unsigned, 8> PhysRegSpillCands;
224 
225  // Check for an available register in this class.
226  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
227  while (unsigned PhysReg = Order.next()) {
228  // Check for interference in PhysReg
229  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
230  case LiveRegMatrix::IK_Free:
231  // PhysReg is available, allocate it.
232  return PhysReg;
233 
234  case LiveRegMatrix::IK_VirtReg:
235  // Only virtual registers in the way, we may be able to spill them.
236  PhysRegSpillCands.push_back(PhysReg);
237  continue;
238 
239  default:
240  // RegMask or RegUnit interference.
241  continue;
242  }
243  }
244 
245  // Try to spill another interfering reg with less spill weight.
246  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
247  PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
248  if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
249  continue;
250 
251  assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
252  "Interference after spill.");
253  // Tell the caller to allocate to this newly freed physical register.
254  return *PhysRegI;
255  }
256 
257  // No other spill candidates were found, so spill the current VirtReg.
258  DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
259  if (!VirtReg.isSpillable())
260  return ~0u;
261  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
262  spiller().spill(LRE);
263 
264  // The live virtual register requesting allocation was spilled, so tell
265  // the caller not to allocate anything during this round.
266  return 0;
267 }
268 
269 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
270  DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
271  << "********** Function: "
272  << mf.getName() << '\n');
273 
274  MF = &mf;
275  RegAllocBase::init(getAnalysis<VirtRegMap>(),
276  getAnalysis<LiveIntervals>(),
277  getAnalysis<LiveRegMatrix>());
278 
280  getAnalysis<MachineLoopInfo>(),
281  getAnalysis<MachineBlockFrequencyInfo>());
282 
283  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
284 
285  allocatePhysRegs();
286 
287  // Diagnostic output before rewriting
288  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
289 
290  releaseMemory();
291  return true;
292 }
293 
295 {
296  return new RABasic();
297 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
const unsigned reg
Definition: LiveInterval.h:616
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:588
void initializeLiveDebugVariablesPass(PassRegistry &)
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:716
Spiller interface.
Definition: Spiller.h:24
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void initializeMachineLoopInfoPass(PassRegistry &)
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
void initializeRegisterCoalescerPass(PassRegistry &)
Live Register Matrix
AnalysisUsage & addRequired()
Query interferences between a single live virtual register and a live interval union.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
static RegisterRegAlloc basicRegAlloc("basic","basic register allocator", createBasicRegisterAllocator)
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:58
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
SlotIndexes pass.
Definition: SlotIndexes.h:334
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
AnalysisUsage & addPreservedID(const void *ID)
RegisterRegAlloc class - Track the registration of register allocators.
void initializeMachineDominatorTreePass(PassRegistry &)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:325
void initializeSlotIndexesPass(PassRegistry &)
void initializeLiveStacksPass(PassRegistry &)
Represent the analysis usage information of a pass.
void initializeLiveIntervalsPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:276
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:263
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
void initializeVirtRegMapPass(PassRegistry &)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
void initializeLiveRegMatrixPass(PassRegistry &)
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=UINT_MAX)
#define DEBUG(X)
Definition: Debug.h:92
StringRef getName() const
getName - Return the name of the corresponding LLVM function.