kernel.c 42.1 KB
Newer Older
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1
/*========================================================================
2
	       Copyright (C) 1996-2002 by Jorn Lind-Nielsen
3
			    All rights reserved
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

    Permission is hereby granted, without written agreement and without
    license or royalty fees, to use, reproduce, prepare derivative
    works, distribute, and display this software and its documentation
    for any purpose, provided that (1) the above copyright notice and
    the following two paragraphs appear in all copies of the source code
    and (2) redistributions, including without limitation binaries,
    reproduce these notices in the supporting documentation. Substantial
    modifications to this software may be copyrighted by their authors
    and need not follow the licensing terms described here, provided
    that the new terms are clearly indicated in all files where they apply.

    IN NO EVENT SHALL JORN LIND-NIELSEN, OR DISTRIBUTORS OF THIS
    SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
    INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS
    SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE AUTHORS OR ANY OF THE
    ABOVE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    JORN LIND-NIELSEN SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
    BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
    ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO
    OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
    MODIFICATIONS.
========================================================================*/

/*************************************************************************
31
  $Header: /Volumes/CVS/repository/spot/spot/buddy/src/kernel.c,v 1.6 2007/09/19 18:58:20 adl Exp $
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
32
33
34
35
36
37
  FILE:  kernel.c
  DESCR: implements the bdd kernel functions.
  AUTH:  Jorn Lind
  DATE:  (C) june 1997

  WARNING: Do not use pointers to nodes across makenode calls,
38
	   as makenode may resize/move the nodetable.
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

*************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <assert.h>

#include "kernel.h"
#include "cache.h"
#include "prime.h"

/*************************************************************************
  Various definitions and global variables
*************************************************************************/

/*=== EXTERNAL VARIABLES FOR PACKAGE USERS =============================*/

/*
NAME    {* bddtrue *}
SECTION {* kernel *}
SHORT   {* the constant true bdd *}
PROTO   {* extern const BDD bddtrue; *}
DESCR   {* This bdd holds the constant true value *}
ALSO    {* bddfalse, bdd\_true, bdd\_false *}
*/
const BDD bddtrue=1;                     /* The constant true bdd */

/*
NAME    {* bddfalse*}
SECTION {* kernel *}
SHORT   {* the constant false bdd *}
PROTO   {* extern const BDD bddfalse; *}
DESCR   {* This bdd holds the constant false value *}
ALSO    {* bddtrue, bdd\_true, bdd\_false *}
*/
const BDD bddfalse=0;                    /* The constant false bdd */


/*=== INTERNAL DEFINITIONS =============================================*/

/* Min. number of nodes (%) that has to be left after a garbage collect
   unless a resize should be done. */
static int minfreenodes=20;


/*=== GLOBAL KERNEL VARIABLES ==========================================*/

int          bddrunning;            /* Flag - package initialized */
int          bdderrorcond;          /* Some error condition */
int          bddnodesize;           /* Number of allocated nodes */
int          bddmaxnodesize;        /* Maximum allowed number of nodes */
int          bddmaxnodeincrease;    /* Max. # of nodes used to inc. table */
BddNode*     bddnodes;          /* All of the bdd nodes */
93
int*         bddhash;           /* Unicity hash table */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
94
95
96
97
98
99
100
101
102
103
int          bddfreepos;        /* First free node */
int          bddfreenum;        /* Number of free nodes */
long int     bddproduced;       /* Number of new nodes ever produced */
int          bddvarnum;         /* Number of defined BDD variables */
int*         bddrefstack;       /* Internal node reference stack */
int*         bddrefstacktop;    /* Internal node reference stack top */
int*         bddvar2level;      /* Variable -> level table */
int*         bddlevel2var;      /* Level -> variable table */
jmp_buf      bddexception;      /* Long-jump point for interrupting calc. */
int          bddresized;        /* Flag indicating a resize of the nodetable */
104
105
int          bddcachesize;      /* Size of the operator caches */
int          bddhashsize;       /* Size of the BDD node hash */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

bddCacheStat bddcachestats;


/*=== PRIVATE KERNEL VARIABLES =========================================*/

static BDD*     bddvarset;             /* Set of defined BDD variables */
static int      gbcollectnum;          /* Number of garbage collections */
static long int gbcclock;              /* Clock ticks used in GBC */
static int      usednodes_nextreorder; /* When to do reorder next time */
static bddinthandler  err_handler;     /* Error handler */
static bddgbchandler  gbc_handler;     /* Garbage collection handler */
static bdd2inthandler resize_handler;  /* Node-table-resize handler */


   /* Strings for all error mesages */
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
122
static const char *errorstrings[BDD_ERRNUM] =
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
{ "Out of memory", "Unknown variable", "Value out of range",
  "Unknown BDD root dereferenced", "bdd_init() called twice",
  "File operation failed", "Incorrect file format",
  "Variables not in ascending order", "User called break",
  "Mismatch in size of variable sets",
  "Cannot allocate fewer nodes than already in use",
  "Unknown operator", "Illegal variable set",
  "Bad variable block operation",
  "Trying to decrease the number of variables",
  "Trying to replace with variables already in the bdd",
  "Number of nodes reached user defined maximum",
  "Unknown BDD - was not in node table",
  "Bad size argument",
  "Mismatch in bitvector size",
  "Illegal shift-left/right parameter",
138
139
  "Division by zero",
  "Unmergeable rewritings."};
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
140
141
142
143


/*=== OTHER INTERNAL DEFINITIONS =======================================*/

144
#define NODEHASH(lvl,l,h) (TRIPLE(lvl,l,h) & (bddhashsize - 1))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
145
146
147
148
149
150
151
152
153
154
155
156


/*************************************************************************
  BDD misc. user operations
*************************************************************************/

