LLVM  9.0.0svn
RegAllocBasic.cpp
Go to the documentation of this file.
1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RABasic function pass, which provides a minimal
10 // implementation of the basic register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AllocationOrder.h"
15 #include "LiveDebugVariables.h"
16 #include "RegAllocBase.h"
17 #include "Spiller.h"
29 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Support/Debug.h"
36 #include <cstdlib>
37 #include <queue>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "regalloc"
42 
43 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
45 
46 namespace {
47  struct CompSpillWeight {
48  bool operator()(LiveInterval *A, LiveInterval *B) const {
49  return A->weight < B->weight;
50  }
51  };
52 }
53 
54 namespace {
55 /// RABasic provides a minimal implementation of the basic register allocation
56 /// algorithm. It prioritizes live virtual registers by spill weight and spills
57 /// whenever a register is unavailable. This is not practical in production but
58 /// provides a useful baseline both for measuring other allocators and comparing
59 /// the speed of the basic algorithm against other styles of allocators.
60 class RABasic : public MachineFunctionPass,
61  public RegAllocBase,
62  private LiveRangeEdit::Delegate {
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  bool LRE_CanEraseVirtReg(unsigned) override;
76  void LRE_WillShrinkVirtReg(unsigned) override;
77 
78 public:
79  RABasic();
80 
81  /// Return the pass name.
82  StringRef getPassName() const override { return "Basic Register Allocator"; }
83 
84  /// RABasic analysis usage.
85  void getAnalysisUsage(AnalysisUsage &AU) const override;
86 
87  void releaseMemory() override;
88 
89  Spiller &spiller() override { return *SpillerInstance; }
90 
91  void enqueue(LiveInterval *LI) override {
92  Queue.push(LI);
93  }
94 
95  LiveInterval *dequeue() override {
96  if (Queue.empty())
97  return nullptr;
98  LiveInterval *LI = Queue.top();
99  Queue.pop();
100  return LI;
101  }
102 
103  unsigned selectOrSplit(LiveInterval &VirtReg,
104  SmallVectorImpl<unsigned> &SplitVRegs) override;
105 
106  /// Perform register allocation.
107  bool runOnMachineFunction(MachineFunction &mf) override;
108 
109  MachineFunctionProperties getRequiredProperties() const override {
112  }
113 
114  // Helper for spilling all live virtual registers currently unified under preg
115  // that interfere with the most recently queried lvr. Return true if spilling
116  // was successful, and append any new spilled/split intervals to splitLVRs.
117  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
118  SmallVectorImpl<unsigned> &SplitVRegs);
119 
120  static char ID;
121 };
122 
123 char RABasic::ID = 0;
124 
125 } // end anonymous namespace
126 
128 
129 INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
130  false, false)
134 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
135 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
142  false)
143 
144 bool RABasic::LRE_CanEraseVirtReg(unsigned VirtReg) {
145  LiveInterval &LI = LIS->getInterval(VirtReg);
146  if (VRM->hasPhys(VirtReg)) {
147  Matrix->unassign(LI);
148  aboutToRemoveInterval(LI);
149  return true;
150  }
151  // Unassigned virtreg is probably in the priority queue.
152  // RegAllocBase will erase it after dequeueing.
153  // Nonetheless, clear the live-range so that the debug
154  // dump will show the right state for that VirtReg.
155  LI.clear();
156  return false;
157 }
158 
159 void RABasic::LRE_WillShrinkVirtReg(unsigned VirtReg) {
160  if (!VRM->hasPhys(VirtReg))
161  return;
162 
163  // Register is assigned, put it back on the queue for reassignment.
164  LiveInterval &LI = LIS->getInterval(VirtReg);
165  Matrix->unassign(LI);
166  enqueue(&LI);
167 }
168 
169 RABasic::RABasic(): MachineFunctionPass(ID) {
170 }
171 
172 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
173  AU.setPreservesCFG();
181  AU.addRequired<LiveStacks>();
182  AU.addPreserved<LiveStacks>();
189  AU.addRequired<VirtRegMap>();
190  AU.addPreserved<VirtRegMap>();
194 }
195 
196 void RABasic::releaseMemory() {
197  SpillerInstance.reset();
198 }
199 
200 
201 // Spill or split all live virtual registers currently unified under PhysReg
202 // that interfere with VirtReg. The newly spilled or split live intervals are
203 // returned by appending them to SplitVRegs.
204 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
205  SmallVectorImpl<unsigned> &SplitVRegs) {
206  // Record each interference and determine if all are spillable before mutating
207  // either the union or live intervals.
209 
210  // Collect interferences assigned to any alias of the physical register.
211  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
212  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
214  for (unsigned i = Q.interferingVRegs().size(); i; --i) {
215  LiveInterval *Intf = Q.interferingVRegs()[i - 1];
216  if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
217  return false;
218  Intfs.push_back(Intf);
219  }
220  }
221  LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
222  << " interferences with " << VirtReg << "\n");
223  assert(!Intfs.empty() && "expected interference");
224 
225  // Spill each interfering vreg allocated to PhysReg or an alias.
226  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
227  LiveInterval &Spill = *Intfs[i];
228 
229  // Skip duplicates.
230  if (!VRM->hasPhys(Spill.reg))
231  continue;
232 
233  // Deallocate the interfering vreg by removing it from the union.
234  // A LiveInterval instance may not be in a union during modification!
235  Matrix->unassign(Spill);
236 
237  // Spill the extracted interval.
238  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
239  spiller().spill(LRE);
240  }
241  return true;
242 }
243 
244 // Driver for the register assignment and splitting heuristics.
245 // Manages iteration over the LiveIntervalUnions.
246 //
247 // This is a minimal implementation of register assignment and splitting that
248 // spills whenever we run out of registers.
249 //
250 // selectOrSplit can only be called once per live virtual register. We then do a
251 // single interference test for each register the correct class until we find an
252 // available register. So, the number of interference tests in the worst case is
253 // |vregs| * |machineregs|. And since the number of interference tests is
254 // minimal, there is no value in caching them outside the scope of
255 // selectOrSplit().
256 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
257  SmallVectorImpl<unsigned> &SplitVRegs) {
258  // Populate a list of physical register spill candidates.
259  SmallVector<unsigned, 8> PhysRegSpillCands;
260 
261  // Check for an available register in this class.
262  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
263  while (unsigned PhysReg = Order.next()) {
264  // Check for interference in PhysReg
265  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
267  // PhysReg is available, allocate it.
268  return PhysReg;
269 
271  // Only virtual registers in the way, we may be able to spill them.
272  PhysRegSpillCands.push_back(PhysReg);
273  continue;
274 
275  default:
276  // RegMask or RegUnit interference.
277  continue;
278  }
279  }
280 
281  // Try to spill another interfering reg with less spill weight.
282  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
283  PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
284  if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
285  continue;
286 
287  assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
288  "Interference after spill.");
289  // Tell the caller to allocate to this newly freed physical register.
290  return *PhysRegI;
291  }
292 
293  // No other spill candidates were found, so spill the current VirtReg.
294  LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
295  if (!VirtReg.isSpillable())
296  return ~0u;
297  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
298  spiller().spill(LRE);
299 
300  // The live virtual register requesting allocation was spilled, so tell
301  // the caller not to allocate anything during this round.
302  return 0;
303 }
304 
305 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
306  LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
307  << "********** Function: " << mf.getName() << '\n');
308 
309  MF = &mf;
310  RegAllocBase::init(getAnalysis<VirtRegMap>(),
311  getAnalysis<LiveIntervals>(),
312  getAnalysis<LiveRegMatrix>());
313 
314  calculateSpillWeightsAndHints(*LIS, *MF, VRM,
315  getAnalysis<MachineLoopInfo>(),
316  getAnalysis<MachineBlockFrequencyInfo>());
317 
318  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
319 
320  allocatePhysRegs();
321  postOptimization();
322 
323  // Diagnostic output before rewriting
324  LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
325 
326  releaseMemory();
327  return true;
328 }
329 
331 {
332  return new RABasic();
333 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
No interference, go ahead and assign.
Definition: LiveRegMatrix.h:85
const unsigned reg
Definition: LiveInterval.h:666
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
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:637
Spiller interface.
Definition: Spiller.h:23
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
unsigned next(unsigned Limit=0)
Return the next physical register in the allocation order, or 0.
unsigned const TargetRegisterInfo * TRI
Callback methods for LiveRangeEdit owners.
Definition: LiveRangeEdit.h:48
Live Register Matrix
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
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...
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator", false, false) INITIALIZE_PASS_END(RABasic
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:60
SlotIndexes pass.
Definition: SlotIndexes.h:328
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
AnalysisUsage & addPreservedID(const void *ID)
char & RABasicID
Basic register allocator.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
size_t size() const
Definition: SmallVector.h:52
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Basic Register Allocator
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, VirtRegMap *VRM, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:314
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
Promote Memory to Register
Definition: Mem2Reg.cpp:109
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
MachineFunctionProperties & set(Property P)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
regallocbasic
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:766
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
#define LLVM_DEBUG(X)
Definition: Debug.h:122
Virtual register interference.
Definition: LiveRegMatrix.h:90
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Properties which a MachineFunction may have at a given point in time.