graphcycles.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // GraphCycles provides incremental cycle detection on a dynamic
  15. // graph using the following algorithm:
  16. //
  17. // A dynamic topological sort algorithm for directed acyclic graphs
  18. // David J. Pearce, Paul H. J. Kelly
  19. // Journal of Experimental Algorithmics (JEA) JEA Homepage archive
  20. // Volume 11, 2006, Article No. 1.7
  21. //
  22. // Brief summary of the algorithm:
  23. //
  24. // (1) Maintain a rank for each node that is consistent
  25. // with the topological sort of the graph. I.e., path from x to y
  26. // implies rank[x] < rank[y].
  27. // (2) When a new edge (x->y) is inserted, do nothing if rank[x] < rank[y].
  28. // (3) Otherwise: adjust ranks in the neighborhood of x and y.
  29. #include "absl/base/attributes.h"
  30. // This file is a no-op if the required LowLevelAlloc support is missing.
  31. #include "absl/base/internal/low_level_alloc.h"
  32. #ifndef ABSL_LOW_LEVEL_ALLOC_MISSING
  33. #include "absl/synchronization/internal/graphcycles.h"
  34. #include <algorithm>
  35. #include <array>
  36. #include <limits>
  37. #include "absl/base/internal/hide_ptr.h"
  38. #include "absl/base/internal/raw_logging.h"
  39. #include "absl/base/internal/spinlock.h"
  40. // Do not use STL. This module does not use standard memory allocation.
  41. namespace absl {
  42. ABSL_NAMESPACE_BEGIN
  43. namespace synchronization_internal {
  44. namespace {
  45. // Avoid LowLevelAlloc's default arena since it calls malloc hooks in
  46. // which people are doing things like acquiring Mutexes.
  47. ABSL_CONST_INIT static absl::base_internal::SpinLock arena_mu(
  48. absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
  49. ABSL_CONST_INIT static base_internal::LowLevelAlloc::Arena* arena;
  50. static void InitArenaIfNecessary() {
  51. arena_mu.Lock();
  52. if (arena == nullptr) {
  53. arena = base_internal::LowLevelAlloc::NewArena(0);
  54. }
  55. arena_mu.Unlock();
  56. }
  57. // Number of inlined elements in Vec. Hash table implementation
  58. // relies on this being a power of two.
  59. static const uint32_t kInline = 8;
  60. // A simple LowLevelAlloc based resizable vector with inlined storage
  61. // for a few elements. T must be a plain type since constructor
  62. // and destructor are not run on elements of type T managed by Vec.
  63. template <typename T>
  64. class Vec {
  65. public:
  66. Vec() { Init(); }
  67. ~Vec() { Discard(); }
  68. void clear() {
  69. Discard();
  70. Init();
  71. }
  72. bool empty() const { return size_ == 0; }
  73. uint32_t size() const { return size_; }
  74. T* begin() { return ptr_; }
  75. T* end() { return ptr_ + size_; }
  76. const T& operator[](uint32_t i) const { return ptr_[i]; }
  77. T& operator[](uint32_t i) { return ptr_[i]; }
  78. const T& back() const { return ptr_[size_-1]; }
  79. void pop_back() { size_--; }
  80. void push_back(const T& v) {
  81. if (size_ == capacity_) Grow(size_ + 1);
  82. ptr_[size_] = v;
  83. size_++;
  84. }
  85. void resize(uint32_t n) {
  86. if (n > capacity_) Grow(n);
  87. size_ = n;
  88. }
  89. void fill(const T& val) {
  90. for (uint32_t i = 0; i < size(); i++) {
  91. ptr_[i] = val;
  92. }
  93. }
  94. // Guarantees src is empty at end.
  95. // Provided for the hash table resizing code below.
  96. void MoveFrom(Vec<T>* src) {
  97. if (src->ptr_ == src->space_) {
  98. // Need to actually copy
  99. resize(src->size_);
  100. std::copy(src->ptr_, src->ptr_ + src->size_, ptr_);
  101. src->size_ = 0;
  102. } else {
  103. Discard();
  104. ptr_ = src->ptr_;
  105. size_ = src->size_;
  106. capacity_ = src->capacity_;
  107. src->Init();
  108. }
  109. }
  110. private:
  111. T* ptr_;
  112. T space_[kInline];
  113. uint32_t size_;
  114. uint32_t capacity_;
  115. void Init() {
  116. ptr_ = space_;
  117. size_ = 0;
  118. capacity_ = kInline;
  119. }
  120. void Discard() {
  121. if (ptr_ != space_) base_internal::LowLevelAlloc::Free(ptr_);
  122. }
  123. void Grow(uint32_t n) {
  124. while (capacity_ < n) {
  125. capacity_ *= 2;
  126. }
  127. size_t request = static_cast<size_t>(capacity_) * sizeof(T);
  128. T* copy = static_cast<T*>(
  129. base_internal::LowLevelAlloc::AllocWithArena(request, arena));
  130. std::copy(ptr_, ptr_ + size_, copy);
  131. Discard();
  132. ptr_ = copy;
  133. }
  134. Vec(const Vec&) = delete;
  135. Vec& operator=(const Vec&) = delete;
  136. };
  137. // A hash set of non-negative int32_t that uses Vec for its underlying storage.
  138. class NodeSet {
  139. public:
  140. NodeSet() { Init(); }
  141. void clear() { Init(); }
  142. bool contains(int32_t v) const { return table_[FindIndex(v)] == v; }
  143. bool insert(int32_t v) {
  144. uint32_t i = FindIndex(v);
  145. if (table_[i] == v) {
  146. return false;
  147. }
  148. if (table_[i] == kEmpty) {
  149. // Only inserting over an empty cell increases the number of occupied
  150. // slots.
  151. occupied_++;
  152. }
  153. table_[i] = v;
  154. // Double when 75% full.
  155. if (occupied_ >= table_.size() - table_.size()/4) Grow();
  156. return true;
  157. }
  158. void erase(uint32_t v) {
  159. uint32_t i = FindIndex(v);
  160. if (static_cast<uint32_t>(table_[i]) == v) {
  161. table_[i] = kDel;
  162. }
  163. }
  164. // Iteration: is done via HASH_FOR_EACH
  165. // Example:
  166. // HASH_FOR_EACH(elem, node->out) { ... }
  167. #define HASH_FOR_EACH(elem, eset) \
  168. for (int32_t elem, _cursor = 0; (eset).Next(&_cursor, &elem); )
  169. bool Next(int32_t* cursor, int32_t* elem) {
  170. while (static_cast<uint32_t>(*cursor) < table_.size()) {
  171. int32_t v = table_[*cursor];
  172. (*cursor)++;
  173. if (v >= 0) {
  174. *elem = v;
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. private:
  181. enum : int32_t { kEmpty = -1, kDel = -2 };
  182. Vec<int32_t> table_;
  183. uint32_t occupied_; // Count of non-empty slots (includes deleted slots)
  184. static uint32_t Hash(uint32_t a) { return a * 41; }
  185. // Return index for storing v. May return an empty index or deleted index
  186. int FindIndex(int32_t v) const {
  187. // Search starting at hash index.
  188. const uint32_t mask = table_.size() - 1;
  189. uint32_t i = Hash(v) & mask;
  190. int deleted_index = -1; // If >= 0, index of first deleted element we see
  191. while (true) {
  192. int32_t e = table_[i];
  193. if (v == e) {
  194. return i;
  195. } else if (e == kEmpty) {
  196. // Return any previously encountered deleted slot.
  197. return (deleted_index >= 0) ? deleted_index : i;
  198. } else if (e == kDel && deleted_index < 0) {
  199. // Keep searching since v might be present later.
  200. deleted_index = i;
  201. }
  202. i = (i + 1) & mask; // Linear probing; quadratic is slightly slower.
  203. }
  204. }
  205. void Init() {
  206. table_.clear();
  207. table_.resize(kInline);
  208. table_.fill(kEmpty);
  209. occupied_ = 0;
  210. }
  211. void Grow() {
  212. Vec<int32_t> copy;
  213. copy.MoveFrom(&table_);
  214. occupied_ = 0;
  215. table_.resize(copy.size() * 2);
  216. table_.fill(kEmpty);
  217. for (const auto& e : copy) {
  218. if (e >= 0) insert(e);
  219. }
  220. }
  221. NodeSet(const NodeSet&) = delete;
  222. NodeSet& operator=(const NodeSet&) = delete;
  223. };
  224. // We encode a node index and a node version in GraphId. The version
  225. // number is incremented when the GraphId is freed which automatically
  226. // invalidates all copies of the GraphId.
  227. inline GraphId MakeId(int32_t index, uint32_t version) {
  228. GraphId g;
  229. g.handle =
  230. (static_cast<uint64_t>(version) << 32) | static_cast<uint32_t>(index);
  231. return g;
  232. }
  233. inline int32_t NodeIndex(GraphId id) {
  234. return static_cast<uint32_t>(id.handle & 0xfffffffful);
  235. }
  236. inline uint32_t NodeVersion(GraphId id) {
  237. return static_cast<uint32_t>(id.handle >> 32);
  238. }
  239. struct Node {
  240. int32_t rank; // rank number assigned by Pearce-Kelly algorithm
  241. uint32_t version; // Current version number
  242. int32_t next_hash; // Next entry in hash table
  243. bool visited; // Temporary marker used by depth-first-search
  244. uintptr_t masked_ptr; // User-supplied pointer
  245. NodeSet in; // List of immediate predecessor nodes in graph
  246. NodeSet out; // List of immediate successor nodes in graph
  247. int priority; // Priority of recorded stack trace.
  248. int nstack; // Depth of recorded stack trace.
  249. void* stack[40]; // stack[0,nstack-1] holds stack trace for node.
  250. };
  251. // Hash table for pointer to node index lookups.
  252. class PointerMap {
  253. public:
  254. explicit PointerMap(const Vec<Node*>* nodes) : nodes_(nodes) {
  255. table_.fill(-1);
  256. }
  257. int32_t Find(void* ptr) {
  258. auto masked = base_internal::HidePtr(ptr);
  259. for (int32_t i = table_[Hash(ptr)]; i != -1;) {
  260. Node* n = (*nodes_)[i];
  261. if (n->masked_ptr == masked) return i;
  262. i = n->next_hash;
  263. }
  264. return -1;
  265. }
  266. void Add(void* ptr, int32_t i) {
  267. int32_t* head = &table_[Hash(ptr)];
  268. (*nodes_)[i]->next_hash = *head;
  269. *head = i;
  270. }
  271. int32_t Remove(void* ptr) {
  272. // Advance through linked list while keeping track of the
  273. // predecessor slot that points to the current entry.
  274. auto masked = base_internal::HidePtr(ptr);
  275. for (int32_t* slot = &table_[Hash(ptr)]; *slot != -1; ) {
  276. int32_t index = *slot;
  277. Node* n = (*nodes_)[index];
  278. if (n->masked_ptr == masked) {
  279. *slot = n->next_hash; // Remove n from linked list
  280. n->next_hash = -1;
  281. return index;
  282. }
  283. slot = &n->next_hash;
  284. }
  285. return -1;
  286. }
  287. private:
  288. // Number of buckets in hash table for pointer lookups.
  289. static constexpr uint32_t kHashTableSize = 8171; // should be prime
  290. const Vec<Node*>* nodes_;
  291. std::array<int32_t, kHashTableSize> table_;
  292. static uint32_t Hash(void* ptr) {
  293. return reinterpret_cast<uintptr_t>(ptr) % kHashTableSize;
  294. }
  295. };
  296. } // namespace
  297. struct GraphCycles::Rep {
  298. Vec<Node*> nodes_;
  299. Vec<int32_t> free_nodes_; // Indices for unused entries in nodes_
  300. PointerMap ptrmap_;
  301. // Temporary state.
  302. Vec<int32_t> deltaf_; // Results of forward DFS
  303. Vec<int32_t> deltab_; // Results of backward DFS
  304. Vec<int32_t> list_; // All nodes to reprocess
  305. Vec<int32_t> merged_; // Rank values to assign to list_ entries
  306. Vec<int32_t> stack_; // Emulates recursion stack for depth-first searches
  307. Rep() : ptrmap_(&nodes_) {}
  308. };
  309. static Node* FindNode(GraphCycles::Rep* rep, GraphId id) {
  310. Node* n = rep->nodes_[NodeIndex(id)];
  311. return (n->version == NodeVersion(id)) ? n : nullptr;
  312. }
  313. GraphCycles::GraphCycles() {
  314. InitArenaIfNecessary();
  315. rep_ = new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Rep), arena))
  316. Rep;
  317. }
  318. GraphCycles::~GraphCycles() {
  319. for (auto* node : rep_->nodes_) {
  320. node->Node::~Node();
  321. base_internal::LowLevelAlloc::Free(node);
  322. }
  323. rep_->Rep::~Rep();
  324. base_internal::LowLevelAlloc::Free(rep_);
  325. }
  326. bool GraphCycles::CheckInvariants() const {
  327. Rep* r = rep_;
  328. NodeSet ranks; // Set of ranks seen so far.
  329. for (uint32_t x = 0; x < r->nodes_.size(); x++) {
  330. Node* nx = r->nodes_[x];
  331. void* ptr = base_internal::UnhidePtr<void>(nx->masked_ptr);
  332. if (ptr != nullptr && static_cast<uint32_t>(r->ptrmap_.Find(ptr)) != x) {
  333. ABSL_RAW_LOG(FATAL, "Did not find live node in hash table %u %p", x, ptr);
  334. }
  335. if (nx->visited) {
  336. ABSL_RAW_LOG(FATAL, "Did not clear visited marker on node %u", x);
  337. }
  338. if (!ranks.insert(nx->rank)) {
  339. ABSL_RAW_LOG(FATAL, "Duplicate occurrence of rank %d", nx->rank);
  340. }
  341. HASH_FOR_EACH(y, nx->out) {
  342. Node* ny = r->nodes_[y];
  343. if (nx->rank >= ny->rank) {
  344. ABSL_RAW_LOG(FATAL, "Edge %u->%d has bad rank assignment %d->%d", x, y,
  345. nx->rank, ny->rank);
  346. }
  347. }
  348. }
  349. return true;
  350. }
  351. GraphId GraphCycles::GetId(void* ptr) {
  352. int32_t i = rep_->ptrmap_.Find(ptr);
  353. if (i != -1) {
  354. return MakeId(i, rep_->nodes_[i]->version);
  355. } else if (rep_->free_nodes_.empty()) {
  356. Node* n =
  357. new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Node), arena))
  358. Node;
  359. n->version = 1; // Avoid 0 since it is used by InvalidGraphId()
  360. n->visited = false;
  361. n->rank = rep_->nodes_.size();
  362. n->masked_ptr = base_internal::HidePtr(ptr);
  363. n->nstack = 0;
  364. n->priority = 0;
  365. rep_->nodes_.push_back(n);
  366. rep_->ptrmap_.Add(ptr, n->rank);
  367. return MakeId(n->rank, n->version);
  368. } else {
  369. // Preserve preceding rank since the set of ranks in use must be
  370. // a permutation of [0,rep_->nodes_.size()-1].
  371. int32_t r = rep_->free_nodes_.back();
  372. rep_->free_nodes_.pop_back();
  373. Node* n = rep_->nodes_[r];
  374. n->masked_ptr = base_internal::HidePtr(ptr);
  375. n->nstack = 0;
  376. n->priority = 0;
  377. rep_->ptrmap_.Add(ptr, r);
  378. return MakeId(r, n->version);
  379. }
  380. }
  381. void GraphCycles::RemoveNode(void* ptr) {
  382. int32_t i = rep_->ptrmap_.Remove(ptr);
  383. if (i == -1) {
  384. return;
  385. }
  386. Node* x = rep_->nodes_[i];
  387. HASH_FOR_EACH(y, x->out) {
  388. rep_->nodes_[y]->in.erase(i);
  389. }
  390. HASH_FOR_EACH(y, x->in) {
  391. rep_->nodes_[y]->out.erase(i);
  392. }
  393. x->in.clear();
  394. x->out.clear();
  395. x->masked_ptr = base_internal::HidePtr<void>(nullptr);
  396. if (x->version == std::numeric_limits<uint32_t>::max()) {
  397. // Cannot use x any more
  398. } else {
  399. x->version++; // Invalidates all copies of node.
  400. rep_->free_nodes_.push_back(i);
  401. }
  402. }
  403. void* GraphCycles::Ptr(GraphId id) {
  404. Node* n = FindNode(rep_, id);
  405. return n == nullptr ? nullptr
  406. : base_internal::UnhidePtr<void>(n->masked_ptr);
  407. }
  408. bool GraphCycles::HasNode(GraphId node) {
  409. return FindNode(rep_, node) != nullptr;
  410. }
  411. bool GraphCycles::HasEdge(GraphId x, GraphId y) const {
  412. Node* xn = FindNode(rep_, x);
  413. return xn && FindNode(rep_, y) && xn->out.contains(NodeIndex(y));
  414. }
  415. void GraphCycles::RemoveEdge(GraphId x, GraphId y) {
  416. Node* xn = FindNode(rep_, x);
  417. Node* yn = FindNode(rep_, y);
  418. if (xn && yn) {
  419. xn->out.erase(NodeIndex(y));
  420. yn->in.erase(NodeIndex(x));
  421. // No need to update the rank assignment since a previous valid
  422. // rank assignment remains valid after an edge deletion.
  423. }
  424. }
  425. static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound);
  426. static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound);
  427. static void Reorder(GraphCycles::Rep* r);
  428. static void Sort(const Vec<Node*>&, Vec<int32_t>* delta);
  429. static void MoveToList(
  430. GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst);
  431. bool GraphCycles::InsertEdge(GraphId idx, GraphId idy) {
  432. Rep* r = rep_;
  433. const int32_t x = NodeIndex(idx);
  434. const int32_t y = NodeIndex(idy);
  435. Node* nx = FindNode(r, idx);
  436. Node* ny = FindNode(r, idy);
  437. if (nx == nullptr || ny == nullptr) return true; // Expired ids
  438. if (nx == ny) return false; // Self edge
  439. if (!nx->out.insert(y)) {
  440. // Edge already exists.
  441. return true;
  442. }
  443. ny->in.insert(x);
  444. if (nx->rank <= ny->rank) {
  445. // New edge is consistent with existing rank assignment.
  446. return true;
  447. }
  448. // Current rank assignments are incompatible with the new edge. Recompute.
  449. // We only need to consider nodes that fall in the range [ny->rank,nx->rank].
  450. if (!ForwardDFS(r, y, nx->rank)) {
  451. // Found a cycle. Undo the insertion and tell caller.
  452. nx->out.erase(y);
  453. ny->in.erase(x);
  454. // Since we do not call Reorder() on this path, clear any visited
  455. // markers left by ForwardDFS.
  456. for (const auto& d : r->deltaf_) {
  457. r->nodes_[d]->visited = false;
  458. }
  459. return false;
  460. }
  461. BackwardDFS(r, x, ny->rank);
  462. Reorder(r);
  463. return true;
  464. }
  465. static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) {
  466. // Avoid recursion since stack space might be limited.
  467. // We instead keep a stack of nodes to visit.
  468. r->deltaf_.clear();
  469. r->stack_.clear();
  470. r->stack_.push_back(n);
  471. while (!r->stack_.empty()) {
  472. n = r->stack_.back();
  473. r->stack_.pop_back();
  474. Node* nn = r->nodes_[n];
  475. if (nn->visited) continue;
  476. nn->visited = true;
  477. r->deltaf_.push_back(n);
  478. HASH_FOR_EACH(w, nn->out) {
  479. Node* nw = r->nodes_[w];
  480. if (nw->rank == upper_bound) {
  481. return false; // Cycle
  482. }
  483. if (!nw->visited && nw->rank < upper_bound) {
  484. r->stack_.push_back(w);
  485. }
  486. }
  487. }
  488. return true;
  489. }
  490. static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) {
  491. r->deltab_.clear();
  492. r->stack_.clear();
  493. r->stack_.push_back(n);
  494. while (!r->stack_.empty()) {
  495. n = r->stack_.back();
  496. r->stack_.pop_back();
  497. Node* nn = r->nodes_[n];
  498. if (nn->visited) continue;
  499. nn->visited = true;
  500. r->deltab_.push_back(n);
  501. HASH_FOR_EACH(w, nn->in) {
  502. Node* nw = r->nodes_[w];
  503. if (!nw->visited && lower_bound < nw->rank) {
  504. r->stack_.push_back(w);
  505. }
  506. }
  507. }
  508. }
  509. static void Reorder(GraphCycles::Rep* r) {
  510. Sort(r->nodes_, &r->deltab_);
  511. Sort(r->nodes_, &r->deltaf_);
  512. // Adds contents of delta lists to list_ (backwards deltas first).
  513. r->list_.clear();
  514. MoveToList(r, &r->deltab_, &r->list_);
  515. MoveToList(r, &r->deltaf_, &r->list_);
  516. // Produce sorted list of all ranks that will be reassigned.
  517. r->merged_.resize(r->deltab_.size() + r->deltaf_.size());
  518. std::merge(r->deltab_.begin(), r->deltab_.end(),
  519. r->deltaf_.begin(), r->deltaf_.end(),
  520. r->merged_.begin());
  521. // Assign the ranks in order to the collected list.
  522. for (uint32_t i = 0; i < r->list_.size(); i++) {
  523. r->nodes_[r->list_[i]]->rank = r->merged_[i];
  524. }
  525. }
  526. static void Sort(const Vec<Node*>& nodes, Vec<int32_t>* delta) {
  527. struct ByRank {
  528. const Vec<Node*>* nodes;
  529. bool operator()(int32_t a, int32_t b) const {
  530. return (*nodes)[a]->rank < (*nodes)[b]->rank;
  531. }
  532. };
  533. ByRank cmp;
  534. cmp.nodes = &nodes;
  535. std::sort(delta->begin(), delta->end(), cmp);
  536. }
  537. static void MoveToList(
  538. GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst) {
  539. for (auto& v : *src) {
  540. int32_t w = v;
  541. v = r->nodes_[w]->rank; // Replace v entry with its rank
  542. r->nodes_[w]->visited = false; // Prepare for future DFS calls
  543. dst->push_back(w);
  544. }
  545. }
  546. int GraphCycles::FindPath(GraphId idx, GraphId idy, int max_path_len,
  547. GraphId path[]) const {
  548. Rep* r = rep_;
  549. if (FindNode(r, idx) == nullptr || FindNode(r, idy) == nullptr) return 0;
  550. const int32_t x = NodeIndex(idx);
  551. const int32_t y = NodeIndex(idy);
  552. // Forward depth first search starting at x until we hit y.
  553. // As we descend into a node, we push it onto the path.
  554. // As we leave a node, we remove it from the path.
  555. int path_len = 0;
  556. NodeSet seen;
  557. r->stack_.clear();
  558. r->stack_.push_back(x);
  559. while (!r->stack_.empty()) {
  560. int32_t n = r->stack_.back();
  561. r->stack_.pop_back();
  562. if (n < 0) {
  563. // Marker to indicate that we are leaving a node
  564. path_len--;
  565. continue;
  566. }
  567. if (path_len < max_path_len) {
  568. path[path_len] = MakeId(n, rep_->nodes_[n]->version);
  569. }
  570. path_len++;
  571. r->stack_.push_back(-1); // Will remove tentative path entry
  572. if (n == y) {
  573. return path_len;
  574. }
  575. HASH_FOR_EACH(w, r->nodes_[n]->out) {
  576. if (seen.insert(w)) {
  577. r->stack_.push_back(w);
  578. }
  579. }
  580. }
  581. return 0;
  582. }
  583. bool GraphCycles::IsReachable(GraphId x, GraphId y) const {
  584. return FindPath(x, y, 0, nullptr) > 0;
  585. }
  586. void GraphCycles::UpdateStackTrace(GraphId id, int priority,
  587. int (*get_stack_trace)(void** stack, int)) {
  588. Node* n = FindNode(rep_, id);
  589. if (n == nullptr || n->priority >= priority) {
  590. return;
  591. }
  592. n->nstack = (*get_stack_trace)(n->stack, ABSL_ARRAYSIZE(n->stack));
  593. n->priority = priority;
  594. }
  595. int GraphCycles::GetStackTrace(GraphId id, void*** ptr) {
  596. Node* n = FindNode(rep_, id);
  597. if (n == nullptr) {
  598. *ptr = nullptr;
  599. return 0;
  600. } else {
  601. *ptr = n->stack;
  602. return n->nstack;
  603. }
  604. }
  605. } // namespace synchronization_internal
  606. ABSL_NAMESPACE_END
  607. } // namespace absl
  608. #endif // ABSL_LOW_LEVEL_ALLOC_MISSING