/*
NAME   {* bdd\_init *}
SECTION {* kernel *}
SHORT  {* initializes the BDD package *}
PROTO  {* int bdd_init(int nodesize, int cachesize) *}
DESCR  {* This function initiates the bdd package and {\em must} be called
157
	  before any bdd operations are done. The argument {\tt nodesize}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
158
159
160
161
162
163
164
165
166
	  is the initial number of nodes in the nodetable and {\tt cachesize}
	  is the fixed size of the internal caches. Typical values for
	  {\tt nodesize} are 10000 nodes for small test examples and up to
	  1000000 nodes for large examples. A cache size of 10000 seems to
	  work good even for large examples, but lesser values should do it
	  for smaller examples.

	  The number of cache entries can also be set to depend on the size
	  of the nodetable using a call to {\tt bdd\_setcacheratio}.
167

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
168
169
170
171
172
	  The initial number of nodes is not critical for any bdd operation
	  as the table will be resized whenever there are to few nodes left
	  after a garbage collection. But it does have some impact on the
	  efficency of the operations. *}
RETURN {* If no errors occur then 0 is returned, otherwise
173
	  a negative error code. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
174
175
176
177
178
ALSO   {* bdd\_done, bdd\_resize\_hook *}
*/
int bdd_init(int initnodesize, int cs)
{
   int n, err;
179

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
180
181
   if (bddrunning)
      return bdd_error(BDD_RUNNING);
182

183
   bddnodesize = initnodesize;
184

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
185
186
187
   if ((bddnodes=(BddNode*)malloc(sizeof(BddNode)*bddnodesize)) == NULL)
      return bdd_error(BDD_MEMORY);

188
189
   bddhashsize = bdd_nextpower(bddnodesize);
   if ((bddhash=(int*)calloc(bddhashsize, sizeof(*bddhash))) == NULL)
190
191
192
193
194
     {
       free(bddnodes);
       return bdd_error(BDD_MEMORY);
     }

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
195
   bddresized = 0;
196

197
198
   /* Load these globals into local variables to help the
      optimizer. */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
199
   {
200
201
202
203
204
205
206
207
208
209
210
211
212
     int sz = bddnodesize;
     BddNodeInit* b = (BddNodeInit*)bddnodes;
     for (n=0 ; n<sz ; n++)
       {
         b[n].z = 0;
         b[n].low = -1;
         /* Initializing HIGH is useless in BuDDy, but it helps the
            compiler vectorizing the code, and it helps the processor
            write-combining data to memory. */
         b[n].high = 0;
         b[n].next = n+1;
       }
     b[sz-1].next = 0;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
213
214
215
216
   }
   bddnodes[0].refcou = bddnodes[1].refcou = MAXREF;
   LOW(0) = HIGH(0) = 0;
   LOW(1) = HIGH(1) = 1;
217

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
218
219
220
221
222
223
224
225
226
227
228
229
   if ((err=bdd_operator_init(cs)) < 0)
   {
      bdd_done();
      return err;
   }

   bddfreepos = 2;
   bddfreenum = bddnodesize-2;
   bddrunning = 1;
   bddvarnum = 0;
   gbcollectnum = 0;
   gbcclock = 0;
230
   bddcachesize = cs;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
231
232
233
234
   usednodes_nextreorder = bddnodesize;
   bddmaxnodeincrease = DEFAULTMAXNODEINC;

   bdderrorcond = 0;
235

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
236
237
238
239
240
241
242
   bddcachestats.uniqueAccess = 0;
   bddcachestats.uniqueChain = 0;
   bddcachestats.uniqueHit = 0;
   bddcachestats.uniqueMiss = 0;
   bddcachestats.opHit = 0;
   bddcachestats.opMiss = 0;
   bddcachestats.swapCount = 0;
243

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
244
245
246
247
248
249
   bdd_gbc_hook(bdd_default_gbchandler);
   bdd_error_hook(bdd_default_errhandler);
   bdd_resize_hook(NULL);
   bdd_pairs_init();
   bdd_reorder_init();
   bdd_fdd_init();
250

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
251
252
253
254
255
256
257
258
259
260
261
262
263
   if (setjmp(bddexception) != 0)
      assert(0);

   return 0;
}


/*
NAME    {* bdd\_done*}
SECTION {* kernel *}
SHORT {* resets the bdd package *}
PROTO {* void bdd_done(void) *}
DESCR {* This function frees all memory used by the bdd package and resets
264
	 the package to it's initial state.*}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
265
266
267
268
269
270
271
272
ALSO  {* bdd\_init *}
*/
void bdd_done(void)
{
   /*sanitycheck(); FIXME */
   bdd_fdd_done();
   bdd_reorder_done();
   bdd_pairs_done();
273

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
274
275
276
277
278
   free(bddnodes);
   free(bddrefstack);
   free(bddvarset);
   free(bddvar2level);
   free(bddlevel2var);
279

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
280
281
282
283
284
285
286
287
288
289
290
   bddnodes = NULL;
   bddrefstack = NULL;
   bddvarset = NULL;

   bdd_operator_done();

   bddrunning = 0;
   bddnodesize = 0;
   bddmaxnodesize = 0;
   bddvarnum = 0;
   bddproduced = 0;
291

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
292
293
294
295
296
297
298
299
300
301
302
303
   err_handler = NULL;
   gbc_handler = NULL;
   resize_handler = NULL;
}


/*
NAME    {* bdd\_setvarnum *}
SECTION {* kernel *}
SHORT   {* set the number of used bdd variables *}
PROTO   {* int bdd_setvarnum(int num) *}
DESCR   {* This function is used to define the number of variables used in
304
	   the bdd package. It may be called more than one time, but only
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
305
306
307
308
309
310
311
312
313
314
315
	   to increase the number of variables. The argument
	   {\tt num} is the number of variables to use. *}
RETURN  {* Zero on succes, otherwise a negative error code. *}
ALSO    {* bdd\_ithvar, bdd\_varnum, bdd\_extvarnum *}
*/
int bdd_setvarnum(int num)
{
   int bdv;
   int oldbddvarnum = bddvarnum;

   bdd_disable_reorder();
316

317
#ifndef NDEBUG
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
318
319
   if (num < 1  ||  num > MAXVAR)
   {
320
      return bdd_error(BDD_RANGE);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
321
322
323
324
   }

   if (num < bddvarnum)
      return bdd_error(BDD_DECVNUM);
325
#endif
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
326
327
328
   if (num == bddvarnum)
      return 0;

329
   if (__unlikely(bddvarset == NULL))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
330
   {
331
332
333
334
     if (__unlikely((bddvarset = (BDD*)malloc(sizeof(BDD)*num*2)) == NULL))
       return bdd_error(BDD_MEMORY);
     if (__unlikely((bddlevel2var = (int*)malloc(sizeof(int)*(num+1))) == NULL))
       {
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
335
336
	 free(bddvarset);
	 return bdd_error(BDD_MEMORY);
337
338
339
       }
     if (__unlikely((bddvar2level = (int*)malloc(sizeof(int)*(num+1))) == NULL))
       {
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
340
341
342
	 free(bddvarset);
	 free(bddlevel2var);
	 return bdd_error(BDD_MEMORY);
343
       }
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
344
345
346
   }
   else
   {
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
     {
       BDD* tmp_ptr = (BDD*)realloc(bddvarset,sizeof(BDD)*num*2);
       if (__unlikely(tmp_ptr == NULL))
         return bdd_error(BDD_MEMORY);
       bddvarset = tmp_ptr;
     }
     {
       int* tmp_ptr2 = (int*)realloc(bddlevel2var,sizeof(int)*(num+1));
       if (__unlikely(tmp_ptr2 == NULL))
         {
           free(bddvarset);
           return bdd_error(BDD_MEMORY);
         }
       bddlevel2var = tmp_ptr2;
     }
     {
       int* tmp_ptr2 = (int*)realloc(bddvar2level,sizeof(int)*(num+1));
       if (__unlikely(tmp_ptr2 == NULL))
         {
           free(bddvarset);
           free(bddlevel2var);
           return bdd_error(BDD_MEMORY);
         }
       bddvar2level = tmp_ptr2;
     }
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
372
373
   }

374
   if (__likely(bddrefstack != NULL))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
375
376
377
378
379
380
381
382
      free(bddrefstack);
   bddrefstack = bddrefstacktop = (int*)malloc(sizeof(int)*(num*2+4));

   for(bdv=bddvarnum ; bddvarnum < num; bddvarnum++)
   {
      bddvarset[bddvarnum*2] = PUSHREF( bdd_makenode(bddvarnum, 0, 1) );
      bddvarset[bddvarnum*2+1] = bdd_makenode(bddvarnum, 1, 0);
      POPREF(1);
383

384
      if (__unlikely(bdderrorcond))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
385
386
387
388
      {
	 bddvarnum = bdv;
	 return -bdderrorcond;
      }
389

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
390
391
392
393
394
395
396
397
398
399
      bddnodes[bddvarset[bddvarnum*2]].refcou = MAXREF;
      bddnodes[bddvarset[bddvarnum*2+1]].refcou = MAXREF;
      bddlevel2var[bddvarnum] = bddvarnum;
      bddvar2level[bddvarnum] = bddvarnum;
   }

   LEVEL(0) = num;
   LEVEL(1) = num;
   bddvar2level[num] = num;
   bddlevel2var[num] = num;
400

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
401
402
   bdd_pairs_resize(oldbddvarnum, bddvarnum);
   bdd_operator_varresize();
403

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
404
   bdd_enable_reorder();
405

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
406
407
408
409
410
411
412
413
414
415
   return 0;
}


