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"
32 /// @brief Spill option index.
33 inline unsigned getSpillOptionIdx() { return 0; }
35 /// \brief Metadata to speed allocatability test.
37 /// Keeps track of the number of infinities in each row and column.
38 class MatrixMetadata {
40 MatrixMetadata(const MatrixMetadata&);
41 void operator=(const MatrixMetadata&);
43 MatrixMetadata(const Matrix& M)
44 : WorstRow(0), WorstCol(0),
45 UnsafeRows(new bool[M.getRows() - 1]()),
46 UnsafeCols(new bool[M.getCols() - 1]()) {
48 unsigned* ColCounts = new unsigned[M.getCols() - 1]();
50 for (unsigned i = 1; i < M.getRows(); ++i) {
51 unsigned RowCount = 0;
52 for (unsigned j = 1; j < M.getCols(); ++j) {
53 if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
56 UnsafeRows[i - 1] = true;
57 UnsafeCols[j - 1] = true;
60 WorstRow = std::max(WorstRow, RowCount);
62 unsigned WorstColCountForCurRow =
63 *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
64 WorstCol = std::max(WorstCol, WorstColCountForCurRow);
68 unsigned getWorstRow() const { return WorstRow; }
69 unsigned getWorstCol() const { return WorstCol; }
70 const bool* getUnsafeRows() const { return UnsafeRows.get(); }
71 const bool* getUnsafeCols() const { return UnsafeCols.get(); }
74 unsigned WorstRow, WorstCol;
75 std::unique_ptr<bool[]> UnsafeRows;
76 std::unique_ptr<bool[]> UnsafeCols;
79 /// \brief Holds a vector of the allowed physical regs for a vreg.
80 class AllowedRegVector {
81 friend hash_code hash_value(const AllowedRegVector &);
84 AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
86 AllowedRegVector(const std::vector<unsigned> &OptVec)
87 : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
88 std::copy(OptVec.begin(), OptVec.end(), Opts.get());
91 AllowedRegVector(const AllowedRegVector &Other)
92 : NumOpts(Other.NumOpts), Opts(new unsigned[NumOpts]) {
93 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
96 AllowedRegVector(AllowedRegVector &&Other)
97 : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
99 AllowedRegVector& operator=(const AllowedRegVector &Other) {
100 NumOpts = Other.NumOpts;
101 Opts.reset(new unsigned[NumOpts]);
102 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
106 AllowedRegVector& operator=(AllowedRegVector &&Other) {
107 NumOpts = std::move(Other.NumOpts);
108 Opts = std::move(Other.Opts);
112 unsigned size() const { return NumOpts; }
113 unsigned operator[](size_t I) const { return Opts[I]; }
115 bool operator==(const AllowedRegVector &Other) const {
116 if (NumOpts != Other.NumOpts)
118 return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
121 bool operator!=(const AllowedRegVector &Other) const {
122 return !(*this == Other);
127 std::unique_ptr<unsigned[]> Opts;
130 inline hash_code hash_value(const AllowedRegVector &OptRegs) {
131 unsigned *OStart = OptRegs.Opts.get();
132 unsigned *OEnd = OptRegs.Opts.get() + OptRegs.NumOpts;
133 return hash_combine(OptRegs.NumOpts,
134 hash_combine_range(OStart, OEnd));
137 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
138 class GraphMetadata {
140 typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
143 typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
145 GraphMetadata(MachineFunction &MF,
147 MachineBlockFrequencyInfo &MBFI)
148 : MF(MF), LIS(LIS), MBFI(MBFI) {}
152 MachineBlockFrequencyInfo &MBFI;
154 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
155 VRegToNodeId[VReg] = NId;
158 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
159 auto VRegItr = VRegToNodeId.find(VReg);
160 if (VRegItr == VRegToNodeId.end())
161 return GraphBase::invalidNodeId();
162 return VRegItr->second;
165 void eraseNodeIdForVReg(unsigned VReg) {
166 VRegToNodeId.erase(VReg);
169 AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
170 return AllowedRegVecs.getValue(std::move(Allowed));
174 DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
175 AllowedRegVecPool AllowedRegVecs;
178 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
181 typedef RegAlloc::AllowedRegVector AllowedRegVector;
183 // The node's reduction state. The order in this enum is important,
184 // as it is assumed nodes can only progress up (i.e. towards being
185 // optimally reducible) when reducing the graph.
188 NotProvablyAllocatable,
189 ConservativelyAllocatable,
194 : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
197 , everConservativelyAllocatable(false)
201 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
202 // MSVC synthesizes move constructors properly.
203 NodeMetadata(const NodeMetadata &Other)
204 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
205 OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
206 AllowedRegs(Other.AllowedRegs) {
208 std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
213 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
214 // MSVC synthesizes move constructors properly.
215 NodeMetadata(NodeMetadata &&Other)
216 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
217 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
218 AllowedRegs(std::move(Other.AllowedRegs)) {}
220 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
221 // MSVC synthesizes move constructors properly.
222 NodeMetadata& operator=(const NodeMetadata &Other) {
224 NumOpts = Other.NumOpts;
225 DeniedOpts = Other.DeniedOpts;
226 OptUnsafeEdges.reset(new unsigned[NumOpts]);
227 std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
228 OptUnsafeEdges.get());
230 AllowedRegs = Other.AllowedRegs;
234 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
235 // MSVC synthesizes move constructors properly.
236 NodeMetadata& operator=(NodeMetadata &&Other) {
238 NumOpts = Other.NumOpts;
239 DeniedOpts = Other.DeniedOpts;
240 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
242 AllowedRegs = std::move(Other.AllowedRegs);
246 void setVReg(unsigned VReg) { this->VReg = VReg; }
247 unsigned getVReg() const { return VReg; }
249 void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
250 this->AllowedRegs = std::move(AllowedRegs);
252 const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
254 void setup(const Vector& Costs) {
255 NumOpts = Costs.getLength() - 1;
256 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
259 ReductionState getReductionState() const { return RS; }
260 void setReductionState(ReductionState RS) {
261 assert(RS >= this->RS && "A node's reduction state can not be downgraded");
265 // Remember this state to assert later that a non-infinite register
266 // option was available.
267 if (RS == ConservativelyAllocatable)
268 everConservativelyAllocatable = true;
273 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
274 DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
275 const bool* UnsafeOpts =
276 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
277 for (unsigned i = 0; i < NumOpts; ++i)
278 OptUnsafeEdges[i] += UnsafeOpts[i];
281 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
282 DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
283 const bool* UnsafeOpts =
284 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
285 for (unsigned i = 0; i < NumOpts; ++i)
286 OptUnsafeEdges[i] -= UnsafeOpts[i];
289 bool isConservativelyAllocatable() const {
290 return (DeniedOpts < NumOpts) ||
291 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
292 &OptUnsafeEdges[NumOpts]);
296 bool wasConservativelyAllocatable() const {
297 return everConservativelyAllocatable;
305 std::unique_ptr<unsigned[]> OptUnsafeEdges;
307 GraphMetadata::AllowedRegVecRef AllowedRegs;
310 bool everConservativelyAllocatable;
314 class RegAllocSolverImpl {
316 typedef MDMatrix<MatrixMetadata> RAMatrix;
318 typedef PBQP::Vector RawVector;
319 typedef PBQP::Matrix RawMatrix;
320 typedef PBQP::Vector Vector;
321 typedef RAMatrix Matrix;
322 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
324 typedef GraphBase::NodeId NodeId;
325 typedef GraphBase::EdgeId EdgeId;
327 typedef RegAlloc::NodeMetadata NodeMetadata;
328 struct EdgeMetadata { };
329 typedef RegAlloc::GraphMetadata GraphMetadata;
331 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
333 RegAllocSolverImpl(Graph &G) : G(G) {}
339 S = backpropagate(G, reduce());
344 void handleAddNode(NodeId NId) {
345 assert(G.getNodeCosts(NId).getLength() > 1 &&
346 "PBQP Graph should not contain single or zero-option nodes");
347 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
349 void handleRemoveNode(NodeId NId) {}
350 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
352 void handleAddEdge(EdgeId EId) {
353 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
354 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
357 void handleRemoveEdge(EdgeId EId) {
358 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
359 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
362 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
363 NodeMetadata& NMd = G.getNodeMetadata(NId);
364 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
365 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
369 void handleReconnectEdge(EdgeId EId, NodeId NId) {
370 NodeMetadata& NMd = G.getNodeMetadata(NId);
371 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
372 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
375 void handleUpdateCosts(EdgeId EId, const Matrix& NewCosts) {
376 NodeId N1Id = G.getEdgeNode1Id(EId);
377 NodeId N2Id = G.getEdgeNode2Id(EId);
378 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
379 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
380 bool Transpose = N1Id != G.getEdgeNode1Id(EId);
382 // Metadata are computed incrementally. First, update them
383 // by removing the old cost.
384 const MatrixMetadata& OldMMd = G.getEdgeCosts(EId).getMetadata();
385 N1Md.handleRemoveEdge(OldMMd, Transpose);
386 N2Md.handleRemoveEdge(OldMMd, !Transpose);
388 // And update now the metadata with the new cost.
389 const MatrixMetadata& MMd = NewCosts.getMetadata();
390 N1Md.handleAddEdge(MMd, Transpose);
391 N2Md.handleAddEdge(MMd, !Transpose);
393 // As the metadata may have changed with the update, the nodes may have
394 // become ConservativelyAllocatable or OptimallyReducible.
401 void promote(NodeId NId, NodeMetadata& NMd) {
402 if (G.getNodeDegree(NId) == 3) {
403 // This node is becoming optimally reducible.
404 moveToOptimallyReducibleNodes(NId);
405 } else if (NMd.getReductionState() ==
406 NodeMetadata::NotProvablyAllocatable &&
407 NMd.isConservativelyAllocatable()) {
408 // This node just became conservatively allocatable.
409 moveToConservativelyAllocatableNodes(NId);
413 void removeFromCurrentSet(NodeId NId) {
414 switch (G.getNodeMetadata(NId).getReductionState()) {
415 case NodeMetadata::Unprocessed: break;
416 case NodeMetadata::OptimallyReducible:
417 assert(OptimallyReducibleNodes.find(NId) !=
418 OptimallyReducibleNodes.end() &&
419 "Node not in optimally reducible set.");
420 OptimallyReducibleNodes.erase(NId);
422 case NodeMetadata::ConservativelyAllocatable:
423 assert(ConservativelyAllocatableNodes.find(NId) !=
424 ConservativelyAllocatableNodes.end() &&
425 "Node not in conservatively allocatable set.");
426 ConservativelyAllocatableNodes.erase(NId);
428 case NodeMetadata::NotProvablyAllocatable:
429 assert(NotProvablyAllocatableNodes.find(NId) !=
430 NotProvablyAllocatableNodes.end() &&
431 "Node not in not-provably-allocatable set.");
432 NotProvablyAllocatableNodes.erase(NId);
437 void moveToOptimallyReducibleNodes(NodeId NId) {
438 removeFromCurrentSet(NId);
439 OptimallyReducibleNodes.insert(NId);
440 G.getNodeMetadata(NId).setReductionState(
441 NodeMetadata::OptimallyReducible);
444 void moveToConservativelyAllocatableNodes(NodeId NId) {
445 removeFromCurrentSet(NId);
446 ConservativelyAllocatableNodes.insert(NId);
447 G.getNodeMetadata(NId).setReductionState(
448 NodeMetadata::ConservativelyAllocatable);
451 void moveToNotProvablyAllocatableNodes(NodeId NId) {
452 removeFromCurrentSet(NId);
453 NotProvablyAllocatableNodes.insert(NId);
454 G.getNodeMetadata(NId).setReductionState(
455 NodeMetadata::NotProvablyAllocatable);
460 for (auto NId : G.nodeIds()) {
461 if (G.getNodeDegree(NId) < 3)
462 moveToOptimallyReducibleNodes(NId);
463 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
464 moveToConservativelyAllocatableNodes(NId);
466 moveToNotProvablyAllocatableNodes(NId);
470 // Compute a reduction order for the graph by iteratively applying PBQP
471 // reduction rules. Locally optimal rules are applied whenever possible (R0,
472 // R1, R2). If no locally-optimal rules apply then any conservatively
473 // allocatable node is reduced. Finally, if no conservatively allocatable
474 // node exists then the node with the lowest spill-cost:degree ratio is
476 std::vector<GraphBase::NodeId> reduce() {
477 assert(!G.empty() && "Cannot reduce empty graph.");
479 typedef GraphBase::NodeId NodeId;
480 std::vector<NodeId> NodeStack;
482 // Consume worklists.
484 if (!OptimallyReducibleNodes.empty()) {
485 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
487 OptimallyReducibleNodes.erase(NItr);
488 NodeStack.push_back(NId);
489 switch (G.getNodeDegree(NId)) {
498 default: llvm_unreachable("Not an optimally reducible node.");
500 } else if (!ConservativelyAllocatableNodes.empty()) {
501 // Conservatively allocatable nodes will never spill. For now just
502 // take the first node in the set and push it on the stack. When we
503 // start optimizing more heavily for register preferencing, it may
504 // would be better to push nodes with lower 'expected' or worst-case
505 // register costs first (since early nodes are the most
507 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
509 ConservativelyAllocatableNodes.erase(NItr);
510 NodeStack.push_back(NId);
511 G.disconnectAllNeighborsFromNode(NId);
513 } else if (!NotProvablyAllocatableNodes.empty()) {
514 NodeSet::iterator NItr =
515 std::min_element(NotProvablyAllocatableNodes.begin(),
516 NotProvablyAllocatableNodes.end(),
517 SpillCostComparator(G));
519 NotProvablyAllocatableNodes.erase(NItr);
520 NodeStack.push_back(NId);
521 G.disconnectAllNeighborsFromNode(NId);
529 class SpillCostComparator {
531 SpillCostComparator(const Graph& G) : G(G) {}
532 bool operator()(NodeId N1Id, NodeId N2Id) {
533 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
534 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
542 typedef std::set<NodeId> NodeSet;
543 NodeSet OptimallyReducibleNodes;
544 NodeSet ConservativelyAllocatableNodes;
545 NodeSet NotProvablyAllocatableNodes;
548 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
550 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
552 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
554 /// @brief Dump this graph to dbgs().
557 /// @brief Dump this graph to an output stream.
558 /// @param OS Output stream to print on.
559 void dump(raw_ostream &OS) const;
561 /// @brief Print a representation of this graph in DOT format.
562 /// @param OS Output stream to print on.
563 void printDot(raw_ostream &OS) const;
566 inline Solution solve(PBQPRAGraph& G) {
569 RegAllocSolverImpl RegAllocSolver(G);
570 return RegAllocSolver.solve();
573 } // namespace RegAlloc
576 /// @brief Create a PBQP register allocator instance.
578 createPBQPRegisterAllocator(char *customPassID = nullptr);
582 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */