Coverage Report

Created: 2025-08-25 06:55

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