/*
NAME    {* bdd\_extvarnum *}
SECTION {* kernel *}
SHORT   {* add extra BDD variables *}
PROTO   {* int bdd_extvarnum(int num) *}
DESCR   {* Extends the current number of allocated BDD variables with
416
	   {\tt num} extra variables. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
417
418
419
420
421
422
RETURN  {* The old number of allocated variables or a negative error code. *}
ALSO    {* bdd\_setvarnum, bdd\_ithvar, bdd\_nithvar *}
*/
int bdd_extvarnum(int num)
{
   int start = bddvarnum;
423

424
   if (__unlikely(num < 0  ||  num > 0x3FFFFFFF))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
425
426
427
428
429
430
431
432
433
434
435
436
437
      return bdd_error(BDD_RANGE);

   bdd_setvarnum(bddvarnum+num);
   return start;
}


/*
NAME  {* bdd\_error\_hook *}
SECTION {* kernel *}
SHORT {* set a handler for error conditions *}
PROTO {* bddinthandler bdd_error_hook(bddinthandler handler) *}
DESCR {* Whenever an error occurs in the bdd package a test is done to
438
	see if an error handler is supplied by the user and if such exists
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
	then it will be called
	with an error code in the variable {\tt errcode}. The handler may
	then print any usefull information and return or exit afterwards.

	This function sets the handler to be {\tt handler}. If a {\tt NULL}
	argument is supplied then no calls are made when an error occurs.
	Possible error codes are found in {\tt bdd.h}. The default handler
	is {\tt bdd\_default\_errhandler} which will use {\tt exit()} to
	terminate the program.

	Any handler should be defined like this:
	\begin{verbatim}
void my_error_handler(int errcode)
{
   ...
}
\end{verbatim} *}
RETURN {* The previous handler *}
ALSO  {* bdd\_errstring *}
*/
bddinthandler bdd_error_hook(bddinthandler handler)
{
   bddinthandler tmp = err_handler;
   err_handler = handler;
   return tmp;
}


/*
NAME    {* bdd\_clear\_error *}
SECTION {* kernel *}
SHORT   {* clears an error condition in the kernel *}
PROTO   {* void bdd_clear_error(void) *}
DESCR   {* The BuDDy kernel may at some point run out of new ROBDD nodes if
473
	   a maximum limit is set with {\tt bdd\_setmaxnodenum}. In this case
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
	   the current error handler is called and an internal error flag
	   is set. Further calls to BuDDy will always return {\tt bddfalse}.
	   From here BuDDy must either be restarted or {\tt bdd\_clear\_error}
	   may be called after action is taken to let BuDDy continue. This may
	   not be especially usefull since the default error handler exits
	   the program - other needs may of course exist.*}
ALSO    {* bdd\_error\_hook, bdd\_setmaxnodenum *}
*/
void bdd_clear_error(void)
{
   bdderrorcond = 0;
   bdd_operator_reset();
}


/*
NAME  {* bdd\_gbc\_hook *}
SECTION {* kernel *}
SHORT {* set a handler for garbage collections *}
PROTO {* bddgbchandler bdd_gbc_hook(bddgbchandler handler) *}
DESCR {* Whenever a garbage collection is required, a test is done to
495
	 see if a handler for this event is supplied by the user and if such
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
	 exists then it is called, both before and after the garbage collection
	 takes places. This is indicated by an integer flag {\tt pre} passed to
	 the handler, which will be one before garbage collection and zero
	 after garbage collection.

	 This function sets the handler to be {\tt handler}. If a {\tt
	 NULL} argument is supplied then no calls are made when a
	 garbage collection takes place. The argument {\tt pre}
	 indicates pre vs. post garbage collection and the argument
	 {\tt stat} contains information about the garbage
	 collection. The default handler is {\tt bdd\_default\_gbchandler}.

	 Any handler should be defined like this:
	 \begin{verbatim}
void my_gbc_handler(int pre, bddGbcStat *stat)
{
   ...
}
\end{verbatim} *}
RETURN {* The previous handler *}
ALSO {* bdd\_resize\_hook, bdd\_reorder\_hook *} */
bddgbchandler bdd_gbc_hook(bddgbchandler handler)
{
   bddgbchandler tmp = gbc_handler;
   gbc_handler = handler;
   return tmp;
}


/*
NAME  {* bdd\_resize\_hook  *}
SECTION {* kernel *}
SHORT {* set a handler for nodetable resizes *}
PROTO {* bdd2inthandler bdd_resize_hook(bdd2inthandler handler) *}
DESCR {* Whenever it is impossible to get enough free nodes by a garbage
531
	 collection then the node table is resized and a test is done to see
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
	 if a handler is supllied by the user for this event. If so then
	 it is called with {\tt oldsize} being the old nodetable size and
	 {\tt newsize} being the new nodetable size.

	 This function sets the handler to be {\tt handler}. If a {\tt NULL}
	 argument is supplied then no calls are made when a table resize
	 is done. No default handler is supplied.

	 Any handler should be defined like this:
	 \begin{verbatim}
void my_resize_handler(int oldsize, int newsize)
{
   ...
}
\end{verbatim} *}
RETURN {* The previous handler *}
ALSO  {* bdd\_gbc\_hook, bdd\_reorder\_hook, bdd\_setminfreenodes  *}
*/
bdd2inthandler bdd_resize_hook(bdd2inthandler handler)
{
   bdd2inthandler tmp = handler;
   resize_handler = handler;
   return tmp;
}


/*
NAME    {* bdd\_setmaxincrease *}
SECTION {* kernel *}
SHORT   {* set max. number of nodes used to increase node table *}
PROTO   {* int bdd_setmaxincrease(int size) *}
DESCR   {* The node table is expanded by doubling the size of the table
564
	   when no more free nodes can be found, but a maximum for the
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
565
566
567
568
569
570
571
572
	   number of new nodes added can be set with {\tt bdd\_maxincrease}
	   to {\tt size} nodes. The default is 50000 nodes (1 Mb). *}
RETURN  {* The old threshold on succes, otherwise a negative error code. *}
ALSO    {* bdd\_setmaxnodenum, bdd\_setminfreenodes *}
*/
int bdd_setmaxincrease(int size)
{
   int old = bddmaxnodeincrease;
573

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
574
575
576
577
578
579
580
581
582
583
584
585
586
   if (size < 0)
      return bdd_error(BDD_SIZE);

   bddmaxnodeincrease = size;
   return old;
}

/*
NAME    {* bdd\_setmaxnodenum *}
SECTION {* kernel *}
SHORT {* set the maximum available number of bdd nodes *}
PROTO {* int bdd_setmaxnodenum(int size) *}
DESCR {* This function sets the maximal number of bdd nodes the package may
587
	 allocate before it gives up a bdd operation. The
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
	 argument {\tt size} is the absolute maximal number of nodes there
	 may be allocated for the nodetable. Any attempt to allocate more
	 nodes results in the constant false being returned and the error
	 handler being called until some nodes are deallocated.
	 A value of 0 is interpreted as an unlimited amount.
	 It is {\em not} possible to specify
	 fewer nodes than there has already been allocated. *}
RETURN {* The old threshold on succes, otherwise a negative error code. *}
ALSO   {* bdd\_setmaxincrease, bdd\_setminfreenodes *}
*/
int bdd_setmaxnodenum(int size)
{
   if (size > bddnodesize  ||  size == 0)
   {
      int old = bddmaxnodesize;
      bddmaxnodesize = size;
      return old;
   }

   return bdd_error(BDD_NODES);
}


/*
NAME    {* bdd\_setminfreenodes *}
SECTION {* kernel *}
SHORT   {* set min. no. of nodes to be reclaimed after GBC. *}
PROTO   {* int bdd_setminfreenodes(int n) *}
DESCR   {* Whenever a garbage collection is executed the number of free
617
	   nodes left are checked to see if a resize of the node table is
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
	   required. If $X = (\mathit{bddfreenum}*100)/\mathit{maxnum}$
	   is less than or
	   equal to {\tt n} then a resize is initiated. The range of
	   {\tt X} is of course $0\ldots 100$ and has some influence
	   on how fast the package is. A low number means harder attempts
	   to avoid resizing and saves space, and a high number reduces
	   the time used in garbage collections. The default value is
	   20. *}
RETURN  {* The old threshold on succes, otherwise a negative error code. *}
ALSO    {* bdd\_setmaxnodenum, bdd\_setmaxincrease *}
*/
int bdd_setminfreenodes(int mf)
{
   int old = minfreenodes;
632

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
   if (mf<0 || mf>100)
      return bdd_error(BDD_RANGE);

   minfreenodes = mf;
   return old;
}


/*
NAME    {* bdd\_getnodenum *}
SECTION {* kernel *}
SHORT   {* get the number of active nodes in use *}
PROTO   {* int bdd_getnodenum(void) *}
DESCR   {* Returns the number of nodes in the nodetable that are
647
	   currently in use. Note that dead nodes that have not been
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
	   reclaimed yet
	   by a garbage collection are counted as active. *}
RETURN  {* The number of nodes. *}
ALSO    {* bdd\_getallocnum, bdd\_setmaxnodenum *}
*/
int bdd_getnodenum(void)
{
   return bddnodesize - bddfreenum;
}


/*
NAME    {* bdd\_getallocnum *}
SECTION {* kernel *}
SHORT   {* get the number of allocated nodes *}
PROTO   {* int bdd_getallocnum(void) *}
DESCR   {* Returns the number of nodes currently allocated. This includes
665
	   both dead and active nodes. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
RETURN  {* The number of nodes. *}
ALSO    {* bdd\_getnodenum, bdd\_setmaxnodenum *}
*/
int bdd_getallocnum(void)
{
   return bddnodesize;
}


/*
NAME    {* bdd\_isrunning *}
SECTION {* kernel *}
SHORT   {* test whether the package is started or not *}
PROTO   {* void bdd_isrunning(void) *}
DESCR   {* This function tests the internal state of the package and returns
681
	  a status. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
RETURN  {* 1 (true) if the package has been started, otherwise 0. *}
ALSO    {* bdd\_init, bdd\_done *}
*/
int bdd_isrunning(void)
{
   return bddrunning;
}


/*
NAME    {* bdd\_versionstr *}
SECTION {* kernel *}
SHORT   {* returns a text string with version information *}
PROTO   {* char* bdd_versionstr(void) *}
DESCR   {* This function returns a text string with information about the
697
	   version of the bdd package. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
ALSO    {* bdd\_versionnum *}
*/
char *bdd_versionstr(void)
{
   static char str[100];
   sprintf(str, "BuDDy -  release %d.%d", VERSION/10, VERSION%10);
   return str;
}


/*
NAME    {* bdd\_versionnum *}
SECTION {* kernel *}
SHORT   {* returns the version number of the bdd package *}
PROTO   {* int bdd_versionnum(void) *}
DESCR   {* This function returns the version number of the bdd package. The
714
	   number is in the range 10-99 for version 1.0 to 9.9. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
715
716
717
718
719
720
721
722
723
724
725
726
727
728
ALSO    {* bdd\_versionstr *}
*/
int bdd_versionnum(void)
{
   return VERSION;
}


/*
NAME    {* bdd\_stats *}
SECTION {* kernel *}
SHORT   {* returns some status information about the bdd package *}
PROTO   {* void bdd_stats(bddStat* stat) *}
DESCR   {* This function acquires information about the internal state of
729
	   the bdd package. The status information is written into the
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
730
731
732
733
734
735
736
737
738
739
740
	   {\tt stat} argument. *}
ALSO    {* bddStat *}
*/
void bdd_stats(bddStat *s)
{
   s->produced = bddproduced;
   s->nodenum = bddnodesize;
   s->maxnodenum = bddmaxnodesize;
   s->freenodes = bddfreenum;
   s->minfreenodes = minfreenodes;
   s->varnum = bddvarnum;
741
742
   s->cachesize = bddcachesize;
   s->hashsize = bddhashsize;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
743
744
745
746
747
748
749
750
751
752
753
   s->gbcnum = gbcollectnum;
}



/*
NAME    {* bdd\_cachestats *}
SECTION {* kernel *}
SHORT   {* Fetch cache access usage *}
PROTO   {* void bdd_cachestats(bddCacheStat *s) *}
DESCR   {* Fetches cache usage information and stores it in {\tt s}. The
754
	   fields of {\tt s} can be found in the documentaion for
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
	   {\tt bddCacheStat}. This function may or may not be compiled
	   into the BuDDy package - depending on the setup at compile
	   time of BuDDy. *}
ALSO    {* bddCacheStat, bdd\_printstat *}
*/
void bdd_cachestats(bddCacheStat *s)
{
   *s = bddcachestats;
}


/*
NAME    {* bdd\_printstat *}
EXTRA   {* bdd\_fprintstat *}
SECTION {* kernel *}
SHORT   {* print cache statistics *}
PROTO   {* void bdd_printstat(void)
void bdd_fprintstat(FILE *ofile) *}
DESCR   {* Prints information about the cache performance on standard output
774
	   (or the supplied file). The information contains the number of
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
775
776
777
778
779
780
781
782
783
784
	   accesses to the unique node table, the number of times a node
	   was (not) found there and how many times a hash chain had to
	   traversed. Hit and miss count is also given for the operator
	   caches. *}
ALSO    {* bddCacheStat, bdd\_cachestats *}
*/
void bdd_fprintstat(FILE *ofile)
{
   bddCacheStat s;
   bdd_cachestats(&s);
785

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
786
787
   fprintf(ofile, "\nCache statistics\n");
   fprintf(ofile, "----------------\n");
788

789
790
791
792
   fprintf(ofile, "Unique Access:  %lu\n", s.uniqueAccess);
   fprintf(ofile, "Unique Chain:   %lu\n", s.uniqueChain);
   fprintf(ofile, "Unique Hit:     %lu\n", s.uniqueHit);
   fprintf(ofile, "Unique Miss:    %lu\n", s.uniqueMiss);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
793
   fprintf(ofile, "=> Hit rate =   %.2f\n",
794
	   (s.uniqueHit+s.uniqueMiss > 0) ?
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
795
	   ((float)s.uniqueHit)/((float)s.uniqueHit+s.uniqueMiss) : 0);
796
797
   fprintf(ofile, "Operator Hits:  %lu\n", s.opHit);
   fprintf(ofile, "Operator Miss:  %lu\n", s.opMiss);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
798
   fprintf(ofile, "=> Hit rate =   %.2f\n",
799
	   (s.opHit+s.opMiss > 0) ?
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
800
	   ((float)s.opHit)/((float)s.opHit+s.opMiss) : 0);
801
   fprintf(ofile, "Swap count =    %lu\n", s.swapCount);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
}


void bdd_printstat(void)
{
   bdd_fprintstat(stdout);
}


/*************************************************************************
  Error handler
*************************************************************************/

/*
NAME    {* bdd\_errstring *}
SECTION {* kernel *}
SHORT   {* converts an error code to a string*}
PROTO   {* const char *bdd_errstring(int errorcode) *}
DESCR   {* Converts a negative error code {\tt errorcode} to a descriptive
821
	   string that can be used for error handling. *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
RETURN  {* An error description string if {\tt e} is known, otherwise {\tt NULL}. *}
ALSO    {* bdd\_err\_hook *}
*/
const char *bdd_errstring(int e)
{
   e = abs(e);
   if (e<1 || e>BDD_ERRNUM)
      return NULL;
   return errorstrings[e-1];
}


void bdd_default_errhandler(int e)
{
   fprintf(stderr, "BDD error: %s\n", bdd_errstring(e));
837
   abort();
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
838
839
840
841
842
843
844
}


int bdd_error(int e)
{
   if (err_handler != NULL)
      err_handler(e);
845

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
   return e;
}


/*************************************************************************
  BDD primitives
*************************************************************************/

/*
NAME    {* bdd\_true *}
SECTION {* kernel *}
SHORT   {* returns the constant true bdd *}
PROTO   {* BDD bdd_true(void) *}
DESCR   {* This function returns the constant true bdd and can freely be
860
	   used together with the {\tt bddtrue} and {\tt bddfalse}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
	   constants. *}
RETURN  {* The constant true bdd *}
ALSO    {* bdd\_false, bddtrue, bddfalse *}
*/
BDD bdd_true(void)
{
   return 1;
}


/*
NAME    {* bdd\_false *}
SECTION {* kernel *}
SHORT   {* returns the constant false bdd *}
PROTO   {* BDD bdd_false(void) *}
DESCR   {* This function returns the constant false bdd and can freely be
877
	   used together with the {\tt bddtrue} and {\tt bddfalse}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
	   constants. *}
RETURN  {* The constant false bdd *}
ALSO    {* bdd\_true, bddtrue, bddfalse *}
*/
BDD bdd_false(void)
{
   return 0;
}


/*
NAME    {* bdd\_ithvar *}
SECTION {* kernel *}
SHORT   {* returns a bdd representing the I'th variable *}
PROTO   {* BDD bdd_ithvar(int var) *}
DESCR   {* This function is used to get a bdd representing the I'th
894
	   variable (one node with the childs true and false). The requested
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
895
896
897
898
899
900
901
902
903
904
905
906
	   variable must be in the range define by {\tt
	   bdd\_setvarnum} starting with 0 being the first. For ease
	   of use then the bdd returned from {\tt bdd\_ithvar} does
	   not have to be referenced counted with a call to {\tt
	   bdd\_addref}. The initial variable order is defined by the
	   the index {\tt var} that also defines the position in the
	   variable order -- variables with lower indecies are before
	   those with higher indecies. *}
RETURN  {* The I'th variable on succes, otherwise the constant false bdd *}
ALSO {* bdd\_setvarnum, bdd\_nithvar, bddtrue, bddfalse *} */
BDD bdd_ithvar(int var)
{
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
907
#ifndef NDEBUG
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
908
909
910
911
912
   if (var < 0  ||  var >= bddvarnum)
   {
      bdd_error(BDD_VAR);
      return bddfalse;
   }
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
913
#endif
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
914
915
916
917
918
919
920
921
922
923
924

   return bddvarset[var*2];
}


/*
NAME    {* bdd\_nithvar *}
SECTION {* kernel *}
SHORT   {* returns a bdd representing the negation of the I'th variable *}
PROTO   {* BDD bdd_nithvar(int var) *}
DESCR   {* This function is used to get a bdd representing the negation of
925
	   the I'th variable (one node with the childs false and true).
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
926
927
928
929
	   The requested variable must be in the range define by
	   {\tt bdd\_setvarnum} starting with 0 being the first. For ease of
	   use then the bdd returned from {\tt bdd\_nithvar} does not have
	   to be referenced counted with a call to {\tt bdd\_addref}. *}
930
RETURN  {* The negated I'th variable on succes, otherwise the constant false bdd *}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
931
932
933
934
ALSO    {* bdd\_setvarnum, bdd\_ithvar, bddtrue, bddfalse *}
*/
BDD bdd_nithvar(int var)
{
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
935
#ifndef NDEBUG
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
936
937
938
939
940
   if (var < 0  ||  var >= bddvarnum)
   {
      bdd_error(BDD_VAR);
      return bddfalse;
   }
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
941
#endif
942

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
943
944
945
946
947
948
949
950
951
952
   return bddvarset[var*2+1];
}


/*
NAME    {* bdd\_varnum *}
SECTION {* kernel *}
SHORT   {* returns the number of defined variables *}
PROTO   {* int bdd_varnum(void) *}
DESCR   {* This function returns the number of variables defined by
953
	   a call to {\tt bdd\_setvarnum}.*}
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
RETURN  {* The number of defined variables *}
ALSO    {* bdd\_setvarnum, bdd\_ithvar *}
*/
int bdd_varnum(void)
{
   return bddvarnum;
}


/*
NAME    {* bdd\_var *}
SECTION {* info *}
SHORT   {* gets the variable labeling the bdd *}
PROTO   {* int bdd_var(BDD r) *}
DESCR   {* Gets the variable labeling the bdd {\tt r}. *}
RETURN  {* The variable number. *}
*/
int bdd_var(BDD root)
{
   CHECK(root);
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
974
975
   CHECKnc(root);
   return bddlevel2var[LEVEL(root)];
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
}


/*
NAME    {* bdd\_low *}
SECTION {* info *}
SHORT   {* gets the false branch of a bdd  *}
PROTO   {* BDD bdd_low(BDD r) *}
DESCR   {* Gets the false branch of the bdd {\tt r}.  *}
RETURN  {* The bdd of the false branch *}
ALSO    {* bdd\_high *}
*/
BDD bdd_low(BDD root)
{
   CHECK(root);
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
991
992
   CHECKnc(root);
   return LOW(root);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
}


/*
NAME    {* bdd\_high *}
SECTION {* info *}
SHORT   {* gets the true branch of a bdd  *}
PROTO   {* BDD bdd_high(BDD r) *}
DESCR   {* Gets the true branch of the bdd {\tt r}.  *}
RETURN  {* The bdd of the true branch *}
ALSO    {* bdd\_low *}
*/
BDD bdd_high(BDD root)
{
   CHECK(root);
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
1008
1009
   CHECKnc(root);
   return HIGH(root);
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
}



/*************************************************************************
  Garbage collection and node referencing
*************************************************************************/

void bdd_default_gbchandler(int pre, bddGbcStat *s)
{
   if (!pre)
   {
1022
      fprintf(stderr, "Garbage collection #%d: %d nodes / %d free",
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1023
	     s->num, s->nodes, s->freenodes);
1024
      fprintf(stderr, " / %.1fs / %.1fs total\n",
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
	     (float)s->time/(float)(CLOCKS_PER_SEC),
	     (float)s->sumtime/(float)CLOCKS_PER_SEC);
   }
}


static void bdd_gbc_rehash(void)
{
   int n;

   bddfreepos = 0;
   bddfreenum = 0;

   for (n=bddnodesize-1 ; n>=2 ; n--)
   {
      register BddNode *node = &bddnodes[n];

      if (LOWp(node) != -1)
      {
	 register unsigned int hash;

	 hash = NODEHASH(LEVELp(node), LOWp(node), HIGHp(node));
1047
1048
	 node->next = bddhash[hash];
	 bddhash[hash] = n;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
      }
      else
      {
	 node->next = bddfreepos;
	 bddfreepos = n;
	 bddfreenum++;
      }
   }
}


void bdd_gbc(void)
{
   int *r;
   int n;
   long int c2, c1 = clock();

   if (gbc_handler != NULL)
   {
      bddGbcStat s;
      s.nodes = bddnodesize;
      s.freenodes = bddfreenum;
      s.time = 0;
      s.sumtime = gbcclock;
      s.num = gbcollectnum;
      gbc_handler(1, &s);
   }
1076

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1077
1078
1079
1080
1081
1082
1083
1084
   for (r=bddrefstack ; r<bddrefstacktop ; r++)
      bdd_mark(*r);

   for (n=0 ; n<bddnodesize ; n++)
   {
      if (bddnodes[n].refcou > 0)
	 bdd_mark(n);
   }
1085

1086
   memset(bddhash, 0, bddhashsize*sizeof(*bddhash));
1087

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
   bddfreepos = 0;
   bddfreenum = 0;

   for (n=bddnodesize-1 ; n>=2 ; n--)
   {
      register BddNode *node = &bddnodes[n];

      if ((LEVELp(node) & MARKON)  &&  LOWp(node) != -1)
      {
	 register unsigned int hash;

	 LEVELp(node) &= MARKOFF;
	 hash = NODEHASH(LEVELp(node), LOWp(node), HIGHp(node));
1101
1102
	 node->next = bddhash[hash];
	 bddhash[hash] = n;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
      }
      else
      {
	 LOWp(node) = -1;
	 node->next = bddfreepos;
	 bddfreepos = n;
	 bddfreenum++;
      }
   }

   bdd_operator_reset();

   c2 = clock();
   gbcclock += c2-c1;
   gbcollectnum++;

   if (gbc_handler != NULL)
   {
      bddGbcStat s;
      s.nodes = bddnodesize;
      s.freenodes = bddfreenum;
      s.time = c2-c1;
      s.sumtime = gbcclock;
      s.num = gbcollectnum;
      gbc_handler(0, &s);
   }
}


1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
BDD bdd_addref_nc(BDD root)
{
#ifndef NDEBUG
   if (!bddrunning)
      return root;
   if (root < 2 || root >= bddnodesize)
      return bdd_error(BDD_ILLBDD);
   if (LOW(root) == -1)
      return bdd_error(BDD_ILLBDD);
#endif
   INCREF(root);
   return root;
}

1146
1147
1148
1149
1150
1151
1152
/*
NAME    {* bdd\_addref *}
SECTION {* kernel *}
SHORT   {* increases the reference count on a node *}
PROTO   {* BDD bdd_addref(BDD r) *}
DESCR   {* Reference counting is done on externaly referenced nodes only
	   and the count for a specific node {\tt r} can and must be
1153
	   increased using this function to avoid losing the node in the next
1154
1155
1156
1157
1158
1159
	   garbage collection. *}
ALSO    {* bdd\_delref *}
RETURN  {* The BDD node {\tt r}. *}
*/
BDD bdd_addref(BDD root)
{
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
1160
1161
1162
1163
#if NDEBUG
   if (root < 2)
      return root;
#else
1164
1165
1166
1167
1168
1169
   if (root < 2  ||  !bddrunning)
      return root;
   if (root >= bddnodesize)
      return bdd_error(BDD_ILLBDD);
   if (LOW(root) == -1)
      return bdd_error(BDD_ILLBDD);
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
1170
#endif
1171
1172
1173
1174
   INCREF(root);
   return root;
}

1175
/* Non constant version */
1176
1177
1178
BDD bdd_delref_nc(BDD root)
{
#ifndef NDEBUG
1179
   if (!bddrunning)
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
      return root;
   if (root >= bddnodesize)
      return bdd_error(BDD_ILLBDD);
   if (LOW(root) == -1)
      return bdd_error(BDD_ILLBDD);

   /* if the following line is present, fails there much earlier */
   if (!HASREF(root)) bdd_error(BDD_BREAK); /* distinctive */
#endif
   DECREF(root);
   return root;
}
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206

/*
NAME    {* bdd\_delref *}
SECTION {* kernel *}
SHORT   {* decreases the reference count on a node *}
PROTO   {* BDD bdd_delref(BDD r) *}
DESCR   {* Reference counting is done on externaly referenced nodes only
	   and the count for a specific node {\tt r} can and must be
	   decreased using this function to make it possible to reclaim the
	   node in the next garbage collection. *}
ALSO    {* bdd\_addref *}
RETURN  {* The BDD node {\tt r}. *}
*/
BDD bdd_delref(BDD root)
{
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
1207
1208
1209
1210
#if NDEBUG
   if (root < 2)
      return root;
#else
1211
1212
1213
1214
1215
1216
1217
1218
1219
   if (root < 2  ||  !bddrunning)
      return root;
   if (root >= bddnodesize)
      return bdd_error(BDD_ILLBDD);
   if (LOW(root) == -1)
      return bdd_error(BDD_ILLBDD);

   /* if the following line is present, fails there much earlier */
   if (!HASREF(root)) bdd_error(BDD_BREAK); /* distinctive */
Alexandre Duret-Lutz's avatar
[buddy]    
Alexandre Duret-Lutz committed
1220
#endif
1221
1222
1223
1224
   DECREF(root);
   return root;
}

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1225
1226
1227
1228
1229
1230

/*=== RECURSIVE MARK / UNMARK ==========================================*/

void bdd_mark(int i)
{
   BddNode *node;
1231

1232
   if (__unlikely(i < 2))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1233
1234
1235
1236
1237
      return;

   node = &bddnodes[i];
   if (LEVELp(node) & MARKON  ||  LOWp(node) == -1)
      return;
1238

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1239
   LEVELp(node) |= MARKON;
1240

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1241
1242
1243
1244
1245
1246
1247
1248
   bdd_mark(LOWp(node));
   bdd_mark(HIGHp(node));
}


void bdd_mark_upto(int i, int level)
{
   BddNode *node = &bddnodes[i];
1249

1250
   if (__unlikely(i < 2))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1251
      return;
1252

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1253
1254
   if (LEVELp(node) & MARKON  ||  LOWp(node) == -1)
      return;
1255

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
   if (LEVELp(node) > level)
      return;

   LEVELp(node) |= MARKON;

   bdd_mark_upto(LOWp(node), level);
   bdd_mark_upto(HIGHp(node), level);
}


void bdd_markcount(int i, int *cou)
{
   BddNode *node;
1269

1270
   if (__unlikely(i < 2))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1271
1272
1273
1274
1275
      return;

   node = &bddnodes[i];
   if (MARKEDp(node)  ||  LOWp(node) == -1)
      return;
1276

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1277
1278
   SETMARKp(node);
   *cou += 1;
1279

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1280
1281
1282
1283
1284
1285
1286
1287
   bdd_markcount(LOWp(node), cou);
   bdd_markcount(HIGHp(node), cou);
}


void bdd_unmark(int i)
{
   BddNode *node;
1288

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1289
1290
1291
1292
1293
1294
1295
1296
   if (i < 2)
      return;

   node = &bddnodes[i];

   if (!MARKEDp(node)  ||  LOWp(node) == -1)
      return;
   UNMARKp(node);
1297

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1298
1299
1300
1301
1302
1303
1304
1305
1306
   bdd_unmark(LOWp(node));
   bdd_unmark(HIGHp(node));
}


void bdd_unmark_upto(int i, int level)
{
   BddNode *node = &bddnodes[i];

1307
   if (__unlikely(i < 2))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1308
      return;
1309

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1310
1311
   if (!(LEVELp(node) & MARKON))
      return;
1312

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1313
   LEVELp(node) &= MARKOFF;
1314

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
   if (LEVELp(node) > level)
      return;

   bdd_unmark_upto(LOWp(node), level);
   bdd_unmark_upto(HIGHp(node), level);
}


/*************************************************************************
  Unique node table functions
*************************************************************************/

int bdd_makenode(unsigned int level, int low, int high)
{
   register BddNode *node;
   register unsigned int hash;
   register int res;

#ifdef CACHESTATS
   bddcachestats.uniqueAccess++;
#endif
1336

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1337
1338
1339
1340
1341
1342
      /* check whether childs are equal */
   if (low == high)
      return low;

      /* Try to find an existing node of this kind */
   hash = NODEHASH(level, low, high);
1343
   res = bddhash[hash];
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359

   while(res != 0)
   {
      if (LEVEL(res) == level  &&  LOW(res) == low  &&  HIGH(res) == high)
      {
#ifdef CACHESTATS
	 bddcachestats.uniqueHit++;
#endif
	 return res;
      }

      res = bddnodes[res].next;
#ifdef CACHESTATS
      bddcachestats.uniqueChain++;
#endif
   }
1360

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1361
1362
1363
1364
1365
1366
      /* No existing node -> build one */
#ifdef CACHESTATS
   bddcachestats.uniqueMiss++;
#endif

      /* Any free nodes to use ? */
1367
   if (__unlikely(bddfreepos == 0))
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1368
1369
1370
   {
      if (bdderrorcond)
	 return 0;
1371
1372

	 /* Try to allocate more nodes */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
      bdd_gbc();

      if ((bddnodesize-bddfreenum) >= usednodes_nextreorder  &&
	   bdd_reorder_ready())
      {
	 longjmp(bddexception,1);
      }

      if ((bddfreenum*100) / bddnodesize <= minfreenodes)
      {
	 bdd_noderesize(1);
	 hash = NODEHASH(level, low, high);
      }

1387
	 /* Panic if that is not possible */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
      if (bddfreepos == 0)
      {
	 bdd_error(BDD_NODENUM);
	 bdderrorcond = abs(BDD_NODENUM);
	 return 0;
      }
   }

      /* Build new node */
   res = bddfreepos;
   bddfreepos = bddnodes[bddfreepos].next;
   bddfreenum--;
   bddproduced++;
1401

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1402
1403
1404
1405
   node = &bddnodes[res];
   LEVELp(node) = level;
   LOWp(node) = low;
   HIGHp(node) = high;
1406

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1407
      /* Insert node */
1408
1409
   node->next = bddhash[hash];
   bddhash[hash] = res;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1410
1411
1412
1413
1414
1415
1416
1417
1418

   return res;
}


int bdd_noderesize(int doRehash)
{
   BddNode *newnodes;
   int oldsize = bddnodesize;
1419
   int oldhashsize = bddhashsize;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1420
1421
1422
1423
   int n;

   if (bddnodesize >= bddmaxnodesize  &&  bddmaxnodesize > 0)
      return -1;
1424

1425
   bddnodesize <<= 1;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440

   if (bddnodesize > oldsize + bddmaxnodeincrease)
      bddnodesize = oldsize + bddmaxnodeincrease;

   if (bddnodesize > bddmaxnodesize  &&  bddmaxnodesize > 0)
      bddnodesize = bddmaxnodesize;

   if (resize_handler != NULL)
      resize_handler(oldsize, bddnodesize);

   newnodes = (BddNode*)realloc(bddnodes, sizeof(BddNode)*bddnodesize);
   if (newnodes == NULL)
      return bdd_error(BDD_MEMORY);
   bddnodes = newnodes;

1441
1442
1443
   if (oldhashsize * 2 <= bddnodesize)
     bddhashsize <<= 1;

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1444
   if (doRehash)
1445
1446
     {
       free(bddhash);
1447
       if ((bddhash=(int*)calloc(bddhashsize, sizeof(*bddhash))) == NULL)
1448
1449
1450
1451
	 return bdd_error(BDD_MEMORY);
     }
   else
     {
1452
       bddhash = (int*)realloc(bddhash, sizeof(*bddhash)*bddhashsize);
1453
1454
       if (bddhash == NULL)
	 return bdd_error(BDD_MEMORY);
1455
1456
       memset(bddhash + oldhashsize, 0,
              (bddhashsize-oldhashsize)*sizeof(*bddhash));
1457
     }
1458

1459
1460
   /* copy these global variables into local variables to help the
      optimizer */
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1461
   {
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
     int sz = bddnodesize;
     BddNodeInit* b = (BddNodeInit*)(bddnodes);
     for (n=oldsize ; n<sz ; n++)
       {
         b[n].z = 0;
         b[n].low = -1;
         b[n].high = 0;
         b[n].next = n+1;
       }
     b[sz-1].next = bddfreepos;
     bddfreepos = oldsize;
     bddfreenum += bddnodesize - oldsize;
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1474
1475
1476
1477
1478
1479
   }

   if (doRehash)
      bdd_gbc_rehash();

   bddresized = 1;
1480

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
   return 0;
}


void bdd_checkreorder(void)
{
   bdd_reorder_auto();

      /* Do not reorder before twice as many nodes have been used */
   usednodes_nextreorder = 2 * (bddnodesize - bddfreenum);
1491

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
      /* And if very little was gained this time (< 20%) then wait until
       * even more nodes (upto twice as many again) have been used */
   if (bdd_reorder_gain() < 20)
      usednodes_nextreorder +=
	 (usednodes_nextreorder * (20-bdd_reorder_gain())) / 20;
}


/*************************************************************************
  Variable sets
*************************************************************************/

/*
NAME    {* bdd\_scanset *}
SECTION {* kernel *}
SHORT   {* returns an integer representation of a variable set *}
PROTO   {* int bdd_scanset(BDD r, int **v, int *n) *}
DESCR   {* Scans a variable set {\tt r} and copies the stored variables into
1510
	   an integer array of variable numbers. The argument {\tt v} is
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
	   the address of an integer pointer where the array is stored and
	   {\tt n} is a pointer to an integer where the number of elements
	   are stored. It is the users responsibility to make sure the
	   array is deallocated by a call to {\tt free(v)}. The numbers
	   returned are guaranteed to be in ascending order. *}
ALSO    {* bdd\_makeset *}
RETURN  {* Zero on success, otherwise a negative error code. *}
*/
int bdd_scanset(BDD r, int **varset, int *varnum)
{
   int n, num;

   CHECK(r);
   if (r < 2)
   {
      *varnum = 0;
      *varset = NULL;
      return 0;
   }
1530

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1531
1532
1533
1534
1535
   for (n=r, num=0 ; n > 1 ; n=HIGH(n))
      num++;

   if (((*varset) = (int *)malloc(sizeof(int)*num)) == NULL)
      return bdd_error(BDD_MEMORY);
1536

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
   for (n=r, num=0 ; n > 1 ; n=HIGH(n))
      (*varset)[num++] = bddlevel2var[LEVEL(n)];

   *varnum = num;

   return 0;
}


/*
NAME    {* bdd\_makeset *}
SECTION {* kernel *}
SHORT   {* builds a BDD variable set from an integer array *}
PROTO   {* BDD bdd_makeset(int *v, int n) *}
DESCR   {* Reads a set of variable numbers from the integer array {\tt v}
1552
	   which must hold exactly {\tt n} integers and then builds a BDD
Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
	   representing the variable set.

	   The BDD variable set is represented as the conjunction of
	   all the variables in their positive form and may just as
	   well be made that way by the user. The user should keep a
	   reference to the returned BDD instead of building it every
	   time the set is needed. *}
ALSO    {* bdd\_scanset *}
RETURN {* A BDD variable set. *} */
BDD bdd_makeset(int *varset, int varnum)
{
   int v, res=1;
1565

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
   for (v=varnum-1 ; v>=0 ; v--)
   {
      BDD tmp;
      bdd_addref(res);
      tmp = bdd_apply(res, bdd_ithvar(varset[v]), bddop_and);
      bdd_delref(res);
      res = tmp;
   }

   return res;
}


/* EOF */