[PBQP] Replace PBQPBuilder with composable constraints (PBQPRAConstraint).
[oota-llvm.git] / include / llvm / CodeGen / PBQP / Graph.h
1 //===-------------------- Graph.h - PBQP Graph ------------------*- 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 // PBQP Graph class.
11 //
12 //===----------------------------------------------------------------------===//
13
14
15 #ifndef LLVM_CODEGEN_PBQP_GRAPH_H
16 #define LLVM_CODEGEN_PBQP_GRAPH_H
17
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/Debug.h"
21 #include <list>
22 #include <map>
23 #include <set>
24
25 namespace llvm {
26 namespace PBQP {
27
28   class GraphBase {
29   public:
30     typedef unsigned NodeId;
31     typedef unsigned EdgeId;
32
33     /// @brief Returns a value representing an invalid (non-existent) node.
34     static NodeId invalidNodeId() {
35       return std::numeric_limits<NodeId>::max();
36     }
37
38     /// @brief Returns a value representing an invalid (non-existent) edge.
39     static EdgeId invalidEdgeId() {
40       return std::numeric_limits<EdgeId>::max();
41     }
42   };
43
44   /// PBQP Graph class.
45   /// Instances of this class describe PBQP problems.
46   ///
47   template <typename SolverT>
48   class Graph : public GraphBase {
49   private:
50     typedef typename SolverT::CostAllocator CostAllocator;
51   public:
52     typedef typename SolverT::RawVector RawVector;
53     typedef typename SolverT::RawMatrix RawMatrix;
54     typedef typename SolverT::Vector Vector;
55     typedef typename SolverT::Matrix Matrix;
56     typedef typename CostAllocator::VectorPtr VectorPtr;
57     typedef typename CostAllocator::MatrixPtr MatrixPtr;
58     typedef typename SolverT::NodeMetadata NodeMetadata;
59     typedef typename SolverT::EdgeMetadata EdgeMetadata;
60     typedef typename SolverT::GraphMetadata GraphMetadata;
61
62   private:
63
64     class NodeEntry {
65     public:
66       typedef std::vector<EdgeId> AdjEdgeList;
67       typedef AdjEdgeList::size_type AdjEdgeIdx;
68       typedef AdjEdgeList::const_iterator AdjEdgeItr;
69
70       static AdjEdgeIdx getInvalidAdjEdgeIdx() {
71         return std::numeric_limits<AdjEdgeIdx>::max();
72       }
73
74       NodeEntry(VectorPtr Costs) : Costs(Costs) {}
75
76       AdjEdgeIdx addAdjEdgeId(EdgeId EId) {
77         AdjEdgeIdx Idx = AdjEdgeIds.size();
78         AdjEdgeIds.push_back(EId);
79         return Idx;
80       }
81
82       void removeAdjEdgeId(Graph &G, NodeId ThisNId, AdjEdgeIdx Idx) {
83         // Swap-and-pop for fast removal.
84         //   1) Update the adj index of the edge currently at back().
85         //   2) Move last Edge down to Idx.
86         //   3) pop_back()
87         // If Idx == size() - 1 then the setAdjEdgeIdx and swap are
88         // redundant, but both operations are cheap.
89         G.getEdge(AdjEdgeIds.back()).setAdjEdgeIdx(ThisNId, Idx);
90         AdjEdgeIds[Idx] = AdjEdgeIds.back();
91         AdjEdgeIds.pop_back();
92       }
93
94       const AdjEdgeList& getAdjEdgeIds() const { return AdjEdgeIds; }
95
96       VectorPtr Costs;
97       NodeMetadata Metadata;
98     private:
99       AdjEdgeList AdjEdgeIds;
100     };
101
102     class EdgeEntry {
103     public:
104       EdgeEntry(NodeId N1Id, NodeId N2Id, MatrixPtr Costs)
105         : Costs(Costs) {
106         NIds[0] = N1Id;
107         NIds[1] = N2Id;
108         ThisEdgeAdjIdxs[0] = NodeEntry::getInvalidAdjEdgeIdx();
109         ThisEdgeAdjIdxs[1] = NodeEntry::getInvalidAdjEdgeIdx();
110       }
111
112       void invalidate() {
113         NIds[0] = NIds[1] = Graph::invalidNodeId();
114         ThisEdgeAdjIdxs[0] = ThisEdgeAdjIdxs[1] =
115           NodeEntry::getInvalidAdjEdgeIdx();
116         Costs = nullptr;
117       }
118
119       void connectToN(Graph &G, EdgeId ThisEdgeId, unsigned NIdx) {
120         assert(ThisEdgeAdjIdxs[NIdx] == NodeEntry::getInvalidAdjEdgeIdx() &&
121                "Edge already connected to NIds[NIdx].");
122         NodeEntry &N = G.getNode(NIds[NIdx]);
123         ThisEdgeAdjIdxs[NIdx] = N.addAdjEdgeId(ThisEdgeId);
124       }
125
126       void connectTo(Graph &G, EdgeId ThisEdgeId, NodeId NId) {
127         if (NId == NIds[0])
128           connectToN(G, ThisEdgeId, 0);
129         else {
130           assert(NId == NIds[1] && "Edge does not connect NId.");
131           connectToN(G, ThisEdgeId, 1);
132         }
133       }
134
135       void connect(Graph &G, EdgeId ThisEdgeId) {
136         connectToN(G, ThisEdgeId, 0);
137         connectToN(G, ThisEdgeId, 1);
138       }
139
140       void setAdjEdgeIdx(NodeId NId, typename NodeEntry::AdjEdgeIdx NewIdx) {
141         if (NId == NIds[0])
142           ThisEdgeAdjIdxs[0] = NewIdx;
143         else {
144           assert(NId == NIds[1] && "Edge not connected to NId");
145           ThisEdgeAdjIdxs[1] = NewIdx;
146         }
147       }
148
149       void disconnectFromN(Graph &G, unsigned NIdx) {
150         assert(ThisEdgeAdjIdxs[NIdx] != NodeEntry::getInvalidAdjEdgeIdx() &&
151                "Edge not connected to NIds[NIdx].");
152         NodeEntry &N = G.getNode(NIds[NIdx]);
153         N.removeAdjEdgeId(G, NIds[NIdx], ThisEdgeAdjIdxs[NIdx]);
154         ThisEdgeAdjIdxs[NIdx] = NodeEntry::getInvalidAdjEdgeIdx();
155       }
156
157       void disconnectFrom(Graph &G, NodeId NId) {
158         if (NId == NIds[0])
159           disconnectFromN(G, 0);
160         else {
161           assert(NId == NIds[1] && "Edge does not connect NId");
162           disconnectFromN(G, 1);
163         }
164       }
165
166       NodeId getN1Id() const { return NIds[0]; }
167       NodeId getN2Id() const { return NIds[1]; }
168       MatrixPtr Costs;
169       EdgeMetadata Metadata;
170     private:
171       NodeId NIds[2];
172       typename NodeEntry::AdjEdgeIdx ThisEdgeAdjIdxs[2];
173     };
174
175     // ----- MEMBERS -----
176
177     GraphMetadata Metadata;
178     CostAllocator CostAlloc;
179     SolverT *Solver;
180
181     typedef std::vector<NodeEntry> NodeVector;
182     typedef std::vector<NodeId> FreeNodeVector;
183     NodeVector Nodes;
184     FreeNodeVector FreeNodeIds;
185
186     typedef std::vector<EdgeEntry> EdgeVector;
187     typedef std::vector<EdgeId> FreeEdgeVector;
188     EdgeVector Edges;
189     FreeEdgeVector FreeEdgeIds;
190
191     // ----- INTERNAL METHODS -----
192
193     NodeEntry& getNode(NodeId NId) { return Nodes[NId]; }
194     const NodeEntry& getNode(NodeId NId) const { return Nodes[NId]; }
195
196     EdgeEntry& getEdge(EdgeId EId) { return Edges[EId]; }
197     const EdgeEntry& getEdge(EdgeId EId) const { return Edges[EId]; }
198
199     NodeId addConstructedNode(NodeEntry N) {
200       NodeId NId = 0;
201       if (!FreeNodeIds.empty()) {
202         NId = FreeNodeIds.back();
203         FreeNodeIds.pop_back();
204         Nodes[NId] = std::move(N);
205       } else {
206         NId = Nodes.size();
207         Nodes.push_back(std::move(N));
208       }
209       return NId;
210     }
211
212     EdgeId addConstructedEdge(EdgeEntry E) {
213       assert(findEdge(E.getN1Id(), E.getN2Id()) == invalidEdgeId() &&
214              "Attempt to add duplicate edge.");
215       EdgeId EId = 0;
216       if (!FreeEdgeIds.empty()) {
217         EId = FreeEdgeIds.back();
218         FreeEdgeIds.pop_back();
219         Edges[EId] = std::move(E);
220       } else {
221         EId = Edges.size();
222         Edges.push_back(std::move(E));
223       }
224
225       EdgeEntry &NE = getEdge(EId);
226
227       // Add the edge to the adjacency sets of its nodes.
228       NE.connect(*this, EId);
229       return EId;
230     }
231
232     Graph(const Graph &Other) {}
233     void operator=(const Graph &Other) {}
234
235   public:
236
237     typedef typename NodeEntry::AdjEdgeItr AdjEdgeItr;
238
239     class NodeItr {
240     public:
241       typedef std::forward_iterator_tag iterator_category;
242       typedef NodeId value_type;
243       typedef int difference_type;
244       typedef NodeId* pointer;
245       typedef NodeId& reference;
246
247       NodeItr(NodeId CurNId, const Graph &G)
248         : CurNId(CurNId), EndNId(G.Nodes.size()), FreeNodeIds(G.FreeNodeIds) {
249         this->CurNId = findNextInUse(CurNId); // Move to first in-use node id
250       }
251
252       bool operator==(const NodeItr &O) const { return CurNId == O.CurNId; }
253       bool operator!=(const NodeItr &O) const { return !(*this == O); }
254       NodeItr& operator++() { CurNId = findNextInUse(++CurNId); return *this; }
255       NodeId operator*() const { return CurNId; }
256
257     private:
258       NodeId findNextInUse(NodeId NId) const {
259         while (NId < EndNId &&
260                std::find(FreeNodeIds.begin(), FreeNodeIds.end(), NId) !=
261                FreeNodeIds.end()) {
262           ++NId;
263         }
264         return NId;
265       }
266
267       NodeId CurNId, EndNId;
268       const FreeNodeVector &FreeNodeIds;
269     };
270
271     class EdgeItr {
272     public:
273       EdgeItr(EdgeId CurEId, const Graph &G)
274         : CurEId(CurEId), EndEId(G.Edges.size()), FreeEdgeIds(G.FreeEdgeIds) {
275         this->CurEId = findNextInUse(CurEId); // Move to first in-use edge id
276       }
277
278       bool operator==(const EdgeItr &O) const { return CurEId == O.CurEId; }
279       bool operator!=(const EdgeItr &O) const { return !(*this == O); }
280       EdgeItr& operator++() { CurEId = findNextInUse(++CurEId); return *this; }
281       EdgeId operator*() const { return CurEId; }
282
283     private:
284       EdgeId findNextInUse(EdgeId EId) const {
285         while (EId < EndEId &&
286                std::find(FreeEdgeIds.begin(), FreeEdgeIds.end(), EId) !=
287                FreeEdgeIds.end()) {
288           ++EId;
289         }
290         return EId;
291       }
292
293       EdgeId CurEId, EndEId;
294       const FreeEdgeVector &FreeEdgeIds;
295     };
296
297     class NodeIdSet {
298     public:
299       NodeIdSet(const Graph &G) : G(G) { }
300       NodeItr begin() const { return NodeItr(0, G); }
301       NodeItr end() const { return NodeItr(G.Nodes.size(), G); }
302       bool empty() const { return G.Nodes.empty(); }
303       typename NodeVector::size_type size() const {
304         return G.Nodes.size() - G.FreeNodeIds.size();
305       }
306     private:
307       const Graph& G;
308     };
309
310     class EdgeIdSet {
311     public:
312       EdgeIdSet(const Graph &G) : G(G) { }
313       EdgeItr begin() const { return EdgeItr(0, G); }
314       EdgeItr end() const { return EdgeItr(G.Edges.size(), G); }
315       bool empty() const { return G.Edges.empty(); }
316       typename NodeVector::size_type size() const {
317         return G.Edges.size() - G.FreeEdgeIds.size();
318       }
319     private:
320       const Graph& G;
321     };
322
323     class AdjEdgeIdSet {
324     public:
325       AdjEdgeIdSet(const NodeEntry &NE) : NE(NE) { }
326       typename NodeEntry::AdjEdgeItr begin() const {
327         return NE.getAdjEdgeIds().begin();
328       }
329       typename NodeEntry::AdjEdgeItr end() const {
330         return NE.getAdjEdgeIds().end();
331       }
332       bool empty() const { return NE.getAdjEdgeIds().empty(); }
333       typename NodeEntry::AdjEdgeList::size_type size() const {
334         return NE.getAdjEdgeIds().size();
335       }
336     private:
337       const NodeEntry &NE;
338     };
339
340     /// @brief Construct an empty PBQP graph.
341     Graph() : Solver(nullptr) {}
342
343     /// @brief Construct an empty PBQP graph with the given graph metadata.
344     Graph(GraphMetadata Metadata) : Metadata(Metadata), Solver(nullptr) {}
345
346     /// @brief Get a reference to the graph metadata.
347     GraphMetadata& getMetadata() { return Metadata; }
348
349     /// @brief Get a const-reference to the graph metadata.
350     const GraphMetadata& getMetadata() const { return Metadata; }
351
352     /// @brief Lock this graph to the given solver instance in preparation
353     /// for running the solver. This method will call solver.handleAddNode for
354     /// each node in the graph, and handleAddEdge for each edge, to give the
355     /// solver an opportunity to set up any requried metadata.
356     void setSolver(SolverT &S) {
357       assert(!Solver && "Solver already set. Call unsetSolver().");
358       Solver = &S;
359       for (auto NId : nodeIds())
360         Solver->handleAddNode(NId);
361       for (auto EId : edgeIds())
362         Solver->handleAddEdge(EId);
363     }
364
365     /// @brief Release from solver instance.
366     void unsetSolver() {
367       assert(Solver && "Solver not set.");
368       Solver = nullptr;
369     }
370
371     /// @brief Add a node with the given costs.
372     /// @param Costs Cost vector for the new node.
373     /// @return Node iterator for the added node.
374     template <typename OtherVectorT>
375     NodeId addNode(OtherVectorT Costs) {
376       // Get cost vector from the problem domain
377       VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs));
378       NodeId NId = addConstructedNode(NodeEntry(AllocatedCosts));
379       if (Solver)
380         Solver->handleAddNode(NId);
381       return NId;
382     }
383
384     /// @brief Add an edge between the given nodes with the given costs.
385     /// @param N1Id First node.
386     /// @param N2Id Second node.
387     /// @return Edge iterator for the added edge.
388     template <typename OtherVectorT>
389     EdgeId addEdge(NodeId N1Id, NodeId N2Id, OtherVectorT Costs) {
390       assert(getNodeCosts(N1Id).getLength() == Costs.getRows() &&
391              getNodeCosts(N2Id).getLength() == Costs.getCols() &&
392              "Matrix dimensions mismatch.");
393       // Get cost matrix from the problem domain.
394       MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs));
395       EdgeId EId = addConstructedEdge(EdgeEntry(N1Id, N2Id, AllocatedCosts));
396       if (Solver)
397         Solver->handleAddEdge(EId);
398       return EId;
399     }
400
401     /// @brief Returns true if the graph is empty.
402     bool empty() const { return NodeIdSet(*this).empty(); }
403
404     NodeIdSet nodeIds() const { return NodeIdSet(*this); }
405     EdgeIdSet edgeIds() const { return EdgeIdSet(*this); }
406
407     AdjEdgeIdSet adjEdgeIds(NodeId NId) { return AdjEdgeIdSet(getNode(NId)); }
408
409     /// @brief Get the number of nodes in the graph.
410     /// @return Number of nodes in the graph.
411     unsigned getNumNodes() const { return NodeIdSet(*this).size(); }
412
413     /// @brief Get the number of edges in the graph.
414     /// @return Number of edges in the graph.
415     unsigned getNumEdges() const { return EdgeIdSet(*this).size(); }
416
417     /// @brief Set a node's cost vector.
418     /// @param NId Node to update.
419     /// @param Costs New costs to set.
420     template <typename OtherVectorT>
421     void setNodeCosts(NodeId NId, OtherVectorT Costs) {
422       VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs));
423       if (Solver)
424         Solver->handleSetNodeCosts(NId, *AllocatedCosts);
425       getNode(NId).Costs = AllocatedCosts;
426     }
427
428     /// @brief Get a node's cost vector (const version).
429     /// @param NId Node id.
430     /// @return Node cost vector.
431     const Vector& getNodeCosts(NodeId NId) const { return *getNode(NId).Costs; }
432
433     NodeMetadata& getNodeMetadata(NodeId NId) {
434       return getNode(NId).Metadata;
435     }
436
437     const NodeMetadata& getNodeMetadata(NodeId NId) const {
438       return getNode(NId).Metadata;
439     }
440
441     typename NodeEntry::AdjEdgeList::size_type getNodeDegree(NodeId NId) const {
442       return getNode(NId).getAdjEdgeIds().size();
443     }
444
445     /// @brief Set an edge's cost matrix.
446     /// @param EId Edge id.
447     /// @param Costs New cost matrix.
448     template <typename OtherMatrixT>
449     void setEdgeCosts(EdgeId EId, OtherMatrixT Costs) {
450       MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs));
451       if (Solver)
452         Solver->handleSetEdgeCosts(EId, *AllocatedCosts);
453       getEdge(EId).Costs = AllocatedCosts;
454     }
455
456     /// @brief Get an edge's cost matrix (const version).
457     /// @param EId Edge id.
458     /// @return Edge cost matrix.
459     const Matrix& getEdgeCosts(EdgeId EId) const {
460       return *getEdge(EId).Costs;
461     }
462
463     EdgeMetadata& getEdgeMetadata(EdgeId NId) {
464       return getEdge(NId).Metadata;
465     }
466
467     const EdgeMetadata& getEdgeMetadata(EdgeId NId) const {
468       return getEdge(NId).Metadata;
469     }
470
471     /// @brief Get the first node connected to this edge.
472     /// @param EId Edge id.
473     /// @return The first node connected to the given edge.
474     NodeId getEdgeNode1Id(EdgeId EId) {
475       return getEdge(EId).getN1Id();
476     }
477
478     /// @brief Get the second node connected to this edge.
479     /// @param EId Edge id.
480     /// @return The second node connected to the given edge.
481     NodeId getEdgeNode2Id(EdgeId EId) {
482       return getEdge(EId).getN2Id();
483     }
484
485     /// @brief Get the "other" node connected to this edge.
486     /// @param EId Edge id.
487     /// @param NId Node id for the "given" node.
488     /// @return The iterator for the "other" node connected to this edge.
489     NodeId getEdgeOtherNodeId(EdgeId EId, NodeId NId) {
490       EdgeEntry &E = getEdge(EId);
491       if (E.getN1Id() == NId) {
492         return E.getN2Id();
493       } // else
494       return E.getN1Id();
495     }
496
497     /// @brief Get the edge connecting two nodes.
498     /// @param N1Id First node id.
499     /// @param N2Id Second node id.
500     /// @return An id for edge (N1Id, N2Id) if such an edge exists,
501     ///         otherwise returns an invalid edge id.
502     EdgeId findEdge(NodeId N1Id, NodeId N2Id) {
503       for (auto AEId : adjEdgeIds(N1Id)) {
504         if ((getEdgeNode1Id(AEId) == N2Id) ||
505             (getEdgeNode2Id(AEId) == N2Id)) {
506           return AEId;
507         }
508       }
509       return invalidEdgeId();
510     }
511
512     /// @brief Remove a node from the graph.
513     /// @param NId Node id.
514     void removeNode(NodeId NId) {
515       if (Solver)
516         Solver->handleRemoveNode(NId);
517       NodeEntry &N = getNode(NId);
518       // TODO: Can this be for-each'd?
519       for (AdjEdgeItr AEItr = N.adjEdgesBegin(),
520              AEEnd = N.adjEdgesEnd();
521            AEItr != AEEnd;) {
522         EdgeId EId = *AEItr;
523         ++AEItr;
524         removeEdge(EId);
525       }
526       FreeNodeIds.push_back(NId);
527     }
528
529     /// @brief Disconnect an edge from the given node.
530     ///
531     /// Removes the given edge from the adjacency list of the given node.
532     /// This operation leaves the edge in an 'asymmetric' state: It will no
533     /// longer appear in an iteration over the given node's (NId's) edges, but
534     /// will appear in an iteration over the 'other', unnamed node's edges.
535     ///
536     /// This does not correspond to any normal graph operation, but exists to
537     /// support efficient PBQP graph-reduction based solvers. It is used to
538     /// 'effectively' remove the unnamed node from the graph while the solver
539     /// is performing the reduction. The solver will later call reconnectNode
540     /// to restore the edge in the named node's adjacency list.
541     ///
542     /// Since the degree of a node is the number of connected edges,
543     /// disconnecting an edge from a node 'u' will cause the degree of 'u' to
544     /// drop by 1.
545     ///
546     /// A disconnected edge WILL still appear in an iteration over the graph
547     /// edges.
548     ///
549     /// A disconnected edge should not be removed from the graph, it should be
550     /// reconnected first.
551     ///
552     /// A disconnected edge can be reconnected by calling the reconnectEdge
553     /// method.
554     void disconnectEdge(EdgeId EId, NodeId NId) {
555       if (Solver)
556         Solver->handleDisconnectEdge(EId, NId);
557
558       EdgeEntry &E = getEdge(EId);
559       E.disconnectFrom(*this, NId);
560     }
561
562     /// @brief Convenience method to disconnect all neighbours from the given
563     ///        node.
564     void disconnectAllNeighborsFromNode(NodeId NId) {
565       for (auto AEId : adjEdgeIds(NId))
566         disconnectEdge(AEId, getEdgeOtherNodeId(AEId, NId));
567     }
568
569     /// @brief Re-attach an edge to its nodes.
570     ///
571     /// Adds an edge that had been previously disconnected back into the
572     /// adjacency set of the nodes that the edge connects.
573     void reconnectEdge(EdgeId EId, NodeId NId) {
574       EdgeEntry &E = getEdge(EId);
575       E.connectTo(*this, EId, NId);
576       if (Solver)
577         Solver->handleReconnectEdge(EId, NId);
578     }
579
580     /// @brief Remove an edge from the graph.
581     /// @param EId Edge id.
582     void removeEdge(EdgeId EId) {
583       if (Solver)
584         Solver->handleRemoveEdge(EId);
585       EdgeEntry &E = getEdge(EId);
586       E.disconnect();
587       FreeEdgeIds.push_back(EId);
588       Edges[EId].invalidate();
589     }
590
591     /// @brief Remove all nodes and edges from the graph.
592     void clear() {
593       Nodes.clear();
594       FreeNodeIds.clear();
595       Edges.clear();
596       FreeEdgeIds.clear();
597     }
598
599     /// @brief Dump a graph to an output stream.
600     template <typename OStream>
601     void dumpToStream(OStream &OS) {
602       OS << nodeIds().size() << " " << edgeIds().size() << "\n";
603
604       for (auto NId : nodeIds()) {
605         const Vector& V = getNodeCosts(NId);
606         OS << "\n" << V.getLength() << "\n";
607         assert(V.getLength() != 0 && "Empty vector in graph.");
608         OS << V[0];
609         for (unsigned i = 1; i < V.getLength(); ++i) {
610           OS << " " << V[i];
611         }
612         OS << "\n";
613       }
614
615       for (auto EId : edgeIds()) {
616         NodeId N1Id = getEdgeNode1Id(EId);
617         NodeId N2Id = getEdgeNode2Id(EId);
618         assert(N1Id != N2Id && "PBQP graphs shound not have self-edges.");
619         const Matrix& M = getEdgeCosts(EId);
620         OS << "\n" << N1Id << " " << N2Id << "\n"
621            << M.getRows() << " " << M.getCols() << "\n";
622         assert(M.getRows() != 0 && "No rows in matrix.");
623         assert(M.getCols() != 0 && "No cols in matrix.");
624         for (unsigned i = 0; i < M.getRows(); ++i) {
625           OS << M[i][0];
626           for (unsigned j = 1; j < M.getCols(); ++j) {
627             OS << " " << M[i][j];
628           }
629           OS << "\n";
630         }
631       }
632     }
633
634     /// @brief Dump this graph to dbgs().
635     void dump() {
636       dumpToStream(dbgs());
637     }
638
639     /// @brief Print a representation of this graph in DOT format.
640     /// @param OS Output stream to print on.
641     template <typename OStream>
642     void printDot(OStream &OS) {
643       OS << "graph {\n";
644       for (auto NId : nodeIds()) {
645         OS << "  node" << NId << " [ label=\""
646            << NId << ": " << getNodeCosts(NId) << "\" ]\n";
647       }
648       OS << "  edge [ len=" << nodeIds().size() << " ]\n";
649       for (auto EId : edgeIds()) {
650         OS << "  node" << getEdgeNode1Id(EId)
651            << " -- node" << getEdgeNode2Id(EId)
652            << " [ label=\"";
653         const Matrix &EdgeCosts = getEdgeCosts(EId);
654         for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
655           OS << EdgeCosts.getRowAsVector(i) << "\\n";
656         }
657         OS << "\" ]\n";
658       }
659       OS << "}\n";
660     }
661   };
662
663 }  // namespace PBQP
664 }  // namespace llvm
665
666 #endif // LLVM_CODEGEN_PBQP_GRAPH_HPP