An Introduction to Binary Decision Diagrams Henrik Reif Andersen x y y z 1 0 Lecture notes for Efficient Algorithms and Programs, Fall 1999. E-mail: hra@itu.dk. Web: http://www.itu.dk/people/hra The IT University of Copenhagen Glentevej 67 2400 Copenhagen NV. 1 2 Preface This note is a short introduction to Binary Decision Diagrams. It provides some background knowledge and describes the core algorithms. More details can be found in Bryant’s original paper on Reduced Ordered Binary Decision Diagrams [Bry86] and the survey paper [Bry92]. A recent extension called Boolean Expression Diagrams is described in [AH97]. This note is a revision of an earlier version from fall 1996 (based on versions from 1995 and 1994). The major differences are as follows: Firstly, ROBDDs are now viewed as nodes of one global graph with one fixed ordering to reflect state-of-the-art of efficient BDD packages. The algorithms have been changed (and simplified) to reflect this fact. Secondly, a proof of the canonicity lemma has been added. Thirdly, the sections presenting the algorithms have been completely restructured. Finally, the project proposal has been revised. Acknowledgements Thanks to the students on the courses of fall 1994, 1995, and 1996 for helping me debug and improve the notes. Thanks are also due to Hans Rischel, Morten Ulrik Sørensen, Niels Maretti, Jørgen Staunstrup, Kim Skak Larsen, Henrik Hulgaard, and various people on the Internet who found typos and suggested improvements. 3 CONTENTS 4 Contents 1 Boolean Expressions 6 2 Normal Forms 7 3 Binary Decision Diagrams 8 4 Constructing and Manipulating ROBDDs 4.1 M K . . . . . . . . . . . . . . . . . . . . 4.2 BUILD . . . . . . . . . . . . . . . . . . . 4.3 A PPLY . . . . . . . . . . . . . . . . . . . 4.4 R ESTRICT . . . . . . . . . . . . . . . . . 4.5 S AT C OUNT, A NY S AT, A LL S AT . . . . . 4.6 S IMPLIFY . . . . . . . . . . . . . . . . . 4.7 Existential Quantification and Substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 15 16 17 19 21 23 25 5 Implementing the ROBDD operations 26 6 Examples of problem solving with ROBDDs 6.1 The 8 Queens problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Correctness of Combinational Circuits . . . . . . . . . . . . . . . . . . . . . . 6.3 Equivalence of Combinational Circuits . . . . . . . . . . . . . . . . . . . . . . 27 27 28 28 7 Verification with ROBDDs 7.1 Knights tour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 32 8 Project: An ROBDD Package 34 References 35 CONTENTS 5 1 BOOLEAN EXPRESSIONS 6 1 Boolean Expressions The classical calculus for dealing with truth values consists of Boolean variables   , the constants true and false , the operators of conjunction , disjunction , negation  , implication  , and bi-implication  which together form the Boolean expressions. Sometimes the variables are called propositional variables or propositional letters and the Boolean expressions are then known as Propositional Logic. Formally, Boolean expressions are generated from the following grammar:                 where ranges over a set of Boolean variables. This is called the abstract syntax of Boolean expressions. The concrete syntax includes parentheses to solve ambiguities. Moreover, as a common convention it is assumed that the operators bind according to their relative priority. The priorities are, with the highest first:  , , ,  ,  . Hence, for example   ! "  !# $# $#  % A Boolean expression with variables &'!( denotes for each assignment of truth values to      the variables itself a truth value according to the standard truth tables, see figure 1. Truth assignments are written as sequences of assignments of values to variables, e.g., )*,+ - .+ / ,+  .+ &0 which assigns to  and  , to  and  . With this particular truth assignment the above expression has value , whereas )*1+ - .+  ,+ 2 ,+ 0 yields .    Figure 1: Truth tables. 54  76 . If we fix an ordering of the variables The set of truth values is often denoted 3 (   of a Boolean expression we can view as defining a function from 3 to 3 where 8 is the number of variables. Notice, that the particular ordering chosen for the variables is essential for what function is defined. Consider for example the expression   . If we choose the   ordering :9; then this is the function < !=#   , true if the first argument implies the  second, but if we choose the ordering >9? then it is the function < @"@#   , true if the second argument implies the first. When we later consider compact representations of Boolean expressions, such variable orderings play a crucial role.  BA Two Boolean expressions and are said to be equal if they yield the same truth value for all truth assignments. A Boolean expression is a tautology if it yields true for all truth assignments; it is satisfiable if it yields true for at least one truth assignment. Exercise 1.1 Show how all operators can be encoded using only  and . Use this to argue that any Boolean expression can be written using only , , variables, and  applied to variables.  A  A Exercise 1.2 Argue that and are equal if and only if  is a tautology. Is it possible to   say whether is satisfiable from the fact that  is a tautology? 2 NORMAL FORMS 7 2 Normal Forms A Boolean expression is in Disjunctive Normal Form (DNF) if it consists of a disjunction of conjunctions of variables and negations of variables, i.e., if it is of the form C  where each NMO   ED2D2D. MO  F& G # H JI ED2D2D.  JI or a negation of a variable  is either a variable JIFLK # D2D2D MO (1) . An example is   =# P Q#  which is a well-known function of and  (which one?). A more succinct presentation of (1) is to write it using indexed versions of and : UT FWV R I X  MO"YZ O M!S  S   Similarly, a Conjunctive Normal Form (CNF) is an expression that can be written as IX UT R WF V  MO"YZ O   M!S S NMO where each is either a variable or a negated variable. It is not difficult to prove the following proposition: Proposition 1 Any Boolean expression is equal to an expression in CNF and an expression in DNF. In general, it is hard to determine whether a Boolean expression is satisfiable. This is made precise by a famous theorem due to Cook [Coo71]: Theorem 1 (Cook) Satisfiability of Boolean expressions is NP-complete. (For readers unfamiliar with the notion of NP-completeness the following short summary of the pragmatic consequences suffices. Problems that are NP-complete can be solved by algorithms that run in exponential time. No polynomial time algorithms are known to exist for any of the NP-complete problems and it is very unlikely that polynomial time algorithms should indeed exist although nobody has yet been able to prove their non-existence.) Cook’s theorem even holds when restricted to expressions in CNF. For DNFs satisfiability is decidable in polynomial time but for DNFs the tautology check is hard (co-NP complete). Although satisfiability is easy for DNFs and tautology check easy for CNFs, this does not help us since the conversion between CNFs and DNFs is exponential as the following example shows.  (  ( Consider the following CNF over the variables [ /" [ !  //!  :  [ #   [ # (  ED2D2D.  [ ( \#   3 BINARY DECISION DIAGRAMS 8 O The corresponding DNF is a disjunction which has a disjunct for each of the 8 -digit binary O from 17 / 71 to 17 / 71 — the ] ’th digit representing a choice of either [ (for numbers ) or  (for ): (_^   (  [  [ [ D2D2D2 [ D2D2D2     (_^  D2D2D2 _(   ^ D2D2D  _([ ^ [ .. . # ([  # ( # (  [ #\ Whereas the original expression has size proportional to 8 the DNF has size proportional to ( 8a` . The next section introduces a normal form that has more desirable properties than DNFs and CNFs. In particular, there are efficient algorithms for determining the satisfiability and tautology questions. Exercise 2.1 Describe a polynomial time algorithm for determining whether a DNF is satisfiable. Exercise 2.2 Describe a polynomial time algorithm for determining whether a CNF is a tautology. Exercise 2.3 Give a proof of proposition 1. Exercise 2.4 Explain how Cook’s theorem implies that checking in-equivalence between Boolean expressions is NP-hard. Exercise 2.5 Explain how the question of tautology and satisfiability can be decided if we are given an algorithm for checking equivalence between Boolean expressions. 3 Binary Decision Diagrams Let >b  [ c be the if-then-else operator defined by >b  [ c    [#   b [  [  d"#   hence, is true if and are true or if is false and  is true. We call the test expression. All operators can easily be expressed using only the if-then-else operator and the constants and . Moreover, this can be done in such a way that all tests are performed only on (un-negated) variables and variables occur in no other places. Hence the operator gives rise to a   # ,   is eb  fb  #$  fb  # . new kind of normal form. For example,  is eb  . Since variables must only occur in tests the Boolean expression is represented as eb An If-then-else Normal Form (INF) is a Boolean expression built entirely from the if-then-else operator and the constants and such that all tests are performed only on variables. 3 BINARY DECISION DIAGRAMS 9  If we by )*1+ 0 denote the Boolean expression obtained by replacing not hard to see that the following equivalence holds: E eb    with  )g.+ 0h i) ,+ 0, in then it is (2) This is known as the Shannon expansion of with respect to . This simple equation has a   lot of useful applications. The first is to generate an INF from any expression . If contains no variables it is either equivalent to or which is an INF. Otherwise we form the Shannon     expansion of with respect to one of the variables in . Thus since )*1+ 0 and )g.+ 0 both   contain one less variable than , we can recursively find INFs for both of these; call them [ and   . An INF for is now simply eb  $   [  We have proved: Proposition 2 Any Boolean expression is equivalent to an expression in INF. jk    d"#   7&# . If we find an INF of Example 1 Consider the Boolean expression   $   d   !   2   _   by selecting in order the variables on which to perform Shannon expansions, we get the expressions [ l  mb  -  [ cjb   [B[ cjb  B $ nb  [B[ $   B[ [B[ nb  BB$  B  [ 7ob  7ob  7ob  7ob    [B[  B  [B[B[  [B[   B [  BB        Figure 2 shows the expression as a tree. Such a tree is also called a decision tree. p A lot of the expressions are easily seen to be identical, so it is tempting to identify them. For     example, instead of B [ we can use [B[B[ and instead of BB we can use [B[  . If we substitute  [B[B[       for B [ in the right-hand side of B and also [B[  for BB , we in fact see that [B[ and B are    identical, and in  we can replace B with [B[ . If we in fact identify all equal subexpressions we end up with what is known as a binary decision diagram (a BDD). It is no longer a tree of Boolean expressions but a directed acyclic graph (DAG).  Applying this idea of sharing, can now be written as: [   [B[  [B[B[  [B[  l      mb  -  [ cjb   [B[ cjb  B[ [  nb  B[ [ $  [B[B[ 7ob  7ob  3 BINARY DECISION DIAGRAMS 10 q,r u/r u/r q7v q7v u$v s u$v t Figure 2: A decision tree for lines high-branches. t u$v    s t cL# t    s t u$v t s _-# . Dashed lines denote low-branches, solid Each subexpression can be viewed as the node of a graph. Such a node is either terminal in the case of the constants and , or non-terminal. A non-terminal node has a low-edge corresponding to the else-part and a high-edge corresponding to the then-part. See figure 3. Notice, that the number of nodes has decreased from w in the decision tree to x in the BDD. It is not hard to imagine that if each of the terminal nodes were other big decision trees the savings would be dramatic. Since we have chosen to consistently select variables in the same order  in the recursive calls during the construction of the INF of , the variables occur in the same orderings on all paths from the root of the BDD. In this situation the binary decision diagram is said to be ordered (an OBDD). Figure 3 shows a BDD that is also an OBDD. Figure 4 shows four OBDDs. Some of the tests (e.g., on  in y ) are redundant, since both the low- and high-branch lead to the same node. Such unnecessary tests can be removed: any reference to the redundant node is simply replaced by a reference to its subnode. If all identical nodes are shared and all redundant tests are eliminated, the OBDD is said to be reduced (an ROBDD). ROBDDs have some very convenient properties centered around the canonicity lemma below. (Often when people speak about BDDs they really mean ROBDDs.) To summarize: 3 BINARY DECISION DIAGRAMS 11 | s z s z s | { z\{ } z@{  ~    _-# with ordering 9€co9‚97 . Low-edges are Figure 3: A BDD for   c"# drawn as dotted lines and high-edges as solid lines. | s | s | s |ƒ{ ~ | { |m„ ~ ~ } a b c ~ d Figure 4: Four OBDDs: a) An OBDD for . b) Another OBDD for with two redundant tests.  with one c) Same as y with one of the redundant tests removed. d) An OBDD for  redundant test. 3 BINARY DECISION DIAGRAMS q q‡†ˆu q‡†‰ 12 q q q u Figure 5: The ordering and reducedness conditions of ROBDDs. Left: Variables must be ordered. Middle: Nodes must be unique. Right: Only non-redundant tests should be present. A Binary Decision Diagram (BDD) is a rooted, directed acyclic graph with Š one or two terminal nodes of out-degree zero labeled 0 or 1, and Š a set of variable nodes ‹ of out-degree two. The two outgoing edges are   given by two functions ŒŽ ‹ # and ‘c’ “‘ ‹ # . (In pictures, these are shown  as dotted and solid lines, respectively.) A variable ”•7– ‹ # is associated with each variable node. A BDD is Ordered (OBDD) if on all paths through the graph the variables respect a given linear order 9—9 D2D2D 9˜( . An (O)BDD is Reduced (R(O)BDD) if Š (uniqueness) no two distinct nodes ‹ and ™ have the same variable name and low- and high-successor, i.e.,            ”•7– ‹ # ”•7– ™ $#  ŽŒ  ‹ # ŒŽ ™ -#  c‘ ’ “‘ ‹ # ‘c’ “‘ ™ # implies ‹ ™ and Š (non-redundant tests) no variable node ‹ has identical low- and highsuccessor, i.e.,    ŒŽ ‹ #›š ‘c’ “‘ ‹ #\ The ordering and reducedness conditions are shown in figure 5. ROBDDs have some interesting properties. They provide compact representations of Boolean expressions, and there are efficient algorithms for performing all kinds of logical on  ( operations 3 b 3 there is ROBDDs. They are all based on the crucial fact that for any function < exactly one ROBDD representing it. This means, in particular, that there is exactly one ROBDD ( for the constant true (and constant false) function on 3 : the terminal node (and in case of false). Hence, it is possible to test in constant time whether an ROBDD is constantly true or false. (Recall that for Boolean expressions this problem is NP-complete.) To make this claim more precise we must say what we mean for an ROBDD to represent a function. First, it is quite easy to see how the nodes ‹ of an ROBDD inductively defines Bœ Boolean expressions : A terminal node is a Boolean constant. A non-terminal node marked with is an if-then-else expression where the condition is and the two branches are the Boolean expressions given by the low- or high-son, respectively: [    œ   ”•7– ‹ #jb ""ž Ÿ /¡ œ'¢  £ ¤B¥¡ œ/¢  if ‹ is a variable node. 3 BINARY DECISION DIAGRAMS 13 Moreover, if n9‚9 D2D2D 9€( is the variable ordering ( of the ROBDD, we œ  Bœ associate with each node ‹ the function < that maps y - y 2// y (1#n¦ 3 to the truth value of )*y  + & y  + // y ( We can now state the key lemma: Lemma 1 (Canonicity( lemma)  For any function < 3 b 3 there is exactly one ROBDD ‹ with variable ordering §9?›9 œ¨  $//"(,# < D2D2D 9( such that < .  Proof: The proof is by induction on the number of arguments of < . For 8 there are only two Boolean functions, the constantly false and constantly true functions. Any ROBDD containing at least one non-terminal node is non-constant. (Why?) Therefore there is exactly one ROBDD for each of these: the terminals and . Assume now that we have proven the lemma for all functions  («@ b of 8 arguments. We proceed 3 be any Boolean function of to show it for all functions of 8‰©ª arguments. Let < 3  [ 8‚© arguments. Define the two functions < and < of 8 arguments by fixing the first argument of < to respectively :    <.¬ 2/'!(«@!# < y "2$!(2«@!# for y ¦ 3 . (Sometimes < [ and <  are called the negative and positive co-factors of These functions satisfy the following equation:   < -//"(,# mb < with respect to  .)   <  //"(,#- < [ 2'!(1#\ (3) Since < [ and <  take only 8 argumentsG we assume by induction that there are unique ROBDD œ'­  [ œ   < and < nodes ‹ [ and ‹  with < < .  œ'­n œ G  œ'­o œ G    [ ‹ < < < < < . There are two cases to consider. If ‹ then < and < [   [ ‹ is an ROBDD for < . It is also the only ROBDD for < since due to the ordering, Hence ‹ if  is at all present in the ROBDD rooted at ‹ ,  would need to be the root node. However,  œ  œ B0  £ ¤J¥¡ œ'¢  œ J0  "ž¯ŸW¡ œ'¢  œ$­  œ G  if  [ [ and < . Since < < < then < < )i,+ < < )®2+ < < < <  by assumption, the low- and high-son of ‹ would be the same, making the ROBDD violate the reducedness condition of non-redundant tests. š  œ ­ š œ G [ If ‹ (using the names 2/'!(«@ in ‹ then < < by the induction hypothesis    , ŒŽ  ‹ #  ‹ [ , and ‘c’ “‘  ‹ #  place of $//!( ). We take ‹ to be the node with ”•7– ‹ # G œ‡ ƒb œ œ$­ œG   œ$­° [ ‹  , i.e., < <œ±  < which is reduced. By assumption < <  and < < therefore using (3) we get < < . Suppose that ™ is some other node with <² < . Clearly, <² must    0  <²_)g.+ J0  <  , a  < 1 ² i ) ,+ depend on  , i.e., <²_)i,+ J0³š <²1)g.+  0 (otherwise also < [      #  ” 7 • – ‹ . Moreover, from contradiction). Due to the ordering this means that ”•7– ™ # G ¢ $ œ ­ ¢ œ  £ ¤J¥¡  [  "ž¯ŸW/¡    ²  < ² < ² < it follows that < < < < and < , which by the induction   #    ‘c’ “‘  ‹ # . From the ‹ [ ŒŽ ‹ # and c ‘ ’  “ ‘ ™ ‹ hypothesis implies that ŒŽ ™ #  ™ .p reducedness property of uniqueness it follows that ‹ An immediate consequence is the following. Since the terminal is an ROBDD for all variable orderings it is the only ROBDD that is constantly true. So in order to check whether an ROBDD is constantly true it suffices to check whether it is the terminal which is definitely a constant time operation. Similarly, ROBDDs that are constantly false must be identical to the terminal . In fact, to determine whether two Boolean functions are the same, it suffices to construct their ROBDDs (in the same graph) and check whether the resulting nodes are the same! + (70 . 3 BINARY DECISION DIAGRAMS 14 The ordering of variables chosen when constructing an ROBDD has a great impact on the     _-# and construct size of the ROBDD. If we consider again the expression   d"# an ROBDD using the ordering ‡9´f9µc¨9µ_ the ROBDD consists of w nodes (figure 6) and not x nodes as for the ordering n9c°9—9?7 (figure 3). | s | { | { z s z s z s z@{ z s z@{ ~ Figure 6: The ROBDD for      d"#  _-# with variable ordering n9€‚9?d°9?7 . Exercise 3.1 Show how to express all operators from the if-then-else operator and the constants and .     7&# Exercise 3.2 Draw the ROBDDs for   cL# n9€‚9—9?do97—97 and n9co9€¶9€7—9—9?7 .     7&# with orderings    _-# with orderings o9—9?co9_ Exercise 3.3 Draw the ROBDDs for   d"# and o9?co9€‚97 . How does it compare with the example in figures 3 and 6? Based on the examples you have seen so far, what variable ordering would you recommend for constructing        7-#  7-# ED2D2D. F   F # ? a small ROBDD for   d"# Exercise 3.4 Give an example of a sequence of ROBDDs ‹ (Q ¸·¹8 which induces exponen tially( bigger decision trees. I.e., if ‹ ( has size º 8 # then the decision tree should have size  º ` #. Exercise 3.5 Construct an ROBDD of maximum size over six variables. 4 CONSTRUCTING AND MANIPULATING ROBDDS »  7  5  ‹  6 4  2  15 Â` Á  3 À xà  & ¾B-¿# ] var ŒŽ ‘c’ “‘ À À Á Á  ` ` Á ` Á À x ‹½b¼ Figure 7: Representing an ROBDD with ordering §9Ä›9?¶9? . The numbers inside the vertices are the identities used in the representation. The numbers and are reserved for the terminal nodes. The numbers to the right of the ROBDD shows the index of the variables in the ordering. The constants are assigned an index which is the number of variables in the ordering  plus one (here Á‚©ª À ). This makes some subsequent algorithms easier to present. The lowand high-fields are unused for the terminal nodes. 4 Constructing and Manipulating ROBDDs In the previous section we saw how to construct an OBDD from a Boolean expression by a simple recursive procedure. The question arises now how do we construct a reduced OBDD? One way is to first construct an OBDD and then proceed by reducing it. Another more appealing approach, which we follow here, is to reduce the OBDD during construction. To describe how this is done we will need an explicit representation of ROBDDs. Nodes will be represented as numbers   ` / with and reserved for the terminal nodes. The variables in the ordering E9Å9 D2D2D 9Å( are represented by their indices  ` /' 8 . »  b  &¾B-¿# The ROBDD is stored in a table which maps a node ‹ to its three attributes  #   #  ¾  # ‹Æ ¼ ¿ ] ”•7– ‹ ] , ŒŽ ‹ , and ‘c’ “‘ ‹ . Figure 7 shows the representation of the ROBDD from figure 3 (with the variable names changed to 9˜¶9˜¶9€ ). 4.1 MK In order to ensure that the OBDD being constructed is reduced, it is necessary to determine from      #  ¾   ¿ a triple ] &¾B-¿# whether there exists a node ‹ with ”•7– ‹ # , and ‘c’ “‘ ‹ #  &¾B-¿# ] b ŒŽ ‹  &¾B-¿# . ] ¼ ‹ mapping triples » ] For this purpose we assume the presence of a table Ç of B ¾  ¿ variable indices ] , and nodes »  È &¾B-¿#to nodes ‹ . The table  Ç is the  “inverse” of the table , i.e., for ] ‹ . The operations needed on the variable nodes ‹ , ‹ # , if and only if, Ç ] ¾J&¿# 4 CONSTRUCTING AND MANIPULATING ROBDDS » 16  M K )  Ç 0 ] &¾B-¿#  ¿ 1: if ¾ then return ¾  2: else if member Ç  ] &¾B-¿# then  3: return lookup Ç  ] ¾J&¿# »  &¾B-¿# 4: else ‹>É add   &¾B-] ¿ # ‹ 5: insert Ç ] Ê.ËdÌ2ÍÎʐÏe‹ 6: Figure 8: The function MK ) »  0  &¾B-¿# Ç ] . two tables are: »   ‹>b¼  » ] &¾B-¿# init # » ‹>É  add   ] &¾B-¿#  ”•7– ‹ #$ ŒŽ ‹ #$ ‘c’ “‘ ‹ #  &¾B-¿# b Ç ]  ¼ ‹ init Ç #  yÉ member Ç  ] &¾B-¿#  &¾B-¿# ‹>É lookup   &¾B-Ç ¿ ] # ‹ insert Ç ] » initialize to contain only and allocate a new node ‹ with attributes » lookup the attributes of ‹ in initialize Ç to be empty  check if ] &¾B-¿# is in Ç  find Ç ] ¾J&¿#  ¾J&¿# make ] map to ‹ in Ç  & ¾B-¿# ]  # . Section 5 We shall assume that all these operations can be performed in constant time, Ð will show how such a low complexity can be achieved. »  The function MK )  Ç 0 ] ¾J&¿# (see figure 8) searches the table Ç for a node with variable index ] and low-, high-branches ¾B-¿ and returns a matching node if one exists. Otherwise it creates a new node ‹ , inserts it into Ç and returns the identity of it. The running time of MK »  # is Ð due to the assumptions on the basic operations on and Ç . The OBDD is ensured to be reduced if nodes are only created through the use of MK. In describing MK and subsequent » algorithms, we make use of the notation )  Ç 0 to indicate that MK depends on the global data » structures and Ç , but we leave out the arguments when invoking it as part of other algorithms. 4.2 B UILD  The construction of an ROBDD from a given Boolean expression proceeds as in the construction of an if-then-else normal form (INF) in section 2. An ordering of the variables Ñ9 D2D2D 9 ( is fixed. Using the Shannon expansion ¨ ¨b  )®2+ J0W  )*,+ J0 , a node for    is constructed by a call to MK, after the nodes for )i,+ J0 and )g.+ B0 have been constructed C  # by recursion. The algorithm is shown in figure 9. BUILD ’ ] constructs an ROBDD O «@-call  4 O ! The //!( 6 . It does so by first recursively for a Boolean expression with variables in O O   constructing ROBDDs ™ [ and ™  for )i,+ 0 and )g.+ 0 in lines 4 and 5, and then proceeding  to find the identity of the node for in line 6. Notice that if ™ [ and ™  are identical, or if there already is a node with the same ] , ™ [ and ™  , no new node is created. 4 CONSTRUCTING AND MANIPULATING ROBDDS » 17 H BUILD )  Ç 0 # C 1: function BUILD’  ] # = 2: if ]ƒÒ€8 then  3: if is false then return 0 else return 1 O H 4: else ™ [ É BUILD ’ )*1+ 0hO  ]@©ª # H ™  É BUILD ’ )®.+ 0h ]©ª # 5: ʐË,Ì.ÍÊÏ MK ]  ™ [  ™ !# 6: 7: end BUILD’ 8: H 9: return BUILD ’  #  Figure 9: Algorithm for building an ROBDD from a Boolean expression using the C ordering ‚9;Ó9 D2D2D 9ª( . In a call BUILD’  ] # , ] is the lowest index that any   variable of can have. Thus when the test ]ÒÔ8 succeeds, contains no variables and must be either constantly false or true. An example of using BUILD to compute an ROBDD is shown in figure 10. The running time of BUILD is bad. It is easy to see ( that for a variable ordering with 8 variables there will always be generated on the order of ` calls . 4.3 A PPLY All the binary Boolean operators on ROBDDs are implemented by the same general algorithm NÕ-Ö  & -# APPLY G Bœ Õ&ÖÑBœ'× ‹ ‹ that for two ROBDDs computes the ROBDD for the Boolean expression . The construction of APPLY is based on the Shannon expansion (2): E eb   )g.+ 0h i) ,+ 0, Observe that for all Boolean operators op the following holds:  eb  -  $ # Õ-Ö> eb  A    A #  >b   &Õ ÖØ A     Õ&ÖÑ A (4) If we start from the root of the two ROBDDs we can construct the ROBDD of the result by recursively constructing the low- and the high-branches and then form the new root from these. Again, to ensure that the result is reduced, we create the node through a call to MK. Moreover, to avoid an exponential blow-up of recursive calls, dynamic programming is used. The algorithm is shown in figure 11.  Dynamic programming is implemented using a table of results Ù . Each entry ] BÚc# is either  empty or contains the earlier computed result of APP ] BÚc# . The algorithm distinguishes between four different cases, the first of them handles the situation where both arguments are terminal nodes, the remaining three handle the situations where at least one argument is a variable node. If both ‹  and ‹  are terminal, a new terminal node is computed having the value of op applied to the two truth values. (Recall, that terminal node is represented by a node with identity and similarly for .) 4 CONSTRUCTING AND MANIPULATING ROBDDS BUILD ’ gà!áNâ$ãà!äBå r â Û®ÛæàçQÞ> d f Û®ÛÝÜßÞ>à!áNâ$ãà!äBå v â Û®Û*ÜQÞ½bÜWâ'ãà"äJåèhâ Û®Û*ÜQÞ½ÜWâ'ã\ÜLå é â 18 Û®Û r Þeà!áNâ$ã\à!äJå v â Û®ÛÝÜßÞ r â$ãcà"äJåèWâ Û®Û*ÜQÞ r â$ã\Ü"å é â Û®Û*ÜßÞ½Ü $â ã r å é â Û®Û r Þ½eÜW$â ãà!äBåŽèhâ Û®Û r Þ½Ü â$ã\Ü"å é â Û®Û*ÜcÞ r â$ã r å é â Û®Û r Þ r â'ãeà"äJåèhâ Û®Û r Þ r â$ã\Ü"å é â ®Û Û r Þ½ÜWâ/ã r åé â Û®Û r Þ r â'ã r å é â a |ƒ{ | „ ~ | „ } ~ b c | { d | { | { | „ | s | { | { | „ } ~ } ~ } | „ ~ e  f } ~ g Figure 10: Using BUILD on the expression   $#  . (a) The tree of calls to BUILD . (b) ! # .  # . (c) After the call BUILD’ " Ñ # .  # . The ROBDD after the call BUILD’ Ñ ! 2 ` # . (e) After the calls BUILD’ ! ˆ # 2  # and (d) After the call BUILD’ ± $# " # 2  # . (f) After the call BUILD’ ! ‡ $# 2 ` # . (g) The final result. BUILD ’ › 4 CONSTRUCTING AND MANIPULATING ROBDDS » 19 hÕ&Ö  ‹  ‹ -# A PPLY )  Ç 0  # 1: init Ù 2:   3: ê Í%ÏÎë7Ì.ìCí@Ï APP ‹ - ‹ #    4: ìCêÙ ‹ - ‹ &#‡š empty Ì.îËßÏeÊ.Ë,Ì.ÍÎʐϱ٠‹ - ‹ -# 4 4  _6òÏÎóô‹ §¦  76oÌ.îÎËcÏ u É Õ-Ö ‹ - ‹ -# 5: Ëcïhð'ËñìCêo‹ o¦    -# 6: Ëcïhð'ËñìCê var ‹ "#  var  "#-‹ Ì.îÎ  ËcÏ  "#$  -#!#-   "#- Ž Œ    ‹ 7: u É MK var ‹ APP ŒŽ ‹ APP ‘c’ “‘ ‹   -# 8 Ëcïhð'ËñìCê var ‹ " #n9 var  ‹ Ì.îÎ  ËcÏ    9 u É MK var ‹ "#- APP ŒŽ ‹ "#$ ‹ -#- APP ‘c’ “‘ ‹ "#- ‹ -#!# õ  "#  -# õ # 10: Ëcïhð'Ë var ‹  Ò  var-#- ‹  -  -#!#-  -  11: APP ‹ ‘c’ “‘ ‹ &#!#!#  -u É -# MK var ‹ APP ‹ ŒŽ ‹ 12: Ù ‹ ‹ É u 13: Ê.Ë,Ì.ÍÎÊÏ u 14: ËcÏÎó APP 15:  16: return APP ‹ - ‹ -# Figure 11: The algorithm APPLY )  ‘c’ “‘ ‹ &#!#"# »  0 hÕ&Ö  &   # Ç ‹ ‹ . If at least one of ‹  and ‹  are non-terminal, we proceed according to the variable index. If the nodes have the same index, the two low-branches are paired and APP recursively computed on them. Similarly for the high-branches. This corresponds exactly to the case shown in equation (4). If they have different indices, we proceed by pairing the node with lowest index with the low- and high-branches of the other. This corresponds to the equation  O b  $  -# 5 op O b     op   op (5)  which holds for all . Since we have taken the index of the terminals to be one larger than the     index of the non-terminals, the last two cases, ”•7– ‹ "#n9 ”•7– ‹ -# and ”•7– ‹ "# ÒԔ•7– ‹ -# , take account of the situations where one of the nodes is a terminal. Figure 12 shows an example of applying the algorithm on two small ROBDDs. Notice how pairs of nodes from the two ROBDDs are combined and computed. To analyze the complexity of APPLY we let  ‹  denote the number of nodes that can be reached from ‹ in the ROBDD. Assume that Ù can be implemented with constant lookup and insertion times. (See section 5 for details on how to achieve this.) Due to the dynamic programming at most  ‹ 2 ‹ _ calls to A PPLY are generated. Each call takes constant time. The total  running time is therefore Ð  ‹ /2 ‹ _¯# . 4.4 R ESTRICT The next operation we consider is the restriction of a ROBDD ‹ . That is, given a truth asBœ signment, for example )i,+ 2 .+ ö 2+ ÷!0 , we want to compute the ROBDD for under this 4 CONSTRUCTING AND MANIPULATING ROBDDS ü ø-ù 5 3 9 5 ø× 7 6 4 3 ø-ú 4 ø$û 2 0 ý øG 8 20 7 8 5 6 3 4 2 2 0 1 1 1 0 øG 8,5 6,3 5,3 0,3 3,2 4,0 2,2 1,1 0,2 0,0 0,1 0,2 2,0 0,0 0,0 1,0 ø× 7,4 0,4 0,0 0,1 øù 5,4 0,2 3,0 2,0 ø-ú 4,2 0,1 0,2 2,2 0,0 Figure 12: An example of applying the algorithm APPLY for computing the conjunction of the two ROBDDs shown at the top left. The result is shown to the right. Below the tree of arguments to the recursive calls of APP. Dashed nodes indicate that the value of the node has previously been computed and is not recomputed due to the use of dynamic programming. The solid ellipses show calls that finishes by a call to MK with the variable index indicated by the variables to the right of the tree. ø$û 4 CONSTRUCTING AND MANIPULATING ROBDDS » 21  R ESTRICT )  Ç 0 ‹ BÚ1 y # =  1: function res ‹ # =  # Ú ìNꛔ•7– ‹ Ò  Ì2îÎËcÏeʐË,Ì.ÍʐÏ>‹ 2: Ú Ì.îËcϱÊ.Ë,Ì.ÍÊ_Ï MK  ”•7–  ‹ #$ res  ŒŽ ËßïNð/ËÓìC궔•7–  ‹ #o9 3:    ËßïNð/Ë (* ”•7–  ‹ #  Ú *) ìCêy §Ì.îÎËcÏeÊ.ËdÌ2 ÍÎÊÏ res ŒŽ 4:  # 1 Ú  " # # ËßïNð/Ë (* ”•7– ‹ y 5: *) Ê.Ë,Ì.ÍÎÊÏ res ‘c’ “‘ ‹ 6: end res  7: return res ‹ # Figure 13: The algorithm RESTRICT )  "# #$   ‹ res ‘c’ “‘ ‹ #"#!#  #!# ‹ »  0   Ú1 # Bœ Ç ‹ y which computes an ROBDD for ) Ú 7+ y 0 . œ restriction, i.e., find the ROBDD for )i,+  2+ ö .+ ÷!0 . As an example consider the ROBDD  of figure 10(g) (repeated below to the left) representing the Boolean expression   -#  .  Restricting it with respect to the truth assignment )i,+ 0 yields an ROBDD for   -# . It is constructed by replacing each occurrence of a node with label  by its left branch yielding the ROBDD at the right: x1 x2 x2 x1 x3 1 x3 0 1 0 The algorithm again uses MK to ensure that the resulting OBDD is reduced. Figure 13 shows the 4  algorithm in the case where only singleton truth assignments ( )*y$+ M 0 , y ¦  BÚ1 #  76 )Ú are allowed. Intuitively, in computing RESTRICT ‹ y we search for all nodes with ”•7– and replace them by their low- or high-son depending on y . Since this might force nodes above the point of replacemen to become equal, it is followed by a reduction (through the calls to MK). Due to the two recursive calls in line 3, the algorithm has an exponential running time, see exercise 4.7 for an improvement that reduces this to linear time. 4.5 S AT C OUNT, A NY S AT, A LL S AT In this section we consider operations to examine the set of satisfying truth assignments of a Bœ node ‹ . A truth assignment þ satisfies a node ‹ if )iþ 0 can be evaluated to using the truth  tables of the Boolean operators. Formally, the satisfying truth assignments is the set sat ‹ # : ø G   ø   sat ø G  ø    œ 0  # ÿ4 ¦ ‹ þ 3 i) þ is true 6  4 where 3 the set of all truth assignments for variables -//"( 6 , i.e., func4 $denotes $!( 6 to the truth values 3  4  76 . The first algorithm, SAT COUNT, comtions from  putes the size of sat ‹ # , see figure 14. The algorithm exploits the following fact. If ‹ is a node 4 CONSTRUCTING AND MANIPULATING ROBDDS 22 »  S AT C OUNT ) 0 ‹ #  1: function count ‹ #  2: if ‹ then res É  3: else if ‹ then res É ^ ¡£ ¤B¥¡ œ'¢ ¢ 4: else res É `  ^   ¡ œ'¢ õ count ŒŽ ‹ #"#   ^  ^  ¡®"ž Ÿ ¡ œ'¢ ¢ ©;`    ¡ œ'¢ õ count  ‘c’ “‘  ‹ #!# 5: 6: 7: 8: return res end count return `  ¡ œ'¢ ^ õ count  # ‹ Figure 14: An algorithm for determining the number of valid truth assignments. Recall, that the “variable index” ”•7– of and in the ROBDD representation is 8ˆ©Ä when  # the ordering  # contains 8 variables (numbered through 8 ). This means that var and var always gives 8 ©; .  œ with variable index ”•7– ‹ # then two sets of truth assignments can make < true. The first set has ”•7–_‹ equal to , the other has ”•7–.‹ equal to . For the first set, the number is found by find   ing the number of truth assignments count ŒŽ ‹ #"# making ŒŽ ‹ # true. All variables between    ”•7– ‹ # and ”•7– ŒŽ ‹ #!¡£ # ¤B¥in¡ œ'the ^ can be chosen arbitrarily, therefore in the case of ”•7–‹ ¢¢ ^ ordering being , a total of `     ¡ œ'¢ õ count  ŒŽ  ‹ #"# satisfying truth assignments exists. To be efficient, dynamic programming should be applied in S AT C OUNT (see exercise 4.10). A NY S AT 1: 2: 3: 4:  # ‹  if ‹ then Error  0 else if ‹  # then  return ) ¡ œ'¢ else if ŒŽ ‹ then return )    b  ¡ œ'¢ ¼ else return ) A NY S AT ŒŽ    #"#J0 b  ¼ !# #J0 A NY SAT ‘c’ “‘ ‹ ‹ Figure 15: An algorithm for returning a satisfying truth-assignment. The variables are assumed to be $//!( ordered in this way. The next algorithm A NY S AT in figure 15 finds a satisfying truth assignment. Some irrelevant variables present in the ordering might not appear in the result and they can be assigned any value whatsoever. A NY S AT simply finds a path leading to 1 by a depth-first traversal, prefering somewhat arbitrarily low-edges over high-edges. It is particularly simple due to the observation that if a node is not the terminal 0, it has at least one path leading to 1. The running time is clearly linear in the result. A LL S AT in figure 16 finds all satisfying truth-assignments leaving out irrelevant variables  from the ordering. A LL S AT ‹ # finds all paths from a node ‹ to the terminal . The running time is linear in the size of the result multiplied with the time to add the single assignments )   ¡ œ/¢ b¼ 0 and )   ¡ œ'¢ b¼ 0 in front of a list of up to 8 elements. However, the result can be  œ  exponentially large in  ‹  , so the running time is the poor Ð ` 8 # . 4 CONSTRUCTING AND MANIPULATING ROBDDS 23  A LL S AT ‹ #  1: if ‹ then return   2: else if ‹ then return  ) 0  3: else return  add )   ¡ œ'¢ b¼ 0 in front of all  4: 5: truth-assignments in A LL S AT ŒŽ ¡ œ'¢ b¼ 0 in front of all 6: add )    7: truth-assignments in A LL S AT ‘c’ “‘ ‹ !# #-  #!# ‹  Figure 16: An algorithm which returns all satisfying truth-assignments. The variables are assumed to be $L( ordered in this way. We use LD2D2D to denote sequences of truth assignments. In particular,  is the empty sequence of truth assignments, and  ) 0  is the sequence consisting of the single empty truth assignment.   [  "# ] ‹ C  ‹ BUILD # hÕ&Ö A PPLY  ‹ 2 ‹  #  R ESTRICT ‹ BÚ1 y #  S AT C OUNT ‹ #  # A NY S AT ‹  A LL S AT ‹ # ! S IMPLIFY  ‹ # MK  Ð  (# Ð ` # Ð   ‹ 2 ‹ _i# Ð   ‹ i# Ð   Ö ‹ i# Ð   ¯# õ Ð   !  8 # Ð  Ž ‹ i# See note See note Ö½  ' #  Ö     # 8 ‹ Ð ‹ ,   ¾C¾  ' ‹ # ,    Ð  `  œ  # See note Note: These running times only holds if dynamic programming is used (exercises 4.7, 4.10, and 4.12). Table 1: Worst-case running times for the ROBDD operations. The running times are the expected running times since they are all based on a hash-table with expected constant time search and insertion operations. 4.6 S IMPLIFY The final algorithm called S IMPLIFY is shown in figure 17. The algorithm is used to simplify ! an ROBDD by trying to remove nodes. The simplification is based on a domain of inter! est. The ROBDD ‹ is supposed to be of interest only on truth assignments that also satisfy . (This occurs when using ROBDDs for formal verification. Section 7 shows how to do formal verification with ROBDDs, but contains no example of using S IMPLIFY.) ! A To be precise, given and ‹ , S IMPLIFY finds another ROBDD ‹ , typically smaller than ‹ , "  œ 5"  œ# such that . It does so by trying to identify sons, and thereby making some nodes redundant. A more detailed analysis is left to the reader. The running time of the algorithms of the previous sections is summarized in table 1. 4 CONSTRUCTING AND MANIPULATING ROBDDS 24 ! S IMPLIFY  ‹ # $! 1: function sim  ‹ # !Ñ then return 2: if 3: else if ‹P·µ then return ‹ !Ñ then 4: else if   !   5: return MK ”•7– ‹ #$ sim  ŒŽ ‹ #"#$ sim $! #   # 6: else if ”•7– $! #  ”•7– ‹ then  $! 7: if ŒŽ then return sim ‘c’ “‘ #- $!   8: else if ‘c’ “‘ #  then  #$ return sim ŒŽ 9: else return MK ”•7– ‹  $! #$  #!#$ 10: sim ŒŽ  $! #- ŒŽ ‹  #!#"# 11: ‘c’ “‘ ‘c’ “‘ ‹ $! #o9  sim # 12: else if ”•7–  ”•7– $‹ ! then  ! #- #$  13: return MK ”•7– #$ sim ŒŽ ‹ sim 14: else   !   15: return MK ”•7– ‹ #$ sim  ŒŽ ‹ #"#$ sim 16: end sim 17: ! 18: return sim  ‹ # !  ‘c’ “‘  ‹ #"#!#  ‘c$! ’ “‘ ‹ #!#  #- ŒŽ ‹ #"#  ! -#  #!# ‹ !  ‘c’ “‘  ‹ #"#!# ‘c’ “‘ Figure 17: An algorithm (due to Coudert et al [CBM89] ) for simplifying an ROB! DD y that we only care about on the domain . Dynamic programming should be applied to improve efficiency (exercise 4.12) 4 CONSTRUCTING AND MANIPULATING ROBDDS 4.7 25 Existential Quantification and Substitution When applying ROBDDs often existential quantification and composition is used. Existential  quantification is the Boolean operation %  . The meaning of an existential quantification of a Boolean variable is given by the following equation: %  E  )i,+ 0  )®2+ 0, (6) On ROBDDs existential quantification can therefore be implemented using two calls to R E STRICT and a single call to A PPLY . Composition is the ROBDD operation performing the equivalent of substitution on Boolean  A expression. Often the notation ) + 0 is used to describe the result of substituting all free oc BA currences of in by . (An occurrence of a variable is free if it is not within the scope of a quantifier.)1 To perform this substitution on ROBDDs we observe the following equation,  which holds if contains no quantifiers:   A 0    A b  0   A b  0W  0W ) + ) ,+ )®2+ )*,+ (7) CBA b  0W  0 #  HB A  0H#  BA  0H# ®) .+ )i,+ )®2+  *) 1+ Since we can compute this with two  applications of RESTRICT and three applications of APPLY (with the operators ,  # , ). However, by essentially generalizing better (see exercise 4.13). APPLY Exercises Exercise 4.1 Construct the ROBDD for the algorithm BUILD in figure 9.   to operators op with three arguments we can do    $# with ordering §9?›9Ä using  Exercise 4.2 Show the representation of the ROBDD of figure 6 in the style of figure 7. C Exercise 4.3 Suggest an improvement BUILD C ONJ # of BUILD which generates only a linear  number of calls for Boolean expressions that are conjunctions of variables and negations of variables.   using whatever ordering you want. Exercise 4.4 Construct the ROBDDs for and Compute the disjunction of the two ROBDDs using APPLY .  Exercise 4.5 Construct the ROBDDs for   $# and  n9€‚9 . Use APPLY to find the ROBDD for    -#  using BUILD with the ordering   -# . Exercise 4.6 Is there any essential difference in running time between finding RESTRICT  and RESTRICT y  8  # when the variable ordering is 9˜¶9 D2D2D 9( ?    # y Exercise 4.7 Use dynamic programming to improve the running time of R ESTRICT. 1 Since ROBDDs contain no quantifiers we shall not be concerned with the problems of free variables of being bound by quantifiers of . & &(' 5 IMPLEMENTING THE ROBDD OPERATIONS Exercise 4.8 Generalise RESTRICT to arbitrary O O truth O assignments O ) y  0 . It might be convenient to assume that G 9 × 9 D2D2D 9  . 26 OG  O O  O O  y G , × y × ,   ,  Exercise 4.9 Suggest a substantially better way of building ROBDDs for (large) Boolean expressions than BUILD . Exercise 4.10 Change S AT C OUNT such that dynamic programming is used. How does this change the running time? Exercise 4.11 Explain why dynamic programming does not help in improving the running time of A LL S AT. Exercise 4.12 Improve the efficiency of S IMPLIFY with dynamic programming.  Exercise 4.13 Write the algorithm C OMPOSE ‹ .! ‹ -# for computing the ROBDD of ‹  )i‹  + 0 efficiently along the lines of APPLY . First generalize APPLY to operators op with three arguments (as for example the if-then-else operator), utilizing once again the Shannon expansion. Then use equation 7 to write the algorithm. 5 Implementing the ROBDD operations There are many choices that have to be taken in implementing the ROBDD operations. There is no obvious best way of doing it. This section gives hints for some reasonable solutions. » First, the node table is an array as shown in figure 7. The only problem is that the size of the array is not known until the full BDD has been constructed. Either a fixed upper bound could be assumed, or other tricks must be applied (for example dynamic arrays [CLR90, sec. 18.4]). The table Ç could be implemented as a hash-table using for instance the hash function ¿  ]  ™ß  ™ #  pair  ]  pair  ™c  ™ "# # mod ) where pair is a pairing function that maps pairs of natural numbers to natural numbers and ) a prime. One choice for the pairing function is   pair ]  Úß#  is  ]© Úc# ]@© Ú ©ª # © ] ` which is a bijection, and therefore “perfect”: it produces no collisions. As usual with hash-tables we have to decide on the size as a prime ) . However, since the size of Ç grows dynamically it can be hard to find a good choice for ) . One solution would be to take ) very large, for   example ) 2À_Á*,À+*7x (which is the 1000000’th prime number), and then take as the hashing function ¿ A  ]  ™ß  ™ #  ¿  ]  ™c  ™ # mod ` F F using a table of size ` . Starting from some reasonable small value of , we could increase the F table when it contains ` elements by adding one to , , construct a new table and rehash all elements into this new table. (Again, see for example [CLR90, sec. 18.4] for details.) For such  # . a dynamic hash-table the amortized, expected cost of each operation is still Ð The table Ù used in A PPLY could be implemented as a two-dimensional array. However, it turns out to be very sparsely used – especially if we succeed in getting small ROBDDs –   and it is better to use a hash-table for it. The hashing function used could be - ™c  ™ # Ö     # ] ™c ™ mod ) and as for Ç a dynamic hash-table could be used. 6 EXAMPLES OF PROBLEM SOLVING WITH ROBDDS 27 6 Examples of problem solving with ROBDDs This section will describe various examples of problems that can be solved with an ROBDDpackage. The examples are not chosen to illustrate when ROBDDs are the best choice, but simply chosen to illustrate the scope of potential applications. 6.1 The 8 Queens problem A classical chess-board problem is the 8 queens problem: Is it possible to place 8 queens on a chess board so that no queen can be captured by another queen? To be a bit more general we could ask the question for arbitrary . : Is it possible to place . queens safely on a .0/1. chess board? To solve the problem using ROBDDs we must encode it using Boolean variables. We O  do this by introducing a variable for each position on the board. We name the variables as M ñ· ] BÚ ·2. where ] is the row and Ú is the column. A variable will be 1 if a queen is placed on the corresponding position. 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 The capturing rules for queens require that no other queen can be positioned on the same row, column, or any of the diagonals. This we can express as Boolean expressions: For all ] BÚ , O X O I  3 I 53 4  I7,S 6 M X O M   3 354 O  F M F  F S6 X O O M   3 354  3 « ^ O 53 4 O  8F  M « F ^ F  M F  F S6 X O O M   3 354  3 « O ^ 53 4 O  F8 M « ^ F F  M F  F S6 Moreover, there must be a queen in each row: For all ] , O O O :D2D2D 4 M   6 EXAMPLES OF PROBLEM SOLVING WITH ROBDDS 28 | z : xor ;=< 9 : ;+> xor ? Figure 18: A full-adder Taking the conjunction of all the above requirements, we get a predicate Sol 4 the configurations that are solutions to the . queens problem. A\#@ true at exactly A@ Exercise 6.1 (8 Queens Problem) Write a program that can find an ROBDD for Sol 4 \# when  given . as input. Make a table of the number of solutions to the . queens problem for . à   `   Á  À  x   *  When there is a solution, give one. 6.2 Correctness of Combinational Circuits O A full-adder takes as arguments two bits and  and an incoming carry bit B . It produces as õ   ©FB O , output a sum bit C and an outgoing carry bit BD . The requirement is that `  B  D E © C © O in other words BD is the most significant bit of the sum of ! , and B , and C the least significant bit. The requirement can be written down as a table for BD and a table for C in terms of values of  , and B O . From such a table it is easy to write down a DNF for BD and C . At the normal level of abstraction a combinational circuit is nothing else than a Boolean expression. It can be represented as an ROBDD, using BUILD to construct the trivial ROBDDs for the inputs and using a call to A PPLY for each gate. Exercise 6.2 Find DNFs for BGD and C . Verify that the circuit in figure 18 implements a one bit full-adder using the ROBDD-package and the DNFs. 6.3 Equivalence of Combinational Circuits As above we can construct an ROBDD from a combinational circuit and use the ROBDDs to show properties. For instance, the equivalence with other circuits. 7 VERIFICATION WITH ROBDDS 29 Exercise 6.3 Verify that the two circuits in figure 19 are not equivalent using ROBDDs. Find an input that returns different outputs in the two circuits. 7 Verification with ROBDDs One of the major uses of ROBDDs is in formal verification. In formal verification a model of a system H is given together with some properties I supposed to hold for the system. The task is to determine whether indeed H satisfy I . The approach we take, in which we shall use an algorithm to answer the satisfaction problem, is often called model checking. We shall look at a concrete example called Milner’s Scheduler (taken from Milner’s book [Mil89]). The model consists of . cyclers, connected in a ring, that co-operates on starting and detecting termination of . tasks that are not further described. The scheduler must make sure that the . tasks are always started in order but they are allowed to terminate in any order. This is one of the properties that has to be shown to hold for the model. The cyclers try to fulfill this by passing a token: the holder of the token is the only process allowed to start its task. O All cyclers are similar except that one of them has the token in the initial state. The cyclers cyc , · ] ·J. are O O in a state-based  O -¿ described  O fashion as small transition systems over the Boolean variables , and B . The variable is whenO task ] is running and when it is O ¿ terminated; is when cycler ] has a token, otherwise; B is when cycler ]K¸ hasO put down  the token and cycler ] not yet picked it up. Hence a cycler starts a task by changing from to O , and detects O its termination when is again changedO back to ; and it picks up the token by changing B from to and puts it down by changing B «@ from to . The behaviour of cycler ] is described by two transitions: if B if ¿ O  O  O    O  O -¿ OB ¡ mod 4 then then B O :=   «¢ @ -¿ O :=  The meaning of a transition “if condition then assignment” is that, if the condition is true in some state, then the system can evolve O to a new O state performing the (parallel) assignment.  O Hence, if the system is in a state where is and is then we can simultaneously set to , B O O B to and ¿ to . The transitions are encoded by a single predicate over the value of the variables before the transitions (the pre-state) O  the values after the transition (the post-state). The @ variables in  O -¿ O  and the pre-state are the B ¸· ]Ø·L. which we shall@ A collectively refer to as and in the BAO -¿ AO  AO  post-state B ¨·;]ƒ·2. , which we shall refer to as . Each transition is an atomic action that excludes any other action. Therefore in the encoding we shall often have to say that a lot @ of variables are unchanged. Assume that  is a subset of the unprimed variables . We shall @ @A use a predicate unchanged M over Î which ensures that all variables in  are unchanged. It is defined as follows: X   A unchangedM def øNM  It is slightly more convenient to use the predicate assigned M # O unchangedøGO P M # which express A that every variable not in  is unchanged. We can now define I , the transitions of cycler ] over 7 VERIFICATION WITH ROBDDS | s 30 : 9 z s nor | { : S : 9 z { nor | s z s : Q : Q | { z { 9 : Q : Figure 19: Two circuits used in exercise 6.3 R 7 VERIFICATION WITH ROBDDS 31 TG VG Tú UG V× U× Uú Vú Uù T× Vù Tù Figure 20: Milner’s Scheduler with 4 cyclers. The token is passed clockwise from B to B  and back to B  @ @A the variables Î I  to B  to B  as follows: O  def O  O B O ¸  ¿ BAO ¿ AO B A¡ O mod 4 ¢ @«  P ¿ AO O PB AO The signalling of termination ofO task ] , by changing is modeled by . transitions a  Ó·;]m·2. : O  O  a O def ¸  O   AO assigned  Y  Z  # W$X X X assigned mod \^]`_ W [ X G Z  # X from to performed by the environment assigned Y X expressing the transitions if then O . Now, O at any given state the system can perform one of the transitions from one of the I ’s or the a ’s, i.e., all possible transitions are given by » the predicate : »  I  :D2D2D2bI ( ca  :D2D2D2ba (n def In the initial state we assume that all tasks are stopped, no cycler has a token and only place ( B  ) has a token. Hence the initial state can be characterized by the predicate d over the @ unprimed variables given by: d  @ def  @ @ ô ¿ cB  PeB  :D2D2D.ôeB 4P O (Here  applied to a vector means the conjunction of  applied to each coordinate .) The predicates describing Milner’s Scheduler are summarized in figure 21. Within this setup we could start asking a lot of questions. For example, 1. Can we find a predicate f over the unprimed variables characterizing exactly the states that can be reached from d ? f is called the set of reachable states. 2. How many reachable states are there? 3. Is it the case that in all reachable states only one token is present? 7 VERIFICATION WITH ROBDDS unchangedM assigned M # O I   def def def a »  O   def def  d def g øNM 32  A unchangedøGO P  O  B¿ O ô O BAO P R O I O  3 354 @ @  ¸ ¿ #  O M  AO AO ¿ AO ô  B B OA mod 4 @«  ¸ ¿ AO assignedY O ca X assigned  Y  Z # W(X X X assigned mod \^_ WX cB  PB  D2D2D¸B 4 Figure 21: Milner’s Scheduler as described by the transition predicate predicate d . 4. Is task O always only started after  O ^ » G Z # X and the initial-state ? 5. Does Milner’s Scheduler possess a deadlock? I.e., is there a reachable state in which no transitions can be taken? To answer these questions we first have to compute f . Intuitively, f must be the set of states » that either satisfy d (are initial) or within a finite number of transitions can be reached from d . This an  F iterative algorithm for computing f as an increasing chain of approximations [ suggest f  f // f / Step , of the algorithm find states that with less than , transitions F «@ can be [  reached from d . Hence, we take f the constantly false predicate and compute f as the F » disjunction of d and the set of states which from one transition of can be reached from f . Figure 22 illustrates the computation of f .  How do we compute this with ROBDDs? We start with the ROBDD f 0 . At any » point in the computation the next approximation is computed by the disjunction of d and A composed with the previous approximation f . We are done when the current and the previous approximations coincide: R EACHABLE -S TATES 1: f´É 0 2: repeat f AÉ f  3: f´A=Éh 4:  d‡ % f 5: until f 6: return f 7.1 Knights tour   »  ƒ@ @ A # d @ » bf # ) @ + @ A 0 O  denote the presence Using the same encoding of a chess board as in section 6.1, letting M  BÚc# of a Knight at position ] we can solve other problems. We can encode moves of a Knight as  transitions. For each position, 8 moves are possible if they stay on the board. A Knight at ] BÚc#   can be moved to any one of ]i BÚ i:` #$ ]i:` BÚ i # assuming they are vacant and within the 7 VERIFICATION WITH ROBDDS 33 Full state space jlknm s m { m „ . . . m Figure 22: Sketch of computation of the reachable states  4ß BÚ and ,  ¾ with Ó·, & ¾ 2 · . and , &¾N#n¦ ]Giô B Ú ½ i ` #$  ]Gi½` B Ú ô i #6: X O O O  OA  #M # H M  F I  def M ¸ F8 I P OA M AF I O #M # O ¡ #  M # ¢ N6 ¡  M ¢  ¡ FG I ¢  » @ @A Hence, the transitions are given as the predicate  # : board boundary. For all ] »  @ @ A #  R def O F M I H O O p o o p O o o  3  M  F8 I 354  ¡ FG I ¢ N ¡   M  ¢  ¡   M  ¢  Exercise 7.1 (Knight’s tour) Write a program to solve the following problem using the ROBDDpackage: Is it possible for a Knight, positioned at the lower left corner to visit all positions on an .q/r. board? (Hint: Compute iteratively all the positions that can be reached by the Knight.) Try it for various . . Exercise 7.2 Why does the algorithm R EACHABLE -S TATES always terminate?  Exercise 7.3 In this exercise we shall work with Milner’s Scheduler for . Á . It is by far be the most convenient to solve the exercise by using an implementation of an ROBDD package. a) Find the reachable states as an ROBDD f . b) Find the number of reachable states. 8 PROJECT: AN ROBDD PACKAGE 34 c) Show that in all reachable states at most one token is present on any of the placeholders B $// B 4 by formulating a suitable property I and prove that fÔ I . d) Show that in all reachable states Milner’s Scheduler can always perform a transition, i.e., it does not possess a deadlock. Exercise 7.4 Complete the above exercise by showing that the tasks are always started in sequence  ` /' .   ` / Exercise 7.5 Write a program that given an . as input computes the reachable states of Milner’s Scheduler with . cyclers. The program should write out the number of reachable states      / (using S AT C OUNT). Run the program for . ` Á x * 2 Measure the running times and draw a graph showing the measurements as a function of . . What is the asymptotic running time of your program? 8 Project: An ROBDD Package This project implements a small package of ROBDD-operations. The full package should contain the following operations: I NIT  # 8 Initialize the package. Use 8 variables numbered through 8 .  P RINT ‹ # Print a representation of the ROBDD on the standard output. Useful for debugging. MK  & ¾B-¿# ]       Return the number ‹ of a node with ”•7– ‹ # ]  ŒŽ ‹ # ¾J ‘c’ “‘ ‹ # ¿ . This could be an existing node, or a newly created node. The reducedness of the ROBDD should not be violated. C BUILD # Construct an ROBDD from a Boolean expression. You could restrict yourself to the expressions or  or finite conjunctions of these. (Why?)  A PPLY op  ‹ - ‹ -# Construct the ROBDD resulting from applying op on ‹   and ‹  . R ESTRICT ‹ BÚ1 y # Restrict the ROBDD ‹ according to the truth assignment  S AT C OUNT ‹ #  Return the number of elements in the set sat numbers such as floating point numbers.)  A NY S AT ‹ # Return a satisfying truth assignment for ‹ )iy$+ M 0 . ‹ # . (Use a type that can contain very large REFERENCES Sub-project 1 35 » Implement the tables and Ç with their operations listed in section 4. On top of these imple   ment the operations I NIT 8 # , P RINT ‹ # , and M K ] ¾J&¿# . Sub-project 2 Continue implementation of the package by adding the operations BUILD Sub-project 3 Finish your implementation of the package by adding R ESTRICT  A NY S AT ‹ # . C #  and A PPLY op  ‹ &  ‹ & # .  B Ú1 #  ‹ y , SAT COUNT ‹ # , and References [AH97] Henrik Reif Andersen and Henrik Hulgaard. Boolean Expression Diagrams. In Proceedings, Twelfth Annual IEEE Symposium on Logic in Computer Science, pages 88–98, Warsaw, Poland, June 29–July 2 1997. IEEE Computer Society. [Bry86] Randal E. Bryant. Graph-based algorithms for Boolean function manipulation. IEEE Transactions on Computers, 8(C-35):677–691, 1986. [Bry92] Randal E. Bryant. Symbolic Boolean manipulation with ordered binary-decision diagrams. ACM Computing Surveys, 24(3):293–318, September 1992. [CBM89] Olivier Coudert, Christian Berthet, and Jean Christophe Madre. Verification of synchronous sequential machines based on symbolic execution. In J. Sifakis, editor, Automatic Verification Methods for Finite State Systems. Proceedings, volume 407 of LNCS, pages 365–373. Springer-Verlag, 1989. [CLR90] Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest. Introduction to Algorithms. McGraw-Hill, 1990. [Coo71] S.A. Cook. The complexity of theorem-proving procedures. In Proceedings of the Third Annual ACM Symposium on the Theory of Computing, pages 151–158, New York, 1971. Association for Computing Machinery. [Mil89] Robin Milner. Communication and Concurrency. Prentice Hall, 1989.