1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
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 PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/PBQPRAConstraint.h"
21 #include "llvm/CodeGen/PBQP/CostAllocator.h"
22 #include "llvm/CodeGen/PBQP/ReductionRules.h"
23 #include "llvm/Support/ErrorHandling.h"
29 /// @brief Spill option index.
30 inline unsigned getSpillOptionIdx() { return 0; }
32 /// \brief Metadata to speed allocatability test.
34 /// Keeps track of the number of infinities in each row and column.
35 class MatrixMetadata {
37 MatrixMetadata(const MatrixMetadata&);
38 void operator=(const MatrixMetadata&);
40 MatrixMetadata(const Matrix& M)
41 : WorstRow(0), WorstCol(0),
42 UnsafeRows(new bool[M.getRows() - 1]()),
43 UnsafeCols(new bool[M.getCols() - 1]()) {
45 unsigned* ColCounts = new unsigned[M.getCols() - 1]();
47 for (unsigned i = 1; i < M.getRows(); ++i) {
48 unsigned RowCount = 0;
49 for (unsigned j = 1; j < M.getCols(); ++j) {
50 if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
53 UnsafeRows[i - 1] = true;
54 UnsafeCols[j - 1] = true;
57 WorstRow = std::max(WorstRow, RowCount);
59 unsigned WorstColCountForCurRow =
60 *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
61 WorstCol = std::max(WorstCol, WorstColCountForCurRow);
65 unsigned getWorstRow() const { return WorstRow; }
66 unsigned getWorstCol() const { return WorstCol; }
67 const bool* getUnsafeRows() const { return UnsafeRows.get(); }
68 const bool* getUnsafeCols() const { return UnsafeCols.get(); }
71 unsigned WorstRow, WorstCol;
72 std::unique_ptr<bool[]> UnsafeRows;
73 std::unique_ptr<bool[]> UnsafeCols;
78 typedef std::vector<unsigned> OptionToRegMap;
80 typedef enum { Unprocessed,
82 ConservativelyAllocatable,
83 NotProvablyAllocatable } ReductionState;
85 NodeMetadata() : RS(Unprocessed), DeniedOpts(0), OptUnsafeEdges(nullptr){}
87 void setVReg(unsigned VReg) { this->VReg = VReg; }
88 unsigned getVReg() const { return VReg; }
90 void setOptionRegs(OptionToRegMap OptionRegs) {
91 this->OptionRegs = std::move(OptionRegs);
93 const OptionToRegMap& getOptionRegs() const { return OptionRegs; }
95 void setup(const Vector& Costs) {
96 NumOpts = Costs.getLength() - 1;
97 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
100 ReductionState getReductionState() const { return RS; }
101 void setReductionState(ReductionState RS) { this->RS = RS; }
103 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
104 DeniedOpts += Transpose ? MD.getWorstCol() : MD.getWorstRow();
105 const bool* UnsafeOpts =
106 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
107 for (unsigned i = 0; i < NumOpts; ++i)
108 OptUnsafeEdges[i] += UnsafeOpts[i];
111 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
112 DeniedOpts -= Transpose ? MD.getWorstCol() : MD.getWorstRow();
113 const bool* UnsafeOpts =
114 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
115 for (unsigned i = 0; i < NumOpts; ++i)
116 OptUnsafeEdges[i] -= UnsafeOpts[i];
119 bool isConservativelyAllocatable() const {
120 return (DeniedOpts < NumOpts) ||
121 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
122 &OptUnsafeEdges[NumOpts]);
129 std::unique_ptr<unsigned[]> OptUnsafeEdges;
131 OptionToRegMap OptionRegs;
134 class RegAllocSolverImpl {
136 typedef MDMatrix<MatrixMetadata> RAMatrix;
138 typedef PBQP::Vector RawVector;
139 typedef PBQP::Matrix RawMatrix;
140 typedef PBQP::Vector Vector;
141 typedef RAMatrix Matrix;
142 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
144 typedef GraphBase::NodeId NodeId;
145 typedef GraphBase::EdgeId EdgeId;
147 typedef RegAlloc::NodeMetadata NodeMetadata;
149 struct EdgeMetadata { };
151 class GraphMetadata {
153 GraphMetadata(MachineFunction &MF,
155 MachineBlockFrequencyInfo &MBFI)
156 : MF(MF), LIS(LIS), MBFI(MBFI) {}
160 MachineBlockFrequencyInfo &MBFI;
162 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
163 VRegToNodeId[VReg] = NId;
166 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
167 auto VRegItr = VRegToNodeId.find(VReg);
168 if (VRegItr == VRegToNodeId.end())
169 return GraphBase::invalidNodeId();
170 return VRegItr->second;
173 void eraseNodeIdForVReg(unsigned VReg) {
174 VRegToNodeId.erase(VReg);
178 DenseMap<unsigned, NodeId> VRegToNodeId;
181 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
183 RegAllocSolverImpl(Graph &G) : G(G) {}
189 S = backpropagate(G, reduce());
194 void handleAddNode(NodeId NId) {
195 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
197 void handleRemoveNode(NodeId NId) {}
198 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
200 void handleAddEdge(EdgeId EId) {
201 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
202 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
205 void handleRemoveEdge(EdgeId EId) {
206 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
207 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
210 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
211 NodeMetadata& NMd = G.getNodeMetadata(NId);
212 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
213 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
214 if (G.getNodeDegree(NId) == 3) {
215 // This node is becoming optimally reducible.
216 moveToOptimallyReducibleNodes(NId);
217 } else if (NMd.getReductionState() ==
218 NodeMetadata::NotProvablyAllocatable &&
219 NMd.isConservativelyAllocatable()) {
220 // This node just became conservatively allocatable.
221 moveToConservativelyAllocatableNodes(NId);
225 void handleReconnectEdge(EdgeId EId, NodeId NId) {
226 NodeMetadata& NMd = G.getNodeMetadata(NId);
227 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
228 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
231 void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
232 handleRemoveEdge(EId);
234 NodeId N1Id = G.getEdgeNode1Id(EId);
235 NodeId N2Id = G.getEdgeNode2Id(EId);
236 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
237 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
238 const MatrixMetadata& MMd = NewCosts.getMetadata();
239 N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
240 N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
245 void removeFromCurrentSet(NodeId NId) {
246 switch (G.getNodeMetadata(NId).getReductionState()) {
247 case NodeMetadata::Unprocessed: break;
248 case NodeMetadata::OptimallyReducible:
249 assert(OptimallyReducibleNodes.find(NId) !=
250 OptimallyReducibleNodes.end() &&
251 "Node not in optimally reducible set.");
252 OptimallyReducibleNodes.erase(NId);
254 case NodeMetadata::ConservativelyAllocatable:
255 assert(ConservativelyAllocatableNodes.find(NId) !=
256 ConservativelyAllocatableNodes.end() &&
257 "Node not in conservatively allocatable set.");
258 ConservativelyAllocatableNodes.erase(NId);
260 case NodeMetadata::NotProvablyAllocatable:
261 assert(NotProvablyAllocatableNodes.find(NId) !=
262 NotProvablyAllocatableNodes.end() &&
263 "Node not in not-provably-allocatable set.");
264 NotProvablyAllocatableNodes.erase(NId);
269 void moveToOptimallyReducibleNodes(NodeId NId) {
270 removeFromCurrentSet(NId);
271 OptimallyReducibleNodes.insert(NId);
272 G.getNodeMetadata(NId).setReductionState(
273 NodeMetadata::OptimallyReducible);
276 void moveToConservativelyAllocatableNodes(NodeId NId) {
277 removeFromCurrentSet(NId);
278 ConservativelyAllocatableNodes.insert(NId);
279 G.getNodeMetadata(NId).setReductionState(
280 NodeMetadata::ConservativelyAllocatable);
283 void moveToNotProvablyAllocatableNodes(NodeId NId) {
284 removeFromCurrentSet(NId);
285 NotProvablyAllocatableNodes.insert(NId);
286 G.getNodeMetadata(NId).setReductionState(
287 NodeMetadata::NotProvablyAllocatable);
292 for (auto NId : G.nodeIds()) {
293 if (G.getNodeDegree(NId) < 3)
294 moveToOptimallyReducibleNodes(NId);
295 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
296 moveToConservativelyAllocatableNodes(NId);
298 moveToNotProvablyAllocatableNodes(NId);
302 // Compute a reduction order for the graph by iteratively applying PBQP
303 // reduction rules. Locally optimal rules are applied whenever possible (R0,
304 // R1, R2). If no locally-optimal rules apply then any conservatively
305 // allocatable node is reduced. Finally, if no conservatively allocatable
306 // node exists then the node with the lowest spill-cost:degree ratio is
308 std::vector<GraphBase::NodeId> reduce() {
309 assert(!G.empty() && "Cannot reduce empty graph.");
311 typedef GraphBase::NodeId NodeId;
312 std::vector<NodeId> NodeStack;
314 // Consume worklists.
316 if (!OptimallyReducibleNodes.empty()) {
317 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
319 OptimallyReducibleNodes.erase(NItr);
320 NodeStack.push_back(NId);
321 switch (G.getNodeDegree(NId)) {
330 default: llvm_unreachable("Not an optimally reducible node.");
332 } else if (!ConservativelyAllocatableNodes.empty()) {
333 // Conservatively allocatable nodes will never spill. For now just
334 // take the first node in the set and push it on the stack. When we
335 // start optimizing more heavily for register preferencing, it may
336 // would be better to push nodes with lower 'expected' or worst-case
337 // register costs first (since early nodes are the most
339 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
341 ConservativelyAllocatableNodes.erase(NItr);
342 NodeStack.push_back(NId);
343 G.disconnectAllNeighborsFromNode(NId);
345 } else if (!NotProvablyAllocatableNodes.empty()) {
346 NodeSet::iterator NItr =
347 std::min_element(NotProvablyAllocatableNodes.begin(),
348 NotProvablyAllocatableNodes.end(),
349 SpillCostComparator(G));
351 NotProvablyAllocatableNodes.erase(NItr);
352 NodeStack.push_back(NId);
353 G.disconnectAllNeighborsFromNode(NId);
361 class SpillCostComparator {
363 SpillCostComparator(const Graph& G) : G(G) {}
364 bool operator()(NodeId N1Id, NodeId N2Id) {
365 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
366 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
374 typedef std::set<NodeId> NodeSet;
375 NodeSet OptimallyReducibleNodes;
376 NodeSet ConservativelyAllocatableNodes;
377 NodeSet NotProvablyAllocatableNodes;
380 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
382 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
384 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
387 inline Solution solve(PBQPRAGraph& G) {
390 RegAllocSolverImpl RegAllocSolver(G);
391 return RegAllocSolver.solve();
394 } // namespace RegAlloc
397 /// @brief Create a PBQP register allocator instance.
399 createPBQPRegisterAllocator(char *customPassID = nullptr);
403 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */