1.1.2 • Published 6 years ago

dominators v1.1.2

Weekly downloads
19
License
MIT
Repository
github
Last release
6 years ago

dominators

Coveralls Status Build Status Dependency Status npm version License Known Vulnerabilities david-dm

Various dominator tree generators.

It implements two different methods for finding the immediate dominators of a graph.

  1. Implements a near-linear time iterative dominator generator based on the paper A Simple, Fast Dominance Algorithm using an iterative method1

  2. Yet another Lengauer & Tarjan implementation with variations. From this paper2 which you can find a link to it here (and many other places, in case this link goes bad): A fast algorithm for finding dominators in a flowgraph

Install

npm i dominators

Usage

const 
    { 
        iterative, 
        lt, 
        frontiers_from_preds, 
        frontiers_from_succs,
        reverse_graph
    } = require( 'dominators' ),
    
    someGraph = [
                        [ 1, 8 ],    // start
                        [ 2, 3 ],    // a
                        [ 3 ],       // b
                        [ 4, 5 ],    // c
                        [ 6 ],       // d
                        [ 6 ],       // e
                        [ 7, 2 ],    // f
                        [ 8 ],       // g
                        []           // end
                    ],
    immediateDominators = iterative( someGraph ),
    //  idoms = [ null, 0, 1, 1, 3, 3, 3, 6, 0 ],

    df = frontiers_from_succs( someGraph, immediateDominators ),
    // df = [ [], [ 8 ], [ 3 ], [ 2, 8 ], [ 6 ], [ 6 ], [ 2, 8 ], [ 8 ], [] ]
    // or
    same = frontiers_from_preds( reverse_graph( someGraph ), immediateDominators ),
    // df = [ [], [ 8 ], [ 3 ], [ 2, 8 ], [ 6 ], [ 6 ], [ 2, 8 ], [ 8 ], [] ]

    // See the explanation of parameters below.
    ltDoms = lt( someGraph, 0, true ),
    //  ltDoms = [ null, 0, 1, 1, 3, 3, 3, 6, 0 ],
    
    // The first parameter is your graph, an array of arrays of successor indices.
    // The second parameter is the start node, defaults to 0. This is optional and defaults to 0.
    // The last parameter is an optional boolean for whether to run it flat or not.
    // If it runs flat (set to true) then it will not use recursion for the DFS or the compress
    // function. The default is true.
    ltDomsSame = lt( someGraph, 0, true );
    //  ltDoms = [ null, 0, 1, 1, 3, 3, 3, 6, 0 ],

// Read full API documentation below
const myGraph = make_dom( graph );

myGraph.forStrictDominators( n => console.log( `${n} is a strict dominator of 9` ), 9 );

if ( myGraph.strictlyDominates( 7, 9 ) )
    console.log( `7 strictly dominates 9` );

console.log( `Node at index 7 strictly dominates these: ${myGraph.strictlyDominates( 7 ).join( ', ' )}` );
console.log( `The strict dominators of 7 are ${myGraph.strictDominators( 7 ).join( ', ' )}` );

Fast Lengauer-Tarjan LINK procedure

For the sake of completeness, below is the fast balanaced version of link, which is not included in the current module code for two reasons:

  1. The LT algorithm with this LINK only becomes faster than the normal implementation when we're dealing with 10s or 100s of thousands of nodes, in which cases you shouldn't be using JavaScript anyway.
  2. I don't have test graph large enough to get proper coverage so, since it's not really useful, I decided to remove it.

