Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/Firefox/js/public/     Datei vom 27.6.2026 mit Größe 988 B image not shown  

Quelle:  UbiNodeDominatorTree.h  Sprache: C


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


#ifndef js_UbiNodeDominatorTree_h
#define js_UbiNodeDominatorTree_h

#include "mozilla/Maybe.h"
#include "mozilla/UniquePtr.h"

#include <utility>

#include "js/AllocPolicy.h"
#include "js/UbiNode.h"
#include "js/UbiNodePostOrder.h"
#include "js/Utility.h"
#include "js/Vector.h"

namespace JS {
namespace ubi {

/**
 * In a directed graph with a root node `R`, a node `A` is said to "dominate" a
 * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to
 * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B`
 * itself, and does not dominate any other nodes which also dominate `B` in
 * turn.
 *
 * If we take every node from a graph `G` and create a new graph `T` with edges
 * to each node from its immediate dominator, then `T` is a tree (each node has
 * only one immediate dominator, or none if it is the root). This tree is called
 * a "dominator tree".
 *
 * This class represents a dominator tree constructed from a `JS::ubi::Node`
 * heap graph. The domination relationship and dominator trees are useful tools
 * for analyzing heap graphs because they tell you:
 *
 *   - Exactly what could be reclaimed by the GC if some node `A` became
 *     unreachable: those nodes which are dominated by `A`,
 *
 *   - The "retained size" of a node in the heap graph, in contrast to its
 *     "shallow size". The "shallow size" is the space taken by a node itself,
 *     not counting anything it references. The "retained size" of a node is its
 *     shallow size plus the size of all the things that would be collected if
 *     the original node wasn't (directly or indirectly) referencing them. In
 *     other words, the retained size is the shallow size of a node plus the
 *     shallow sizes of every other node it dominates. For example, the root
 *     node in a binary tree might have a small shallow size that does not take
 *     up much space itself, but it dominates the rest of the binary tree and
 *     its retained size is therefore significant (assuming no external
 *     references into the tree).
 *
 * The simple, engineered algorithm presented in "A Simple, Fast Dominance
 * Algorithm" by Cooper el al[0] is used to find dominators and construct the
 * dominator tree. This algorithm runs in O(n^2) time, but is faster in practice
 * than alternative algorithms with better theoretical running times, such as
 * Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement
 * is that Cooper et al found it is faster in practice *on control flow graphs*
 * and I'm not convinced that this property also holds on *heap* graphs. That
 * said, the implementation of this algorithm is *much* simpler than
 * Lengauer-Tarjan and has been found to be fast enough at least for the time
 * being.
 *
 * [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf
 */

class JS_PUBLIC_API DominatorTree {
 private:
  // Types.

  using PredecessorSets = js::HashMap<Node, NodeSetPtr, js::DefaultHasher<Node>,
                                      js::SystemAllocPolicy>;
  using NodeToIndexMap = js::HashMap<Node, uint32_t, js::DefaultHasher<Node>,
                                     js::SystemAllocPolicy>;
  class DominatedSets;

 public:
  class DominatedSetRange;

  /**
   * A pointer to an immediately dominated node.
   *
   * Don't use this type directly; it is no safer than regular pointers. This
   * is only for use indirectly with range-based for loops and
   * `DominatedSetRange`.
   *
   * @see JS::ubi::DominatorTree::getDominatedSet
   */

  class DominatedNodePtr {
    friend class DominatedSetRange;

    const JS::ubi::Vector<Node>& postOrder;
    const uint32_t* ptr;

    DominatedNodePtr(const JS::ubi::Vector<Node>& postOrder,
                     const uint32_t* ptr)
        : postOrder(postOrder), ptr(ptr) {}

   public:
    bool operator!=(const DominatedNodePtr& rhs) const {
      return ptr != rhs.ptr;
    }
    void operator++() { ptr++; }
    const Node& operator*() const { return postOrder[*ptr]; }
  };

  /**
   * A range of immediately dominated `JS::ubi::Node`s for use with
   * range-based for loops.
   *
   * @see JS::ubi::DominatorTree::getDominatedSet
   */

  class DominatedSetRange {
    friend class DominatedSets;

    const JS::ubi::Vector<Node>& postOrder;
    const uint32_t* beginPtr;
    const uint32_t* endPtr;

    DominatedSetRange(JS::ubi::Vector<Node>& postOrder, const uint32_t* begin,
                      const uint32_t* end)
        : postOrder(postOrder), beginPtr(begin), endPtr(end) {
      MOZ_ASSERT(begin <= end);
    }

   public:
    DominatedNodePtr begin() const {
      MOZ_ASSERT(beginPtr <= endPtr);
      return DominatedNodePtr(postOrder, beginPtr);
    }

    DominatedNodePtr end() const { return DominatedNodePtr(postOrder, endPtr); }

    size_t length() const {
      MOZ_ASSERT(beginPtr <= endPtr);
      return endPtr - beginPtr;
    }

    /**
     * Safely skip ahead `n` dominators in the range, in O(1) time.
     *
     * Example usage:
     *
     *     mozilla::Maybe<DominatedSetRange> range =
     *         myDominatorTree.getDominatedSet(myNode);
     *     if (range.isNothing()) {
     *         // Handle unknown nodes however you see fit...
     *         return false;
     *     }
     *
     *     // Don't care about the first ten, for whatever reason.
     *     range->skip(10);
     *     for (const JS::ubi::Node& dominatedNode : *range) {
     *         // ...
     *     }
     */

    void skip(size_t n) {
      beginPtr += n;
      if (beginPtr > endPtr) {
        beginPtr = endPtr;
      }
    }
  };

 private:
  /**
   * The set of all dominated sets in a dominator tree.
   *
   * Internally stores the sets in a contiguous array, with a side table of
   * indices into that contiguous array to denote the start index of each
   * individual set.
   */

  class DominatedSets {
    JS::ubi::Vector<uint32_t> dominated;
    JS::ubi::Vector<uint32_t> indices;

    DominatedSets(JS::ubi::Vector<uint32_t>&& dominated,
                  JS::ubi::Vector<uint32_t>&& indices)
        : dominated(std::move(dominated)), indices(std::move(indices)) {}

   public:
    // DominatedSets is not copy-able.
    DominatedSets(const DominatedSets& rhs) = delete;
    DominatedSets& operator=(const DominatedSets& rhs) = delete;

    // DominatedSets is move-able.
    DominatedSets(DominatedSets&& rhs)
        : dominated(std::move(rhs.dominated)), indices(std::move(rhs.indices)) {
      MOZ_ASSERT(this != &rhs, "self-move not allowed");
    }
    DominatedSets& operator=(DominatedSets&& rhs) {
      this->~DominatedSets();
      new (this) DominatedSets(std::move(rhs));
      return *this;
    }

    /**
     * Create the DominatedSets given the mapping of a node index to its
     * immediate dominator. Returns `Some` on success, `Nothing` on OOM
     * failure.
     */

    static mozilla::Maybe<DominatedSets> Create(
        const JS::ubi::Vector<uint32_t>& doms) {
      auto length = doms.length();
      MOZ_ASSERT(length < UINT32_MAX);

      // Create a vector `dominated` holding a flattened set of buckets of
      // immediately dominated children nodes, with a lookup table
      // `indices` mapping from each node to the beginning of its bucket.
      //
      // This has three phases:
      //
      // 1. Iterate over the full set of nodes and count up the size of
      //    each bucket. These bucket sizes are temporarily stored in the
      //    `indices` vector.
      //
      // 2. Convert the `indices` vector to store the cumulative sum of
      //    the sizes of all buckets before each index, resulting in a
      //    mapping from node index to one past the end of that node's
      //    bucket.
      //
      // 3. Iterate over the full set of nodes again, filling in bucket
      //    entries from the end of the bucket's range to its
      //    beginning. This decrements each index as a bucket entry is
      //    filled in. After having filled in all of a bucket's entries,
      //    the index points to the start of the bucket.

      JS::ubi::Vector<uint32_t> dominated;
      JS::ubi::Vector<uint32_t> indices;
      if (!dominated.growBy(length) || !indices.growBy(length)) {
        return mozilla::Nothing();
      }

      // 1
      memset(indices.begin(), 0, length * sizeof(uint32_t));
      for (uint32_t i = 0; i < length; i++) {
        indices[doms[i]]++;
      }

      // 2
      uint32_t sumOfSizes = 0;
      for (uint32_t i = 0; i < length; i++) {
        sumOfSizes += indices*immediate dom

¤ Dauer der Verarbeitung: 0.2 Sekunden  (vorverarbeitet am  2026-11-25) ¤

*Bot Zugriff