LLVM  15.0.0git
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"
26 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/Spiller.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Debug.h"
34 #include <queue>
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "regalloc"
39 
40 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
42 
43 namespace {
44  struct CompSpillWeight {
45  bool operator()(const LiveInterval *A, const LiveInterval *B) const {
46  return A->weight() < B->weight();
47  }
48  };
49 }
50 
51 namespace {
52 /// RABasic provides a minimal implementation of the basic register allocation
53 /// algorithm. It prioritizes live virtual registers by spill weight and spills
54 /// whenever a register is unavailable. This is not practical in production but
55 /// provides a useful baseline both for measuring other allocators and comparing
56 /// the speed of the basic algorithm against other styles of allocators.
57 class RABasic : public MachineFunctionPass,
58  public RegAllocBase,
59  private LiveRangeEdit::Delegate {
60  // context
61  MachineFunction *MF;
62 
63  // state
64  std::unique_ptr<Spiller> SpillerInstance;
65  std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
66  CompSpillWeight>
67  Queue;
68 
69  // Scratch space. Allocated here to avoid repeated malloc calls in
70  // selectOrSplit().
71  BitVector UsableRegs;
72 
73  bool LRE_CanEraseVirtReg(Register) override;
74  void LRE_WillShrinkVirtReg(Register) override;
75 
76 public:
78 
79  /// Return the pass name.
80  StringRef getPassName() const override { return "Basic Register Allocator"; }
81 
82  /// RABasic analysis usage.
83  void getAnalysisUsage(AnalysisUsage &AU) const override;
84 
85  void releaseMemory() override;
86 
87  Spiller &spiller() override { return *SpillerInstance; }
88 
89  void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
90 
91  const LiveInterval *dequeue() override {
92  if (Queue.empty())
93  return nullptr;
94  const LiveInterval *LI = Queue.top();
95  Queue.pop();
96  return LI;
97  }
98 
99  MCRegister selectOrSplit(const LiveInterval &VirtReg,
100  SmallVectorImpl<Register> &SplitVRegs) override;
101 
102  /// Perform register allocation.
103  bool runOnMachineFunction(MachineFunction &mf) override;
104 
105  MachineFunctionProperties getRequiredProperties() const override {
108  }
109 
110  MachineFunctionProperties getClearedProperties() const override {
113  }
114 
115  // Helper for spilling all live virtual registers currently unified under preg
116  // that interfere with the most recently queried lvr. Return true if spilling
117  // was successful, and append any new spilled/split intervals to splitLVRs.
118  bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
119  SmallVectorImpl<Register> &SplitVRegs);
120 
121  static char ID;
122 };
123 
124 char RABasic::ID = 0;
125 
126 } // end anonymous namespace
127 
129 
130 INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
131  false, false)
135 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
136 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
143  false)
144 
145 bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
146  LiveInterval &LI = LIS->getInterval(VirtReg);
147  if (VRM->hasPhys(VirtReg)) {
148  Matrix->unassign(LI);
149  aboutToRemoveInterval(LI);
150  return true;
151  }
152  // Unassigned virtreg is probably in the priority queue.
153  // RegAllocBase will erase it after dequeueing.
154  // Nonetheless, clear the live-range so that the debug
155  // dump will show the right state for that VirtReg.
156  LI.clear();
157  return false;
158 }
159 
160 void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
161  if (!VRM->hasPhys(VirtReg))
162  return;
163 
164  // Register is assigned, put it back on the queue for reassignment.
165  LiveInterval &LI = LIS->getInterval(VirtReg);
166  Matrix->unassign(LI);
167  enqueue(&LI);
168 }
169 
170 RABasic::RABasic(RegClassFilterFunc F):
172  RegAllocBase(F) {
173 }
174 
175 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
176  AU.setPreservesCFG();
184  AU.addRequired<LiveStacks>();
185  AU.addPreserved<LiveStacks>();
192  AU.addRequired<VirtRegMap>();
193  AU.addPreserved<VirtRegMap>();
196  MachineFunctionPass::getAnalysisUsage(AU);
197 }
198 
199 void RABasic::releaseMemory() {
200  SpillerInstance.reset();
201 }
202 
203 
204 // Spill or split all live virtual registers currently unified under PhysReg
205 // that interfere with VirtReg. The newly spilled or split live intervals are
206 // returned by appending them to SplitVRegs.
207 bool RABasic::spillInterferences(const LiveInterval &VirtReg,
208  MCRegister PhysReg,
209  SmallVectorImpl<Register> &SplitVRegs) {
210  // Record each interference and determine if all are spillable before mutating
211  // either the union or live intervals.
213 
214  // Collect interferences assigned to any alias of the physical register.
215  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
216  LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
217  for (const auto *Intf : reverse(Q.interferingVRegs())) {
218  if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
219  return false;
220  Intfs.push_back(Intf);
221  }
222  }
223  LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
224  << " interferences with " << VirtReg << "\n");
225  assert(!Intfs.empty() && "expected interference");
226 
227  // Spill each interfering vreg allocated to PhysReg or an alias.
228  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
229  const LiveInterval &Spill = *Intfs[i];
230 
231  // Skip duplicates.
232  if (!VRM->hasPhys(Spill.reg()))
233  continue;
234 
235  // Deallocate the interfering vreg by removing it from the union.
236  // A LiveInterval instance may not be in a union during modification!
237  Matrix->unassign(Spill);
238 
239  // Spill the extracted interval.
240  LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
241  spiller().spill(LRE);
242  }
243  return true;
244 }
245 
246 // Driver for the register assignment and splitting heuristics.
247 // Manages iteration over the LiveIntervalUnions.
248 //
249 // This is a minimal implementation of register assignment and splitting that
250 // spills whenever we run out of registers.
251 //
252 // selectOrSplit can only be called once per live virtual register. We then do a
253 // single interference test for each register the correct class until we find an
254 // available register. So, the number of interference tests in the worst case is
255 // |vregs| * |machineregs|. And since the number of interference tests is
256 // minimal, there is no value in caching them outside the scope of
257 // selectOrSplit().
258 MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
259  SmallVectorImpl<Register> &SplitVRegs) {
260  // Populate a list of physical register spill candidates.
261  SmallVector<MCRegister, 8> PhysRegSpillCands;
262 
263  // Check for an available register in this class.
264  auto Order =
265  AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
266  for (MCRegister PhysReg : Order) {
267  assert(PhysReg.isValid());
268  // Check for interference in PhysReg
269  switch (Matrix->checkInterference(VirtReg, PhysReg)) {
270  case LiveRegMatrix::IK_Free:
271  // PhysReg is available, allocate it.
272  return PhysReg;
273 
274  case LiveRegMatrix::IK_VirtReg:
275  // Only virtual registers in the way, we may be able to spill them.
276  PhysRegSpillCands.push_back(PhysReg);
277  continue;
278 
279  default:
280  // RegMask or RegUnit interference.
281  continue;
282  }
283  }
284 
285  // Try to spill another interfering reg with less spill weight.
286  for (MCRegister &PhysReg : PhysRegSpillCands) {
287  if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
288  continue;
289 
290  assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
291  "Interference after spill.");
292  // Tell the caller to allocate to this newly freed physical register.
293  return PhysReg;
294  }
295 
296  // No other spill candidates were found, so spill the current VirtReg.
297  LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
298  if (!VirtReg.isSpillable())
299  return ~0u;
300  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
301  spiller().spill(LRE);
302 
303  // The live virtual register requesting allocation was spilled, so tell
304  // the caller not to allocate anything during this round.
305  return 0;
306 }
307 
308 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
309  LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
310  << "********** Function: " << mf.getName() << '\n');
311 
312  MF = &mf;
313  RegAllocBase::init(getAnalysis<VirtRegMap>(),
314  getAnalysis<LiveIntervals>(),
315  getAnalysis<LiveRegMatrix>());
316  VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
317  getAnalysis<MachineBlockFrequencyInfo>());
318  VRAI.calculateSpillWeightsAndHints();
319 
320  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
321 
322  allocatePhysRegs();
323  postOptimization();
324 
325  // Diagnostic output before rewriting
326  LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
327 
328  releaseMemory();
329  return true;
330 }
331 
333  return new RABasic();
334 }
335 
337  return new RABasic(F);
338 }
i
i
Definition: README.txt:29
llvm::Spiller
Spiller interface.
Definition: Spiller.h:24
LiveRegMatrix.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
llvm::RABasicID
char & RABasicID
Basic register allocator.
Definition: RegAllocBasic.cpp:128
AllocationOrder.h
Pass.h
llvm::LiveInterval::isSpillable
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:819
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1185
LiveDebugVariables.h
llvm::VirtRegAuxInfo
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
Definition: CalcSpillWeights.h:45
llvm::LiveInterval::weight
float weight() const
Definition: LiveInterval.h:718
llvm::MCRegister::isValid
bool isValid() const
Definition: MCRegister.h:76
llvm::VirtRegMap
Definition: VirtRegMap.h:33
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
Spiller.h
llvm::reverse
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:380
llvm::MachineFunctionProperties::Property::IsSSA
@ IsSSA
llvm::MachineFunctionProperties
Properties which a MachineFunction may have at a given point in time.
Definition: MachineFunction.h:127
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1628
llvm::RegisterRegAlloc
Definition: RegAllocRegistry.h:61
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::AMDGPU::HSAMD::ValueKind::Queue
@ Queue
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::MachineLoopInfo
Definition: MachineLoopInfo.h:89
AliasAnalysis.h
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::createInlineSpiller
Spiller * createInlineSpiller(MachineFunctionPass &Pass, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
Definition: InlineSpiller.cpp:245
MachineLoopInfo.h
llvm::MachineBlockFrequencyInfo
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
Definition: MachineBlockFrequencyInfo.h:33
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
false
Definition: StackSlotColoring.cpp:141
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::LiveRangeEdit
Definition: LiveRangeEdit.h:44
llvm::MachineFunctionProperties::set
MachineFunctionProperties & set(Property P)
Definition: MachineFunction.h:196
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator", false, false) INITIALIZE_PASS_END(RABasic
llvm::SlotIndexes
SlotIndexes pass.
Definition: SlotIndexes.h:313
llvm::BitVector
Definition: BitVector.h:75
llvm::LiveInterval
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:686
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
Passes.h
LiveIntervals.h
VirtRegMap.h
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::RegClassFilterFunc
std::function< bool(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC)> RegClassFilterFunc
Definition: RegAllocCommon.h:17
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
MachineFunctionPass.h
llvm::MachineFunction::getName
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Definition: MachineFunction.cpp:565
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::LiveDebugVariables
Definition: LiveDebugVariables.h:32
llvm::MachineFunction
Definition: MachineFunction.h:257
Matrix
Live Register Matrix
Definition: LiveRegMatrix.cpp:44
llvm::AnalysisUsage::setPreservesCFG
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:263
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::AnalysisUsage::addPreservedID
AnalysisUsage & addPreservedID(const void *ID)
Definition: PassAnalysisSupport.h:88
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
llvm::LiveIntervalUnion::Query::interferingVRegs
const SmallVectorImpl< const LiveInterval * > & interferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
Definition: LiveIntervalUnion.h:162
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
LiveRangeEdit.h
RegAllocBase.h
llvm::MachineFunctionProperties::Property::NoPHIs
@ NoPHIs
llvm::allocateAllRegClasses
static bool allocateAllRegClasses(const TargetRegisterInfo &, const TargetRegisterClass &)
Default register class filter function for register allocation.
Definition: RegAllocCommon.h:24
llvm::RegAllocBase
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
Definition: RegAllocBase.h:61
llvm::LiveIntervals
Definition: LiveIntervals.h:54
llvm::MCRegUnitIterator
Definition: MCRegisterInfo.h:680
llvm::LiveIntervalUnion::Query
Query interferences between a single live virtual register and a live interval union.
Definition: LiveIntervalUnion.h:112
LiveStacks.h
Allocator
Basic Register Allocator
Definition: RegAllocBasic.cpp:142
llvm::MCRegisterInfo::DiffListIterator::isValid
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
Definition: MCRegisterInfo.h:224
llvm::AAResultsWrapperPass
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Definition: AliasAnalysis.h:1351
llvm::MachineDominatorsID
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
llvm::LiveInterval::reg
Register reg() const
Definition: LiveInterval.h:717
llvm::LiveRange::clear
void clear()
Definition: LiveInterval.h:300
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
llvm::createBasicRegisterAllocator
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
Definition: RegAllocBasic.cpp:332
llvm::AnalysisUsage::addRequiredID
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:277
llvm::LiveRangeEdit::Delegate
Callback methods for LiveRangeEdit owners.
Definition: LiveRangeEdit.h:47
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
CalcSpillWeights.h
regallocbasic
regallocbasic
Definition: RegAllocBasic.cpp:142
raw_ostream.h
llvm::MachineDominatorTree
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Definition: MachineDominators.h:51
llvm::printReg
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
Definition: TargetRegisterInfo.cpp:111
llvm::LiveStacks
Definition: LiveStacks.h:35
MachineBlockFrequencyInfo.h
basicRegAlloc
static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator)
TargetRegisterInfo.h
Debug.h
RegAllocRegistry.h
llvm::MCRegister
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:24
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::LiveRegMatrix
Definition: LiveRegMatrix.h:40