This implementation uses arrays rather then an object. That's how I originally implemented this algorithm but that makes it incompatible with the current implementation. I won't convert it since it's not used, however, because it is interesting, I've included it here, for interested parties, of which there will probably be at least zero but not more.

    balanced_link = ( w ) => {
        let s = w,
            v = parent[ w ];

        do
        {
            let cs  = child[ s ],
                bcs = cs !== null ? best[ cs ] : null;

            if ( cs !== null && semi[ best[ w ] ] < semi[ bcs ] )
            {
                let ccs  = child[ cs ],
                    ss   = size[ s ],
                    scs  = size[ cs ],
                    sccs = ccs !== null ? size[ ccs ] : 0;

                if ( ss - scs >= scs - sccs )
                    child[ s ] = ccs;
                else
                {
                    size[ cs ] = ss;
                    ancestor[ s ] = cs;
                    s = cs;
                }
            }
            else
                break;
        }
        while ( true );

        best[ s ] = best[ w ];
        if ( size[ v ] < size[ w ] )
        {
            let t = s;
            s = child[ v ];
            child[ v ] = t;
        }
        size[ v ] += size[ w ];
        while ( s !== null )
        {
            ancestor[ s ] = v;
            s = child[ s ];
        }
    }

License

MIT © Julian Jensen

API

Functions

Typedefs

make_dom(opts) ⇒ Object

This will associated a graph with a number of useful utility functions. It will return an object with a variety of functions that operate on the graphs.

You might notice that many of these functions I took from the WebKit dominators.h file, which I really liked, and, although I re-wrote the code completely (obviously, since it was in C++), I decided to keep their comments with a few small alterations or corrections. I decided to not use their iterated dominance frontier code, because it was as efficient as it could be. Instead, I implemented one that uses a DJ-graph that I found in Chapter 4 of "The SSA Book," called "Advanced Contruction Algorithms for SSA" by D. Das, U. Ramakrishna, V. Sreedhar. That book doesn't seem to be published or, if it has, I've missed it. You can build the book yourself, supposedly, (I couldn't make that work, though) from here: SSA Book or you can probably find a PDF version of it somewhere on the web, which is what I did.

Kind: global function

ParamType
optsDomWalkerOptions | Array.<Array.<number>>

Example

const myGraph = make_dom( graph );

myGraph.forStrictDominators( n => console.log( `${n} is a strict dominator of 9` ), 9 );

Example

if ( myGraph.strictlyDominates( 7, 9 ) )
    console.log( `7 strictly dominates 9` );

Example

console.log( `Node at index 7 strictly dominates these: ${myGraph.strictlyDominates( 7 ).join( ', ' )}` );
console.log( `The strict dominators of 7 are ${myGraph.strictDominators( 7 ).join( ', ' )}` );

make_dom~alternative_idf(defs) ⇒ Array

This calculates the iterated dominance frontier quickest of all but requires that you have already computed the dominance frontier for each individual node. If you call this without frontiers being set, it will calculate all of them the first time.

Kind: inner method of make_dom

ParamType
defsArray.<number>

make_dom~forIteratedDominanceFrontier(fn, defs)

Same as iteratedDominanceFrontier( defs ) except it doesn't return anything but will invoke the callback as it discovers each node in the iterated dominance frontier.

Kind: inner method of make_dom

ParamTypeDescription
fnfunctionA callback function with one argument, a node in the DF of the input list
defsArray.<number>A list of definition nodes

make_dom~iteratedDominanceFrontier(defs) ⇒ Array.<number>

Given a list of definition nodes, let's call them start nodes, this will return the dominance frontier of those nodes. If you're doing SSA, this would be where you'd want to place phi-functions when building a normal SSA tree. To create a pruned or minimal tree, you'd probably have to discard some of these but it makes for a starting point.

Kind: inner method of make_dom
Returns: Array.<number> - - A list of all node sin the DF of the input set

ParamTypeDescription
defsArray.<number>A list of definition nodes

make_dom~forStrictDominators(fn, to)

Loops through each strict dominator of the given node.

Kind: inner method of make_dom

ParamType
fnfunction
tonumber

make_dom~forDominators(fn, to)

This will visit the dominators starting with the to node and moving up the idom tree until it gets to the root.

Kind: inner method of make_dom

ParamType
fnfunction
tonumber

make_dom~strictDominators(to) ⇒ Array.<number>

This will return all strict dominators for the given node. Same as dominators but excluding the given node.

Kind: inner method of make_dom

ParamType
tonumber

make_dom~dominators() ⇒ Array.<number>

This returns a list of all dominators for the given node, including the node itself since a node always dominates itself.

Kind: inner method of make_dom

make_dom~strictlyDominates(from, to) ⇒ boolean | Array.<number>

This will return one of two things. If call with two node numbers, it will return a boolean indicating if the first node strictly dominates the second node.

If called with only one node number then it will create a list of all nodes strictly dominated by the given node.

Kind: inner method of make_dom

ParamType
fromnumber
tonumber

make_dom~dominates(from, to) ⇒ boolean | Array.<number>

This is the same as the strictlyDominates() function but includes the given node.

Kind: inner method of make_dom

ParamType
fromnumber
tonumber

make_dom~forStrictlyDominates(fn, from, notStrict)

Thie loops through all nodes strictly dominated by the given node.

Kind: inner method of make_dom

ParamTypeDefault
fnfunction
fromnumber
notStrictbooleanfalse

make_dom~forDominates(fn, from)

Thie loops through all nodes strictly dominated by the given node, including the node itself.

Kind: inner method of make_dom

ParamType
fnfunction
fromnumber

make_dom~forDominanceFrontier(fn, from)

Paraphrasing from Dominator (graph theory):

"The dominance frontier of a block 'from' is the set of all blocks 'to' such that 'from' dominates an immediate predecessor of 'to', but 'from' does not strictly dominate 'to'."

A useful corner case to remember: a block may be in its own dominance frontier if it has a loop edge to itself, since it dominates itself and so it dominates its own immediate predecessor, and a block never strictly dominates itself.

Kind: inner method of make_dom

ParamType
fnfunction
fromnumber

make_dom~dominanceFrontier(from) ⇒ Array.<number>

Returns the dominanace frontier of a given node.

Kind: inner method of make_dom

ParamType
fromnumber

make_dom~forPrunedIteratedDominanceFrontier(fn, from)

This is a close relative of forIteratedDominanceFrontier(), which allows the given predicate function to return false to indicate that we don't wish to consider the given block. Useful for computing pruned SSA form.

Kind: inner method of make_dom

ParamType
fnfunction
fromArray.<number>

iterative(succs, startIndex, flat) ⇒ Array.<number>

Implements a near-linear time iterative dominator generator based on this paper: (A Simple, Fast Dominance Algorithm)https://www.cs.rice.edu/~keith/Embed/dom.pdf Citation: Cooper, Keith & Harvey, Timothy & Kennedy, Ken. (2006). A Simple, Fast Dominance Algorithm. Rice University, CS Technical Report 06-33870

Kind: global function

ParamTypeDefault
succsArray.<(Array.<number>|number)>
startIndexnumber0
flatbooleantrue

iterative~nsuccs : Array.<Array.<number>>

Kind: inner constant of iterative

check(vertices, idoms)

Find dominance frontiers

Kind: global function

ParamType
verticesArray.<Array.<number>>
idomsArray.<?number>

frontiers_from_preds(preds, idoms)

Find dominance frontiers

Kind: global function

ParamType
predsArray.<Array.<number>>
idomsArray.<?number>

frontiers_from_succs(succs, idoms)

Find dominance frontiers

Kind: global function

ParamType
succsArray.<Array.<number>>
idomsArray.<?number>

lt(nodes, startIndex, flat)

Kind: global function

ParamTypeDefault
nodesArray.<Array.<number>>
startIndexnumber0
flatbooleantrue

normalize(nodes) ⇒ Array.<Array.<number>>

Kind: global function

ParamType
nodesArray.<(Array.<number>|number)>

condRefToSelf(seed, chk, dest) ⇒ Array.<Array.<number>>

Kind: global function
Returns: Array.<Array.<number>> - }

ParamType
seedArray.<Array.<number>>
chkfunction
destArray.<Array.<number>>

simpleRefToSelf(seed, dest) ⇒ Array.<Array.<number>>

Kind: global function
Returns: Array.<Array.<number>> - }

ParamType
seedArray.<Array.<number>>
destArray.<Array.<number>>

create_j_edges(_nodes, domLevels, domTree, idoms) ⇒ *

This will create and return the J-edges of a graph. The J-edges, or Join edges, make up one-half of the DJ-graph. For more information read the documentation for the DJ-graph.

You need only pass the nodes of the graph to this function. The rest of the parameters are optional and will be computed if not provided. I allow the options to pass them in case you already have them calculated from elsewhere, just to make things a bit faster. If no arguments are provided other than the basic vertices, it will compute the immediate dominators, create the dominator tree, and compute the levels, and discard all of those results. Not a big deal unless you're dealing with very large graphs, in which case you should calculate those separately and provide them as inputs here.

Kind: global function
See: create_dj_graph

ParamTypeDescription
_nodesArray.<Array.<number>>An array of arrays of successors indices, as always
domLevelsArray.<number>The levels (or depth) of the nodes in the dominator tree
domTreeArray.<Array.<number>>The dominator tree in the standard format, same as _nodes
idomsArray.<number>The immediate dominators

create_levels(nodes) ⇒ Array.<number>

Calculate the level of each node in terms of how many edges it takes to reach the root. For the sake of simplicity, this uses a BFS to compute depth values.

Kind: global function
Returns: Array.<number> - - An array of depth (i.e. level) numbers

ParamTypeDescription
nodesArray.<Array.<number>>The graph

create_nodes(_nodes, idoms)

A convenience method. It returns an array of object, one for each nodes in the graph, and in that order, that holds most of the information you could want for working with graphs.

Specifically, each node looks as descibed in the typedef for GraphNode.

Kind: global function
See: GraphNode

ParamTypeDescription
_nodesArray.<Array.<number>>The usual graph nodes
idomsArray.<number>The immediate dominators, if not provided, they will be computed

create_dj_graph(nodes, idoms, domTree)

Returns a DJ-graph which is a graph that consts of the dominator tree and select join edges from the input graph.

Kind: global function

ParamTypeDescription
nodesArray.<Array.<number>>Graph in the usual format
idomsArray.<number>Immediate dominators, if omiteed, they will be computed
domTreeArray.<Array.<number>>Dominator tree, it omitted, will be computed

DomWalkerOptions : object

Kind: global typedef
Properties

NameType
nodesArray.<Array.<number>>
idomsArray.<?number>
domTreeArray.<Array.<number>>
jEdgesArray.<Array.<number>>
frontiersArray.<Array.<number>>
djGraphArray.<Array.<Array.<number>>>
domLevelsArray.<number>

GraphNode : object

Kind: global typedef
Properties

NameTypeDescription
idnumberThe index of this node in the original array
succsArray.<number>The successor node indices
predsArray.<number>The predecessor node indices
domSuccsArray.<number>The dominator tree successor indices
idomnumberThe immediate dominator and, of course, dominator tree predecessor
levelnumberThe depth (or level) of the vertex
domLevelnumberThe depth in the dominator tree
jSuccsArray.<number>The successor J-edges, if any, of this node
jPredsArray.<number>The predecessor J-edges, if any, of this node

1 Cooper, Keith & Harvey, Timothy & Kennedy, Ken. (2006). A Simple, Fast Dominance Algorithm. Rice University, CS Technical Report 06-33870

2 Thomas Lengauer and Robert Endre Tarjan. 1979. A fast algorithm for finding dominators in a flowgraph. ACM Trans. Program. Lang. Syst. 1, 1 (January 1979), 121-141. DOI=http://dx.doi.org/10.1145/357062.357071

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago