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 NodeMetadata(NodeMetadata &&Other)
88 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
89 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
90 OptionRegs(std::move(Other.OptionRegs)) {}
92 NodeMetadata& operator=(NodeMetadata &&Other) {
94 NumOpts = Other.NumOpts;
95 DeniedOpts = Other.DeniedOpts;
96 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
98 OptionRegs = std::move(Other.OptionRegs);
102 void setVReg(unsigned VReg) { this->VReg = VReg; }
103 unsigned getVReg() const { return VReg; }
105 void setOptionRegs(OptionToRegMap OptionRegs) {
106 this->OptionRegs = std::move(OptionRegs);
108 const OptionToRegMap& getOptionRegs() const { return OptionRegs; }
110 void setup(const Vector& Costs) {
111 NumOpts = Costs.getLength() - 1;
112 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
115 ReductionState getReductionState() const { return RS; }
116 void setReductionState(ReductionState RS) { this->RS = RS; }
118 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
119 DeniedOpts += Transpose ? MD.getWorstCol() : MD.getWorstRow();
120 const bool* UnsafeOpts =
121 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
122 for (unsigned i = 0; i < NumOpts; ++i)
123 OptUnsafeEdges[i] += UnsafeOpts[i];
126 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
127 DeniedOpts -= Transpose ? MD.getWorstCol() : MD.getWorstRow();
128 const bool* UnsafeOpts =
129 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
130 for (unsigned i = 0; i < NumOpts; ++i)
131 OptUnsafeEdges[i] -= UnsafeOpts[i];
134 bool isConservativelyAllocatable() const {
135 return (DeniedOpts < NumOpts) ||
136 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
137 &OptUnsafeEdges[NumOpts]);
141 NodeMetadata(const NodeMetadata&) LLVM_DELETED_FUNCTION;
142 void operator=(const NodeMetadata&) LLVM_DELETED_FUNCTION;
147 std::unique_ptr<unsigned[]> OptUnsafeEdges;
149 OptionToRegMap OptionRegs;
152 class RegAllocSolverImpl {
154 typedef MDMatrix<MatrixMetadata> RAMatrix;
156 typedef PBQP::Vector RawVector;
157 typedef PBQP::Matrix RawMatrix;
158 typedef PBQP::Vector Vector;
159 typedef RAMatrix Matrix;
160 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
162 typedef GraphBase::NodeId NodeId;
163 typedef GraphBase::EdgeId EdgeId;
165 typedef RegAlloc::NodeMetadata NodeMetadata;
167 struct EdgeMetadata { };
169 class GraphMetadata {
171 GraphMetadata(MachineFunction &MF,
173 MachineBlockFrequencyInfo &MBFI)
174 : MF(MF), LIS(LIS), MBFI(MBFI) {}
178 MachineBlockFrequencyInfo &MBFI;
180 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
181 VRegToNodeId[VReg] = NId;
184 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
185 auto VRegItr = VRegToNodeId.find(VReg);
186 if (VRegItr == VRegToNodeId.end())
187 return GraphBase::invalidNodeId();
188 return VRegItr->second;
191 void eraseNodeIdForVReg(unsigned VReg) {
192 VRegToNodeId.erase(VReg);
196 DenseMap<unsigned, NodeId> VRegToNodeId;
199 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
201 RegAllocSolverImpl(Graph &G) : G(G) {}
207 S = backpropagate(G, reduce());
212 void handleAddNode(NodeId NId) {
213 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
215 void handleRemoveNode(NodeId NId) {}
216 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
218 void handleAddEdge(EdgeId EId) {
219 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
220 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
223 void handleRemoveEdge(EdgeId EId) {
224 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
225 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
228 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
229 NodeMetadata& NMd = G.getNodeMetadata(NId);
230 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
231 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
232 if (G.getNodeDegree(NId) == 3) {
233 // This node is becoming optimally reducible.
234 moveToOptimallyReducibleNodes(NId);
235 } else if (NMd.getReductionState() ==
236 NodeMetadata::NotProvablyAllocatable &&
237 NMd.isConservativelyAllocatable()) {
238 // This node just became conservatively allocatable.
239 moveToConservativelyAllocatableNodes(NId);
243 void handleReconnectEdge(EdgeId EId, NodeId NId) {
244 NodeMetadata& NMd = G.getNodeMetadata(NId);
245 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
246 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
249 void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
250 handleRemoveEdge(EId);
252 NodeId N1Id = G.getEdgeNode1Id(EId);
253 NodeId N2Id = G.getEdgeNode2Id(EId);
254 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
255 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
256 const MatrixMetadata& MMd = NewCosts.getMetadata();
257 N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
258 N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
263 void removeFromCurrentSet(NodeId NId) {
264 switch (G.getNodeMetadata(NId).getReductionState()) {
265 case NodeMetadata::Unprocessed: break;
266 case NodeMetadata::OptimallyReducible:
267 assert(OptimallyReducibleNodes.find(NId) !=
268 OptimallyReducibleNodes.end() &&
269 "Node not in optimally reducible set.");
270 OptimallyReducibleNodes.erase(NId);
272 case NodeMetadata::ConservativelyAllocatable:
273 assert(ConservativelyAllocatableNodes.find(NId) !=
274 ConservativelyAllocatableNodes.end() &&
275 "Node not in conservatively allocatable set.");
276 ConservativelyAllocatableNodes.erase(NId);
278 case NodeMetadata::NotProvablyAllocatable:
279 assert(NotProvablyAllocatableNodes.find(NId) !=
280 NotProvablyAllocatableNodes.end() &&
281 "Node not in not-provably-allocatable set.");
282 NotProvablyAllocatableNodes.erase(NId);
287 void moveToOptimallyReducibleNodes(NodeId NId) {
288 removeFromCurrentSet(NId);
289 OptimallyReducibleNodes.insert(NId);
290 G.getNodeMetadata(NId).setReductionState(
291 NodeMetadata::OptimallyReducible);
294 void moveToConservativelyAllocatableNodes(NodeId NId) {
295 removeFromCurrentSet(NId);
296 ConservativelyAllocatableNodes.insert(NId);
297 G.getNodeMetadata(NId).setReductionState(
298 NodeMetadata::ConservativelyAllocatable);
301 void moveToNotProvablyAllocatableNodes(NodeId NId) {
302 removeFromCurrentSet(NId);
303 NotProvablyAllocatableNodes.insert(NId);
304 G.getNodeMetadata(NId).setReductionState(
305 NodeMetadata::NotProvablyAllocatable);
310 for (auto NId : G.nodeIds()) {
311 if (G.getNodeDegree(NId) < 3)
312 moveToOptimallyReducibleNodes(NId);
313 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
314 moveToConservativelyAllocatableNodes(NId);
316 moveToNotProvablyAllocatableNodes(NId);
320 // Compute a reduction order for the graph by iteratively applying PBQP
321 // reduction rules. Locally optimal rules are applied whenever possible (R0,
322 // R1, R2). If no locally-optimal rules apply then any conservatively
323 // allocatable node is reduced. Finally, if no conservatively allocatable
324 // node exists then the node with the lowest spill-cost:degree ratio is
326 std::vector<GraphBase::NodeId> reduce() {
327 assert(!G.empty() && "Cannot reduce empty graph.");
329 typedef GraphBase::NodeId NodeId;
330 std::vector<NodeId> NodeStack;
332 // Consume worklists.
334 if (!OptimallyReducibleNodes.empty()) {
335 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
337 OptimallyReducibleNodes.erase(NItr);
338 NodeStack.push_back(NId);
339 switch (G.getNodeDegree(NId)) {
348 default: llvm_unreachable("Not an optimally reducible node.");
350 } else if (!ConservativelyAllocatableNodes.empty()) {
351 // Conservatively allocatable nodes will never spill. For now just
352 // take the first node in the set and push it on the stack. When we
353 // start optimizing more heavily for register preferencing, it may
354 // would be better to push nodes with lower 'expected' or worst-case
355 // register costs first (since early nodes are the most
357 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
359 ConservativelyAllocatableNodes.erase(NItr);
360 NodeStack.push_back(NId);
361 G.disconnectAllNeighborsFromNode(NId);
363 } else if (!NotProvablyAllocatableNodes.empty()) {
364 NodeSet::iterator NItr =
365 std::min_element(NotProvablyAllocatableNodes.begin(),
366 NotProvablyAllocatableNodes.end(),
367 SpillCostComparator(G));
369 NotProvablyAllocatableNodes.erase(NItr);
370 NodeStack.push_back(NId);
371 G.disconnectAllNeighborsFromNode(NId);
379 class SpillCostComparator {
381 SpillCostComparator(const Graph& G) : G(G) {}
382 bool operator()(NodeId N1Id, NodeId N2Id) {
383 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
384 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
392 typedef std::set<NodeId> NodeSet;
393 NodeSet OptimallyReducibleNodes;
394 NodeSet ConservativelyAllocatableNodes;
395 NodeSet NotProvablyAllocatableNodes;
398 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
400 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
402 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
405 inline Solution solve(PBQPRAGraph& G) {
408 RegAllocSolverImpl RegAllocSolver(G);
409 return RegAllocSolver.solve();
412 } // namespace RegAlloc
415 /// @brief Create a PBQP register allocator instance.
417 createPBQPRegisterAllocator(char *customPassID = nullptr);
421 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */