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/PBQP/CostAllocator.h"
21 #include "llvm/CodeGen/PBQP/ReductionRules.h"
22 #include "llvm/CodeGen/PBQPRAConstraint.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;
76 /// \brief Holds a vector of the allowed physical regs for a vreg.
77 class AllowedRegVector {
78 friend hash_code hash_value(const AllowedRegVector &);
81 AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
83 AllowedRegVector(const std::vector<unsigned> &OptVec)
84 : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
85 std::copy(OptVec.begin(), OptVec.end(), Opts.get());
88 AllowedRegVector(const AllowedRegVector &Other)
89 : NumOpts(Other.NumOpts), Opts(new unsigned[NumOpts]) {
90 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
93 AllowedRegVector(AllowedRegVector &&Other)
94 : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
96 AllowedRegVector& operator=(const AllowedRegVector &Other) {
97 NumOpts = Other.NumOpts;
98 Opts.reset(new unsigned[NumOpts]);
99 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
103 AllowedRegVector& operator=(AllowedRegVector &&Other) {
104 NumOpts = std::move(Other.NumOpts);
105 Opts = std::move(Other.Opts);
109 unsigned size() const { return NumOpts; }
110 unsigned operator[](size_t I) const { return Opts[I]; }
112 bool operator==(const AllowedRegVector &Other) const {
113 if (NumOpts != Other.NumOpts)
115 return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
118 bool operator!=(const AllowedRegVector &Other) const {
119 return !(*this == Other);
124 std::unique_ptr<unsigned[]> Opts;
127 inline hash_code hash_value(const AllowedRegVector &OptRegs) {
128 unsigned *OStart = OptRegs.Opts.get();
129 unsigned *OEnd = OptRegs.Opts.get() + OptRegs.NumOpts;
130 return hash_combine(OptRegs.NumOpts,
131 hash_combine_range(OStart, OEnd));
134 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
135 class GraphMetadata {
137 typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
140 typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
142 GraphMetadata(MachineFunction &MF,
144 MachineBlockFrequencyInfo &MBFI)
145 : MF(MF), LIS(LIS), MBFI(MBFI) {}
149 MachineBlockFrequencyInfo &MBFI;
151 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
152 VRegToNodeId[VReg] = NId;
155 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
156 auto VRegItr = VRegToNodeId.find(VReg);
157 if (VRegItr == VRegToNodeId.end())
158 return GraphBase::invalidNodeId();
159 return VRegItr->second;
162 void eraseNodeIdForVReg(unsigned VReg) {
163 VRegToNodeId.erase(VReg);
166 AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
167 return AllowedRegVecs.getValue(std::move(Allowed));
171 DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
172 AllowedRegVecPool AllowedRegVecs;
175 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
178 typedef RegAlloc::AllowedRegVector AllowedRegVector;
180 typedef enum { Unprocessed,
182 ConservativelyAllocatable,
183 NotProvablyAllocatable } ReductionState;
186 : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
189 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
190 // MSVC synthesizes move constructors properly.
191 NodeMetadata(const NodeMetadata &Other)
192 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
193 OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
194 AllowedRegs(Other.AllowedRegs) {
196 std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
201 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
202 // MSVC synthesizes move constructors properly.
203 NodeMetadata(NodeMetadata &&Other)
204 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
205 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
206 AllowedRegs(std::move(Other.AllowedRegs)) {}
208 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
209 // MSVC synthesizes move constructors properly.
210 NodeMetadata& operator=(const NodeMetadata &Other) {
212 NumOpts = Other.NumOpts;
213 DeniedOpts = Other.DeniedOpts;
214 OptUnsafeEdges.reset(new unsigned[NumOpts]);
215 std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
216 OptUnsafeEdges.get());
218 AllowedRegs = Other.AllowedRegs;
222 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
223 // MSVC synthesizes move constructors properly.
224 NodeMetadata& operator=(NodeMetadata &&Other) {
226 NumOpts = Other.NumOpts;
227 DeniedOpts = Other.DeniedOpts;
228 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
230 AllowedRegs = std::move(Other.AllowedRegs);
234 void setVReg(unsigned VReg) { this->VReg = VReg; }
235 unsigned getVReg() const { return VReg; }
237 void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
238 this->AllowedRegs = std::move(AllowedRegs);
240 const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
242 void setup(const Vector& Costs) {
243 NumOpts = Costs.getLength() - 1;
244 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
247 ReductionState getReductionState() const { return RS; }
248 void setReductionState(ReductionState RS) { this->RS = RS; }
250 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
251 DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
252 const bool* UnsafeOpts =
253 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
254 for (unsigned i = 0; i < NumOpts; ++i)
255 OptUnsafeEdges[i] += UnsafeOpts[i];
258 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
259 DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
260 const bool* UnsafeOpts =
261 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
262 for (unsigned i = 0; i < NumOpts; ++i)
263 OptUnsafeEdges[i] -= UnsafeOpts[i];
266 bool isConservativelyAllocatable() const {
267 return (DeniedOpts < NumOpts) ||
268 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
269 &OptUnsafeEdges[NumOpts]);
276 std::unique_ptr<unsigned[]> OptUnsafeEdges;
278 GraphMetadata::AllowedRegVecRef AllowedRegs;
281 class RegAllocSolverImpl {
283 typedef MDMatrix<MatrixMetadata> RAMatrix;
285 typedef PBQP::Vector RawVector;
286 typedef PBQP::Matrix RawMatrix;
287 typedef PBQP::Vector Vector;
288 typedef RAMatrix Matrix;
289 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
291 typedef GraphBase::NodeId NodeId;
292 typedef GraphBase::EdgeId EdgeId;
294 typedef RegAlloc::NodeMetadata NodeMetadata;
295 struct EdgeMetadata { };
296 typedef RegAlloc::GraphMetadata GraphMetadata;
298 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
300 RegAllocSolverImpl(Graph &G) : G(G) {}
306 S = backpropagate(G, reduce());
311 void handleAddNode(NodeId NId) {
312 assert(G.getNodeCosts(NId).getLength() > 1 &&
313 "PBQP Graph should not contain single or zero-option nodes");
314 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
316 void handleRemoveNode(NodeId NId) {}
317 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
319 void handleAddEdge(EdgeId EId) {
320 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
321 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
324 void handleRemoveEdge(EdgeId EId) {
325 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
326 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
329 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
330 NodeMetadata& NMd = G.getNodeMetadata(NId);
331 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
332 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
333 if (G.getNodeDegree(NId) == 3) {
334 // This node is becoming optimally reducible.
335 moveToOptimallyReducibleNodes(NId);
336 } else if (NMd.getReductionState() ==
337 NodeMetadata::NotProvablyAllocatable &&
338 NMd.isConservativelyAllocatable()) {
339 // This node just became conservatively allocatable.
340 moveToConservativelyAllocatableNodes(NId);
344 void handleReconnectEdge(EdgeId EId, NodeId NId) {
345 NodeMetadata& NMd = G.getNodeMetadata(NId);
346 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
347 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
350 void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
351 handleRemoveEdge(EId);
353 NodeId N1Id = G.getEdgeNode1Id(EId);
354 NodeId N2Id = G.getEdgeNode2Id(EId);
355 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
356 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
357 const MatrixMetadata& MMd = NewCosts.getMetadata();
358 N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
359 N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
364 void removeFromCurrentSet(NodeId NId) {
365 switch (G.getNodeMetadata(NId).getReductionState()) {
366 case NodeMetadata::Unprocessed: break;
367 case NodeMetadata::OptimallyReducible:
368 assert(OptimallyReducibleNodes.find(NId) !=
369 OptimallyReducibleNodes.end() &&
370 "Node not in optimally reducible set.");
371 OptimallyReducibleNodes.erase(NId);
373 case NodeMetadata::ConservativelyAllocatable:
374 assert(ConservativelyAllocatableNodes.find(NId) !=
375 ConservativelyAllocatableNodes.end() &&
376 "Node not in conservatively allocatable set.");
377 ConservativelyAllocatableNodes.erase(NId);
379 case NodeMetadata::NotProvablyAllocatable:
380 assert(NotProvablyAllocatableNodes.find(NId) !=
381 NotProvablyAllocatableNodes.end() &&
382 "Node not in not-provably-allocatable set.");
383 NotProvablyAllocatableNodes.erase(NId);
388 void moveToOptimallyReducibleNodes(NodeId NId) {
389 removeFromCurrentSet(NId);
390 OptimallyReducibleNodes.insert(NId);
391 G.getNodeMetadata(NId).setReductionState(
392 NodeMetadata::OptimallyReducible);
395 void moveToConservativelyAllocatableNodes(NodeId NId) {
396 removeFromCurrentSet(NId);
397 ConservativelyAllocatableNodes.insert(NId);
398 G.getNodeMetadata(NId).setReductionState(
399 NodeMetadata::ConservativelyAllocatable);
402 void moveToNotProvablyAllocatableNodes(NodeId NId) {
403 removeFromCurrentSet(NId);
404 NotProvablyAllocatableNodes.insert(NId);
405 G.getNodeMetadata(NId).setReductionState(
406 NodeMetadata::NotProvablyAllocatable);
411 for (auto NId : G.nodeIds()) {
412 if (G.getNodeDegree(NId) < 3)
413 moveToOptimallyReducibleNodes(NId);
414 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
415 moveToConservativelyAllocatableNodes(NId);
417 moveToNotProvablyAllocatableNodes(NId);
421 // Compute a reduction order for the graph by iteratively applying PBQP
422 // reduction rules. Locally optimal rules are applied whenever possible (R0,
423 // R1, R2). If no locally-optimal rules apply then any conservatively
424 // allocatable node is reduced. Finally, if no conservatively allocatable
425 // node exists then the node with the lowest spill-cost:degree ratio is
427 std::vector<GraphBase::NodeId> reduce() {
428 assert(!G.empty() && "Cannot reduce empty graph.");
430 typedef GraphBase::NodeId NodeId;
431 std::vector<NodeId> NodeStack;
433 // Consume worklists.
435 if (!OptimallyReducibleNodes.empty()) {
436 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
438 OptimallyReducibleNodes.erase(NItr);
439 NodeStack.push_back(NId);
440 switch (G.getNodeDegree(NId)) {
449 default: llvm_unreachable("Not an optimally reducible node.");
451 } else if (!ConservativelyAllocatableNodes.empty()) {
452 // Conservatively allocatable nodes will never spill. For now just
453 // take the first node in the set and push it on the stack. When we
454 // start optimizing more heavily for register preferencing, it may
455 // would be better to push nodes with lower 'expected' or worst-case
456 // register costs first (since early nodes are the most
458 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
460 ConservativelyAllocatableNodes.erase(NItr);
461 NodeStack.push_back(NId);
462 G.disconnectAllNeighborsFromNode(NId);
464 } else if (!NotProvablyAllocatableNodes.empty()) {
465 NodeSet::iterator NItr =
466 std::min_element(NotProvablyAllocatableNodes.begin(),
467 NotProvablyAllocatableNodes.end(),
468 SpillCostComparator(G));
470 NotProvablyAllocatableNodes.erase(NItr);
471 NodeStack.push_back(NId);
472 G.disconnectAllNeighborsFromNode(NId);
480 class SpillCostComparator {
482 SpillCostComparator(const Graph& G) : G(G) {}
483 bool operator()(NodeId N1Id, NodeId N2Id) {
484 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
485 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
493 typedef std::set<NodeId> NodeSet;
494 NodeSet OptimallyReducibleNodes;
495 NodeSet ConservativelyAllocatableNodes;
496 NodeSet NotProvablyAllocatableNodes;
499 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
501 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
503 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
506 inline Solution solve(PBQPRAGraph& G) {
509 RegAllocSolverImpl RegAllocSolver(G);
510 return RegAllocSolver.solve();
513 } // namespace RegAlloc
516 /// @brief Create a PBQP register allocator instance.
518 createPBQPRegisterAllocator(char *customPassID = nullptr);
522 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */