Graph.h 22 KB

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