[PBQP Regalloc] Pre-spill vregs that have no legal physregs.
[oota-llvm.git] / include / llvm / CodeGen / RegAllocPBQP.h
1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
12 // interface.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
18
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"
24
25 namespace llvm {
26 namespace PBQP {
27 namespace RegAlloc {
28
29 /// @brief Spill option index.
30 inline unsigned getSpillOptionIdx() { return 0; }
31
32 /// \brief Metadata to speed allocatability test.
33 ///
34 /// Keeps track of the number of infinities in each row and column.
35 class MatrixMetadata {
36 private:
37   MatrixMetadata(const MatrixMetadata&);
38   void operator=(const MatrixMetadata&);
39 public:
40   MatrixMetadata(const Matrix& M)
41     : WorstRow(0), WorstCol(0),
42       UnsafeRows(new bool[M.getRows() - 1]()),
43       UnsafeCols(new bool[M.getCols() - 1]()) {
44
45     unsigned* ColCounts = new unsigned[M.getCols() - 1]();
46
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()) {
51           ++RowCount;
52           ++ColCounts[j - 1];
53           UnsafeRows[i - 1] = true;
54           UnsafeCols[j - 1] = true;
55         }
56       }
57       WorstRow = std::max(WorstRow, RowCount);
58     }
59     unsigned WorstColCountForCurRow =
60       *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
61     WorstCol = std::max(WorstCol, WorstColCountForCurRow);
62     delete[] ColCounts;
63   }
64
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(); }
69
70 private:
71   unsigned WorstRow, WorstCol;
72   std::unique_ptr<bool[]> UnsafeRows;
73   std::unique_ptr<bool[]> UnsafeCols;
74 };
75
76 /// \brief Holds a vector of the allowed physical regs for a vreg.
77 class AllowedRegVector {
78   friend hash_code hash_value(const AllowedRegVector &);
79 public:
80
81   AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
82
83   AllowedRegVector(const std::vector<unsigned> &OptVec)
84     : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
85     std::copy(OptVec.begin(), OptVec.end(), Opts.get());
86   }
87
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());
91   }
92
93   AllowedRegVector(AllowedRegVector &&Other)
94     : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
95
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());
100     return *this;
101   }
102
103   AllowedRegVector& operator=(AllowedRegVector &&Other) {
104     NumOpts = std::move(Other.NumOpts);
105     Opts = std::move(Other.Opts);
106     return *this;
107   }
108
109   unsigned size() const { return NumOpts; }
110   unsigned operator[](size_t I) const { return Opts[I]; }
111
112   bool operator==(const AllowedRegVector &Other) const {
113     if (NumOpts != Other.NumOpts)
114       return false;
115     return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
116   }
117
118   bool operator!=(const AllowedRegVector &Other) const {
119     return !(*this == Other);
120   }
121
122 private:
123   unsigned NumOpts;
124   std::unique_ptr<unsigned[]> Opts;
125 };
126
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));
132 }
133
134 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
135 class GraphMetadata {
136 private:
137   typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
138 public:
139
140   typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
141
142   GraphMetadata(MachineFunction &MF,
143                 LiveIntervals &LIS,
144                 MachineBlockFrequencyInfo &MBFI)
145     : MF(MF), LIS(LIS), MBFI(MBFI) {}
146
147   MachineFunction &MF;
148   LiveIntervals &LIS;
149   MachineBlockFrequencyInfo &MBFI;
150
151   void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
152     VRegToNodeId[VReg] = NId;
153   }
154
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;
160   }
161
162   void eraseNodeIdForVReg(unsigned VReg) {
163     VRegToNodeId.erase(VReg);
164   }
165
166   AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
167     return AllowedRegVecs.getValue(std::move(Allowed));
168   }
169
170 private:
171   DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
172   AllowedRegVecPool AllowedRegVecs;
173 };
174
175 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
176 class NodeMetadata {
177 public:
178   typedef RegAlloc::AllowedRegVector AllowedRegVector;
179
180   typedef enum { Unprocessed,
181                  OptimallyReducible,
182                  ConservativelyAllocatable,
183                  NotProvablyAllocatable } ReductionState;
184
185   NodeMetadata()
186     : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
187       VReg(0) {}
188
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) {
195     if (NumOpts > 0) {
196       std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
197                 &OptUnsafeEdges[0]);
198     }
199   }
200
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)) {}
207
208   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
209   // MSVC synthesizes move constructors properly.
210   NodeMetadata& operator=(const NodeMetadata &Other) {
211     RS = Other.RS;
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());
217     VReg = Other.VReg;
218     AllowedRegs = Other.AllowedRegs;
219     return *this;
220   }
221
222   // FIXME: Re-implementing default behavior to work around MSVC. Remove once
223   // MSVC synthesizes move constructors properly.
224   NodeMetadata& operator=(NodeMetadata &&Other) {
225     RS = Other.RS;
226     NumOpts = Other.NumOpts;
227     DeniedOpts = Other.DeniedOpts;
228     OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
229     VReg = Other.VReg;
230     AllowedRegs = std::move(Other.AllowedRegs);
231     return *this;
232   }
233
234   void setVReg(unsigned VReg) { this->VReg = VReg; }
235   unsigned getVReg() const { return VReg; }
236
237   void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
238     this->AllowedRegs = std::move(AllowedRegs);
239   }
240   const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
241
242   void setup(const Vector& Costs) {
243     NumOpts = Costs.getLength() - 1;
244     OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
245   }
246
247   ReductionState getReductionState() const { return RS; }
248   void setReductionState(ReductionState RS) { this->RS = RS; }
249
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];
256   }
257
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];
264   }
265
266   bool isConservativelyAllocatable() const {
267     return (DeniedOpts < NumOpts) ||
268       (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
269        &OptUnsafeEdges[NumOpts]);
270   }
271
272 private:
273   ReductionState RS;
274   unsigned NumOpts;
275   unsigned DeniedOpts;
276   std::unique_ptr<unsigned[]> OptUnsafeEdges;
277   unsigned VReg;
278   GraphMetadata::AllowedRegVecRef AllowedRegs;
279 };
280
281 class RegAllocSolverImpl {
282 private:
283   typedef MDMatrix<MatrixMetadata> RAMatrix;
284 public:
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;
290
291   typedef GraphBase::NodeId NodeId;
292   typedef GraphBase::EdgeId EdgeId;
293
294   typedef RegAlloc::NodeMetadata NodeMetadata;
295   struct EdgeMetadata { };
296   typedef RegAlloc::GraphMetadata GraphMetadata;
297
298   typedef PBQP::Graph<RegAllocSolverImpl> Graph;
299
300   RegAllocSolverImpl(Graph &G) : G(G) {}
301
302   Solution solve() {
303     G.setSolver(*this);
304     Solution S;
305     setup();
306     S = backpropagate(G, reduce());
307     G.unsetSolver();
308     return S;
309   }
310
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));
315   }
316   void handleRemoveNode(NodeId NId) {}
317   void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
318
319   void handleAddEdge(EdgeId EId) {
320     handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
321     handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
322   }
323
324   void handleRemoveEdge(EdgeId EId) {
325     handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
326     handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
327   }
328
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);
341     }
342   }
343
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));
348   }
349
350   void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
351     handleRemoveEdge(EId);
352
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));
360   }
361
362 private:
363
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);
372       break;
373     case NodeMetadata::ConservativelyAllocatable:
374       assert(ConservativelyAllocatableNodes.find(NId) !=
375              ConservativelyAllocatableNodes.end() &&
376              "Node not in conservatively allocatable set.");
377       ConservativelyAllocatableNodes.erase(NId);
378       break;
379     case NodeMetadata::NotProvablyAllocatable:
380       assert(NotProvablyAllocatableNodes.find(NId) !=
381              NotProvablyAllocatableNodes.end() &&
382              "Node not in not-provably-allocatable set.");
383       NotProvablyAllocatableNodes.erase(NId);
384       break;
385     }
386   }
387
388   void moveToOptimallyReducibleNodes(NodeId NId) {
389     removeFromCurrentSet(NId);
390     OptimallyReducibleNodes.insert(NId);
391     G.getNodeMetadata(NId).setReductionState(
392       NodeMetadata::OptimallyReducible);
393   }
394
395   void moveToConservativelyAllocatableNodes(NodeId NId) {
396     removeFromCurrentSet(NId);
397     ConservativelyAllocatableNodes.insert(NId);
398     G.getNodeMetadata(NId).setReductionState(
399       NodeMetadata::ConservativelyAllocatable);
400   }
401
402   void moveToNotProvablyAllocatableNodes(NodeId NId) {
403     removeFromCurrentSet(NId);
404     NotProvablyAllocatableNodes.insert(NId);
405     G.getNodeMetadata(NId).setReductionState(
406       NodeMetadata::NotProvablyAllocatable);
407   }
408
409   void setup() {
410     // Set up worklists.
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);
416       else
417         moveToNotProvablyAllocatableNodes(NId);
418     }
419   }
420
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
426   // selected.
427   std::vector<GraphBase::NodeId> reduce() {
428     assert(!G.empty() && "Cannot reduce empty graph.");
429
430     typedef GraphBase::NodeId NodeId;
431     std::vector<NodeId> NodeStack;
432
433     // Consume worklists.
434     while (true) {
435       if (!OptimallyReducibleNodes.empty()) {
436         NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
437         NodeId NId = *NItr;
438         OptimallyReducibleNodes.erase(NItr);
439         NodeStack.push_back(NId);
440         switch (G.getNodeDegree(NId)) {
441         case 0:
442           break;
443         case 1:
444           applyR1(G, NId);
445           break;
446         case 2:
447           applyR2(G, NId);
448           break;
449         default: llvm_unreachable("Not an optimally reducible node.");
450         }
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
457         // constrained).
458         NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
459         NodeId NId = *NItr;
460         ConservativelyAllocatableNodes.erase(NItr);
461         NodeStack.push_back(NId);
462         G.disconnectAllNeighborsFromNode(NId);
463
464       } else if (!NotProvablyAllocatableNodes.empty()) {
465         NodeSet::iterator NItr =
466           std::min_element(NotProvablyAllocatableNodes.begin(),
467                            NotProvablyAllocatableNodes.end(),
468                            SpillCostComparator(G));
469         NodeId NId = *NItr;
470         NotProvablyAllocatableNodes.erase(NItr);
471         NodeStack.push_back(NId);
472         G.disconnectAllNeighborsFromNode(NId);
473       } else
474         break;
475     }
476
477     return NodeStack;
478   }
479
480   class SpillCostComparator {
481   public:
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);
486       return N1SC < N2SC;
487     }
488   private:
489     const Graph& G;
490   };
491
492   Graph& G;
493   typedef std::set<NodeId> NodeSet;
494   NodeSet OptimallyReducibleNodes;
495   NodeSet ConservativelyAllocatableNodes;
496   NodeSet NotProvablyAllocatableNodes;
497 };
498
499 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
500 private:
501   typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
502 public:
503   PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
504 };
505
506 inline Solution solve(PBQPRAGraph& G) {
507   if (G.empty())
508     return Solution();
509   RegAllocSolverImpl RegAllocSolver(G);
510   return RegAllocSolver.solve();
511 }
512
513 } // namespace RegAlloc
514 } // namespace PBQP
515
516 /// @brief Create a PBQP register allocator instance.
517 FunctionPass *
518 createPBQPRegisterAllocator(char *customPassID = nullptr);
519
520 } // namespace llvm
521
522 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */