cuddTable.c 104 KB
Newer Older
Alan Mishchenko committed
1 2 3 4 5 6 7 8 9
/**CFile***********************************************************************

  FileName    [cuddTable.c]

  PackageName [cudd]

  Synopsis    [Unique table management functions.]

  Description [External procedures included in this module:
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
                <ul>
                <li> Cudd_Prime()
                </ul>
        Internal procedures included in this module:
                <ul>
                <li> cuddAllocNode()
                <li> cuddInitTable()
                <li> cuddFreeTable()
                <li> cuddGarbageCollect()
                <li> cuddZddGetNode()
                <li> cuddZddGetNodeIVO()
                <li> cuddUniqueInter()
                <li> cuddUniqueInterIVO()
                <li> cuddUniqueInterZdd()
                <li> cuddUniqueConst()
                <li> cuddRehash()
                <li> cuddShrinkSubtable()
                <li> cuddInsertSubtables()
                <li> cuddDestroySubtables()
                <li> cuddResizeTableZdd()
                <li> cuddSlowTableGrowth()
                </ul>
        Static procedures included in this module:
                <ul>
                <li> ddRehashZdd()
                <li> ddResizeTable()
                <li> cuddFindParent()
                <li> cuddOrderedInsert()
                <li> cuddOrderedThread()
                <li> cuddRotateLeft()
                <li> cuddRotateRight()
                <li> cuddDoRebalance()
                <li> cuddCheckCollisionOrdering()
                </ul>]
Alan Mishchenko committed
44 45 46 47 48

  SeeAlso     []

  Author      [Fabio Somenzi]

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
  Copyright   [Copyright (c) 1995-2004, Regents of the University of Colorado

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

  Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  Neither the name of the University of Colorado nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.]
Alan Mishchenko committed
80 81 82

******************************************************************************/

83
#include "misc/util/util_hack.h"
84
#include "cuddInt.h"
Alan Mishchenko committed
85

86 87 88
ABC_NAMESPACE_IMPL_START


89

Alan Mishchenko committed
90 91 92 93 94
/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef DD_UNSORTED_FREE_LIST
95
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
96 97 98 99 100 101
/* Constants for red/black trees. */
#define DD_STACK_SIZE 128
#define DD_RED   0
#define DD_BLACK 1
#define DD_PAGE_SIZE 8192
#define DD_PAGE_MASK ~(DD_PAGE_SIZE - 1)
102
#endif
Alan Mishchenko committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
#endif

/*---------------------------------------------------------------------------*/
/* Stucture declarations                                                     */
/*---------------------------------------------------------------------------*/

/* This is a hack for when CUDD_VALUE_TYPE is double */
typedef union hack {
    CUDD_VALUE_TYPE value;
    unsigned int bits[2];
} hack;

/*---------------------------------------------------------------------------*/
/* Type declarations                                                         */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef lint
124
static char rcsid[] DD_UNUSED = "$Id: cuddTable.c,v 1.122 2009/02/19 16:24:28 fabio Exp $";
Alan Mishchenko committed
125 126 127 128 129 130 131 132
#endif

/*---------------------------------------------------------------------------*/
/* Macro declarations                                                        */
/*---------------------------------------------------------------------------*/


#ifndef DD_UNSORTED_FREE_LIST
133
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
134
/* Macros for red/black trees. */
135 136
#define DD_INSERT_COMPARE(x,y) \
        (((ptruint) (x) & DD_PAGE_MASK) - ((ptruint) (y) & DD_PAGE_MASK))
Alan Mishchenko committed
137 138 139 140 141 142 143
#define DD_COLOR(p)  ((p)->index)
#define DD_IS_BLACK(p) ((p)->index == DD_BLACK)
#define DD_IS_RED(p) ((p)->index == DD_RED)
#define DD_LEFT(p) cuddT(p)
#define DD_RIGHT(p) cuddE(p)
#define DD_NEXT(p) ((p)->next)
#endif
144
#endif
Alan Mishchenko committed
145 146 147 148 149 150 151 152


/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Static function prototypes                                                */
/*---------------------------------------------------------------------------*/

153 154 155 156 157 158 159 160 161 162 163 164
static void ddRehashZdd (DdManager *unique, int i);
static int ddResizeTable (DdManager *unique, int index);
static int cuddFindParent (DdManager *table, DdNode *node);
DD_INLINE static void ddFixLimits (DdManager *unique);
#ifdef DD_RED_BLACK_FREE_LIST
static void cuddOrderedInsert (DdNodePtr *root, DdNodePtr node);
static DdNode * cuddOrderedThread (DdNode *root, DdNode *list);
static void cuddRotateLeft (DdNodePtr *nodeP);
static void cuddRotateRight (DdNodePtr *nodeP);
static void cuddDoRebalance (DdNodePtr **stack, int stackN);
#endif
static void ddPatchTree (DdManager *dd, MtrNode *treenode);
Alan Mishchenko committed
165
#ifdef DD_DEBUG
166
static int cuddCheckCollisionOrdering (DdManager *unique, int i, int j);
Alan Mishchenko committed
167
#endif
168
static void ddReportRefMess (DdManager *unique, int i, const char *caller);
Alan Mishchenko committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

/**AutomaticEnd***************************************************************/


/*---------------------------------------------------------------------------*/
/* Definition of exported functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Returns the next prime &gt;= p.]

  Description []

  SideEffects [None]

******************************************************************************/
unsigned int
Cudd_Prime(
  unsigned int  p)
{
    int i,pn;

    p--;
    do {
        p++;
        if (p&1) {
197 198 199 200 201 202 203 204 205 206
            pn = 1;
            i = 3;
            while ((unsigned) (i * i) <= p) {
                if (p % i == 0) {
                    pn = 0;
                    break;
                }
                i += 2;
            }
        } else {
Alan Mishchenko committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
            pn = 0;
        }
    } while (!pn);
    return(p);

} /* end of Cudd_Prime */


/*---------------------------------------------------------------------------*/
/* Definition of internal functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Fast storage allocation for DdNodes in the table.]

  Description [Fast storage allocation for DdNodes in the table. The
  first 4 bytes of a chunk contain a pointer to the next block; the
  rest contains DD_MEM_CHUNK spaces for DdNodes.  Returns a pointer to
  a new node if successful; NULL is memory is full.]

  SideEffects [None]

  SeeAlso     [cuddDynamicAllocNode]

******************************************************************************/
DdNode *
cuddAllocNode(
  DdManager * unique)
{
    int i;
    DdNodePtr *mem;
    DdNode *list, *node;
241 242 243 244 245 246 247 248 249
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;

    if (unique->nextFree == NULL) {     /* free list is empty */
        /* Check for exceeded limits. */
        if ((unique->keys - unique->dead) + (unique->keysZ - unique->deadZ) >
            unique->maxLive) {
            unique->errorCode = CUDD_TOO_MANY_NODES;
            return(NULL);
Alan Mishchenko committed
250
        }
251 252 253 254 255 256 257 258
        if (unique->stash == NULL || unique->memused > unique->maxmemhard) {
            (void) cuddGarbageCollect(unique,1);
            mem = NULL;
        }
        if (unique->nextFree == NULL) {
            if (unique->memused > unique->maxmemhard) {
                unique->errorCode = CUDD_MAX_MEM_EXCEEDED;
                return(NULL);
Alan Mishchenko committed
259
            }
260 261 262
            /* Try to allocate a new block. */
            saveHandler = MMoutOfMemory;
            MMoutOfMemory = Cudd_OutOfMem;
263 264
//            mem = (DdNodePtr *) ABC_ALLOC(DdNode,DD_MEM_CHUNK + 1);
            mem = (DdNodePtr *) ABC_ALLOC(DdNode,DD_MEM_CHUNK + 2);
265
            MMoutOfMemory = saveHandler;
Alan Mishchenko committed
266
            if (mem == NULL) {
267 268 269 270 271 272 273 274 275 276 277 278 279
                /* No more memory: Try collecting garbage. If this succeeds,
                ** we end up with mem still NULL, but unique->nextFree !=
                ** NULL. */
                if (cuddGarbageCollect(unique,1) == 0) {
                    /* Last resort: Free the memory stashed away, if there
                    ** any. If this succeeeds, mem != NULL and
                    ** unique->nextFree still NULL. */
                    if (unique->stash != NULL) {
                        ABC_FREE(unique->stash);
                        unique->stash = NULL;
                        /* Inhibit resizing of tables. */
                        cuddSlowTableGrowth(unique);
                        /* Now try again. */
280 281
//                        mem = (DdNodePtr *) ABC_ALLOC(DdNode,DD_MEM_CHUNK + 1);
                        mem = (DdNodePtr *) ABC_ALLOC(DdNode,DD_MEM_CHUNK + 2);
282 283 284 285 286 287 288 289
                    }
                    if (mem == NULL) {
                        /* Out of luck. Call the default handler to do
                        ** whatever it specifies for a failed malloc.
                        ** If this handler returns, then set error code,
                        ** print warning, and return. */
                        (*MMoutOfMemory)(sizeof(DdNode)*(DD_MEM_CHUNK + 1));
                        unique->errorCode = CUDD_MEMORY_OUT;
Alan Mishchenko committed
290
#ifdef DD_VERBOSE
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                        (void) fprintf(unique->err,
                                       "cuddAllocNode: out of memory");
                        (void) fprintf(unique->err, "Memory in use = %lu\n",
                                       unique->memused);
#endif
                        return(NULL);
                    }
                }
            }
            if (mem != NULL) {  /* successful allocation; slice memory */
                ptruint offset;
                unique->memused += (DD_MEM_CHUNK + 1) * sizeof(DdNode);
                mem[0] = (DdNodePtr) unique->memoryList;
                unique->memoryList = mem;

306 307 308 309 310 311 312 313
                /* Here we rely on the fact that a DdNode is as large as 4 pointers.  */
//                offset = (ptruint) mem & (sizeof(DdNode) - 1);
//                mem += (sizeof(DdNode) - offset) / sizeof(DdNodePtr);
//                assert(((ptruint) mem & (sizeof(DdNode) - 1)) == 0);
//                list = (DdNode *) mem;
                offset = (ptruint) mem & (32 - 1);
                mem += (32 - offset) / sizeof(DdNodePtr);
                assert(((ptruint) mem & (32 - 1)) == 0);
314 315 316 317 318 319 320 321 322 323 324 325
                list = (DdNode *) mem;

                i = 1;
                do {
                    list[i - 1].ref = 0;
                    list[i - 1].next = &list[i];
                } while (++i < DD_MEM_CHUNK);

                list[DD_MEM_CHUNK-1].ref = 0;
                list[DD_MEM_CHUNK-1].next = NULL;

                unique->nextFree = &list[0];
Alan Mishchenko committed
326 327 328 329 330 331
            }
        }
    }
    unique->allocated++;
    node = unique->nextFree;
    unique->nextFree = node->next;
332
    node->Id = (unique->allocated<<4);
Alan Mishchenko committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    return(node);

} /* end of cuddAllocNode */


/**Function********************************************************************

  Synopsis    [Creates and initializes the unique table.]

  Description [Creates and initializes the unique table. Returns a pointer
  to the table if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_Init cuddFreeTable]

******************************************************************************/
DdManager *
cuddInitTable(
  unsigned int numVars  /* Initial number of BDD variables (and subtables) */,
  unsigned int numVarsZ /* Initial number of ZDD variables (and subtables) */,
  unsigned int numSlots /* Initial size of the BDD subtables */,
  unsigned int looseUpTo /* Limit for fast table growth */)
{
357 358 359 360
    DdManager   *unique = ABC_ALLOC(DdManager,1);
    int         i, j;
    DdNodePtr   *nodelist;
    DdNode      *sentinel;
Alan Mishchenko committed
361 362 363 364
    unsigned int slots;
    int shift;

    if (unique == NULL) {
365
        return(NULL);
Alan Mishchenko committed
366 367 368 369 370 371 372 373 374 375
    }
    sentinel = &(unique->sentinel);
    sentinel->ref = 0;
    sentinel->index = 0;
    cuddT(sentinel) = NULL;
    cuddE(sentinel) = NULL;
    sentinel->next = NULL;
    unique->epsilon = DD_EPSILON;
    unique->maxGrowth = DD_MAX_REORDER_GROWTH;
    unique->maxGrowthAlt = 2.0 * DD_MAX_REORDER_GROWTH;
376
    unique->reordCycle = 0;     /* do not use alternate threshold */
Alan Mishchenko committed
377 378 379 380 381 382 383 384
    unique->size = numVars;
    unique->sizeZ = numVarsZ;
    unique->maxSize = ddMax(DD_DEFAULT_RESIZE, numVars);
    unique->maxSizeZ = ddMax(DD_DEFAULT_RESIZE, numVarsZ);

    /* Adjust the requested number of slots to a power of 2. */
    slots = 8;
    while (slots < numSlots) {
385
        slots <<= 1;
Alan Mishchenko committed
386 387 388 389 390 391
    }
    unique->initSlots = slots;
    shift = sizeof(int) * 8 - cuddComputeFloorLog2(slots);

    unique->slots = (numVars + numVarsZ + 1) * slots;
    unique->keys = 0;
392
    unique->maxLive = ~0;       /* very large number */
Alan Mishchenko committed
393 394 395 396 397 398 399 400 401
    unique->keysZ = 0;
    unique->dead = 0;
    unique->deadZ = 0;
    unique->gcFrac = DD_GC_FRAC_HI;
    unique->minDead = (unsigned) (DD_GC_FRAC_HI * (double) unique->slots);
    unique->looseUpTo = looseUpTo;
    unique->gcEnabled = 1;
    unique->allocated = 0;
    unique->reclaimed = 0;
Alan Mishchenko committed
402
    unique->subtables = ABC_ALLOC(DdSubtable,unique->maxSize);
Alan Mishchenko committed
403
    if (unique->subtables == NULL) {
404 405
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
406
    }
Alan Mishchenko committed
407
    unique->subtableZ = ABC_ALLOC(DdSubtable,unique->maxSizeZ);
Alan Mishchenko committed
408
    if (unique->subtableZ == NULL) {
409 410 411
        ABC_FREE(unique->subtables);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
412
    }
Alan Mishchenko committed
413
    unique->perm = ABC_ALLOC(int,unique->maxSize);
Alan Mishchenko committed
414
    if (unique->perm == NULL) {
415 416 417 418
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
419
    }
Alan Mishchenko committed
420
    unique->invperm = ABC_ALLOC(int,unique->maxSize);
Alan Mishchenko committed
421
    if (unique->invperm == NULL) {
422 423 424 425 426
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
427
    }
Alan Mishchenko committed
428
    unique->permZ = ABC_ALLOC(int,unique->maxSizeZ);
Alan Mishchenko committed
429
    if (unique->permZ == NULL) {
430 431 432 433 434 435
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique->invperm);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
436
    }
Alan Mishchenko committed
437
    unique->invpermZ = ABC_ALLOC(int,unique->maxSizeZ);
Alan Mishchenko committed
438
    if (unique->invpermZ == NULL) {
439 440 441 442 443 444 445
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique->invperm);
        ABC_FREE(unique->permZ);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
446 447
    }
    unique->map = NULL;
Alan Mishchenko committed
448
    unique->stack = ABC_ALLOC(DdNodePtr,ddMax(unique->maxSize,unique->maxSizeZ)+1);
Alan Mishchenko committed
449
    if (unique->stack == NULL) {
450 451 452 453 454 455 456 457
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique->invperm);
        ABC_FREE(unique->permZ);
        ABC_FREE(unique->invpermZ);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
458 459 460 461 462
    }
    unique->stack[0] = NULL; /* to suppress harmless UMR */

#ifndef DD_NO_DEATH_ROW
    unique->deathRowDepth = 1 << cuddComputeFloorLog2(unique->looseUpTo >> 2);
Alan Mishchenko committed
463
    unique->deathRow = ABC_ALLOC(DdNodePtr,unique->deathRowDepth);
Alan Mishchenko committed
464
    if (unique->deathRow == NULL) {
465 466 467 468 469 470 471 472 473
        ABC_FREE(unique->subtables);
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique->invperm);
        ABC_FREE(unique->permZ);
        ABC_FREE(unique->invpermZ);
        ABC_FREE(unique->stack);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
474 475
    }
    for (i = 0; i < unique->deathRowDepth; i++) {
476
        unique->deathRow[i] = NULL;
Alan Mishchenko committed
477 478 479 480 481 482
    }
    unique->nextDead = 0;
    unique->deadMask = unique->deathRowDepth - 1;
#endif

    for (i = 0; (unsigned) i < numVars; i++) {
483 484 485 486 487 488 489 490 491 492
        unique->subtables[i].slots = slots;
        unique->subtables[i].shift = shift;
        unique->subtables[i].keys = 0;
        unique->subtables[i].dead = 0;
        unique->subtables[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
        unique->subtables[i].bindVar = 0;
        unique->subtables[i].varType = CUDD_VAR_PRIMARY_INPUT;
        unique->subtables[i].pairIndex = 0;
        unique->subtables[i].varHandled = 0;
        unique->subtables[i].varToBeGrouped = CUDD_LAZY_NONE;
Alan Mishchenko committed
493

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        nodelist = unique->subtables[i].nodelist = ABC_ALLOC(DdNodePtr,slots);
        if (nodelist == NULL) {
            for (j = 0; j < i; j++) {
                ABC_FREE(unique->subtables[j].nodelist);
            }
            ABC_FREE(unique->subtables);
            ABC_FREE(unique->subtableZ);
            ABC_FREE(unique->perm);
            ABC_FREE(unique->invperm);
            ABC_FREE(unique->permZ);
            ABC_FREE(unique->invpermZ);
            ABC_FREE(unique->stack);
            ABC_FREE(unique);
            return(NULL);
        }
        for (j = 0; (unsigned) j < slots; j++) {
            nodelist[j] = sentinel;
        }
        unique->perm[i] = i;
        unique->invperm[i] = i;
Alan Mishchenko committed
514 515
    }
    for (i = 0; (unsigned) i < numVarsZ; i++) {
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
        unique->subtableZ[i].slots = slots;
        unique->subtableZ[i].shift = shift;
        unique->subtableZ[i].keys = 0;
        unique->subtableZ[i].dead = 0;
        unique->subtableZ[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
        nodelist = unique->subtableZ[i].nodelist = ABC_ALLOC(DdNodePtr,slots);
        if (nodelist == NULL) {
            for (j = 0; (unsigned) j < numVars; j++) {
                ABC_FREE(unique->subtables[j].nodelist);
            }
            ABC_FREE(unique->subtables);
            for (j = 0; j < i; j++) {
                ABC_FREE(unique->subtableZ[j].nodelist);
            }
            ABC_FREE(unique->subtableZ);
            ABC_FREE(unique->perm);
            ABC_FREE(unique->invperm);
            ABC_FREE(unique->permZ);
            ABC_FREE(unique->invpermZ);
            ABC_FREE(unique->stack);
            ABC_FREE(unique);
            return(NULL);
        }
        for (j = 0; (unsigned) j < slots; j++) {
            nodelist[j] = NULL;
        }
        unique->permZ[i] = i;
        unique->invpermZ[i] = i;
Alan Mishchenko committed
544 545 546 547 548 549
    }
    unique->constants.slots = slots;
    unique->constants.shift = shift;
    unique->constants.keys = 0;
    unique->constants.dead = 0;
    unique->constants.maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
Alan Mishchenko committed
550
    nodelist = unique->constants.nodelist = ABC_ALLOC(DdNodePtr,slots);
Alan Mishchenko committed
551
    if (nodelist == NULL) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        for (j = 0; (unsigned) j < numVars; j++) {
            ABC_FREE(unique->subtables[j].nodelist);
        }
        ABC_FREE(unique->subtables);
        for (j = 0; (unsigned) j < numVarsZ; j++) {
            ABC_FREE(unique->subtableZ[j].nodelist);
        }
        ABC_FREE(unique->subtableZ);
        ABC_FREE(unique->perm);
        ABC_FREE(unique->invperm);
        ABC_FREE(unique->permZ);
        ABC_FREE(unique->invpermZ);
        ABC_FREE(unique->stack);
        ABC_FREE(unique);
        return(NULL);
Alan Mishchenko committed
567 568
    }
    for (j = 0; (unsigned) j < slots; j++) {
569
        nodelist[j] = NULL;
Alan Mishchenko committed
570 571 572 573 574 575
    }

    unique->memoryList = NULL;
    unique->nextFree = NULL;

    unique->memused = sizeof(DdManager) + (unique->maxSize + unique->maxSizeZ)
576 577 578
        * (sizeof(DdSubtable) + 2 * sizeof(int)) + (numVars + 1) *
        slots * sizeof(DdNodePtr) +
        (ddMax(unique->maxSize,unique->maxSizeZ) + 1) * sizeof(DdNodePtr);
Alan Mishchenko committed
579 580 581 582 583 584
#ifndef DD_NO_DEATH_ROW
    unique->memused += unique->deathRowDepth * sizeof(DdNodePtr);
#endif

    /* Initialize fields concerned with automatic dynamic reordering */
    unique->reorderings = 0;
585 586 587 588
    unique->autoDyn = 0;        /* initially disabled */
    unique->autoDynZ = 0;       /* initially disabled */
    unique->realign = 0;        /* initially disabled */
    unique->realignZ = 0;       /* initially disabled */
Alan Mishchenko committed
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 617 618 619 620
    unique->reordered = 0;
    unique->autoMethod = CUDD_REORDER_SIFT;
    unique->autoMethodZ = CUDD_REORDER_SIFT;
    unique->nextDyn = DD_FIRST_REORDER;
    unique->countDead = ~0;
    unique->siftMaxVar = DD_SIFT_MAX_VAR;
    unique->siftMaxSwap = DD_SIFT_MAX_SWAPS;
    unique->tree = NULL;
    unique->treeZ = NULL;
    unique->groupcheck = CUDD_GROUP_CHECK7;
    unique->recomb = DD_DEFAULT_RECOMB;
    unique->symmviolation = 0;
    unique->arcviolation = 0;
    unique->populationSize = 0;
    unique->numberXovers = 0;
    unique->linear = NULL;
    unique->linearSize = 0;

    /* Initialize ZDD universe. */
    unique->univ = (DdNodePtr *)NULL;

    /* Initialize auxiliary fields. */
    unique->localCaches = NULL;
    unique->preGCHook = NULL;
    unique->postGCHook = NULL;
    unique->preReorderingHook = NULL;
    unique->postReorderingHook = NULL;
    unique->out = stdout;
    unique->err = stderr;
    unique->errorCode = CUDD_NO_ERROR;

    /* Initialize statistical counters. */
621
    unique->maxmemhard = ~ 0UL;
Alan Mishchenko committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    unique->garbageCollections = 0;
    unique->GCTime = 0;
    unique->reordTime = 0;
#ifdef DD_STATS
    unique->nodesDropped = 0;
    unique->nodesFreed = 0;
#endif
    unique->peakLiveNodes = 0;
#ifdef DD_UNIQUE_PROFILE
    unique->uniqueLookUps = 0;
    unique->uniqueLinks = 0;
#endif
#ifdef DD_COUNT
    unique->recursiveCalls = 0;
    unique->swapSteps = 0;
#ifdef DD_STATS
    unique->nextSample = 250000;
#endif
#endif

    return(unique);

} /* end of cuddInitTable */


/**Function********************************************************************

  Synopsis    [Frees the resources associated to a unique table.]

  Description []

  SideEffects [None]

  SeeAlso     [cuddInitTable]

******************************************************************************/
void
cuddFreeTable(
  DdManager * unique)
{
    DdNodePtr *next;
    DdNodePtr *memlist = unique->memoryList;
    int i;

    if (unique->univ != NULL) cuddZddFreeUniv(unique);
    while (memlist != NULL) {
668 669 670
        next = (DdNodePtr *) memlist[0];        /* link to next block */
        ABC_FREE(memlist);
        memlist = next;
Alan Mishchenko committed
671 672 673 674 675
    }
    unique->nextFree = NULL;
    unique->memoryList = NULL;

    for (i = 0; i < unique->size; i++) {
676
        ABC_FREE(unique->subtables[i].nodelist);
Alan Mishchenko committed
677 678
    }
    for (i = 0; i < unique->sizeZ; i++) {
679
        ABC_FREE(unique->subtableZ[i].nodelist);
Alan Mishchenko committed
680 681 682 683 684 685 686 687 688 689 690 691
    }
    ABC_FREE(unique->constants.nodelist);
    ABC_FREE(unique->subtables);
    ABC_FREE(unique->subtableZ);
    ABC_FREE(unique->acache);
    ABC_FREE(unique->perm);
    ABC_FREE(unique->permZ);
    ABC_FREE(unique->invperm);
    ABC_FREE(unique->invpermZ);
    ABC_FREE(unique->vars);
    if (unique->map != NULL) ABC_FREE(unique->map);
    ABC_FREE(unique->stack);
Alan Mishchenko committed
692
#ifndef DD_NO_DEATH_ROW
Alan Mishchenko committed
693
    ABC_FREE(unique->deathRow);
Alan Mishchenko committed
694 695 696
#endif
    if (unique->tree != NULL) Mtr_FreeTree(unique->tree);
    if (unique->treeZ != NULL) Mtr_FreeTree(unique->treeZ);
Alan Mishchenko committed
697
    if (unique->linear != NULL) ABC_FREE(unique->linear);
Alan Mishchenko committed
698
    while (unique->preGCHook != NULL)
699
        Cudd_RemoveHook(unique,unique->preGCHook->f,CUDD_PRE_GC_HOOK);
Alan Mishchenko committed
700
    while (unique->postGCHook != NULL)
701
        Cudd_RemoveHook(unique,unique->postGCHook->f,CUDD_POST_GC_HOOK);
Alan Mishchenko committed
702
    while (unique->preReorderingHook != NULL)
703 704
        Cudd_RemoveHook(unique,unique->preReorderingHook->f,
                        CUDD_PRE_REORDERING_HOOK);
Alan Mishchenko committed
705
    while (unique->postReorderingHook != NULL)
706 707
        Cudd_RemoveHook(unique,unique->postReorderingHook->f,
                        CUDD_POST_REORDERING_HOOK);
Alan Mishchenko committed
708
    ABC_FREE(unique);
Alan Mishchenko committed
709 710 711 712 713 714

} /* end of cuddFreeTable */


/**Function********************************************************************

715
  Synopsis    [Performs garbage collection on the unique tables.]
Alan Mishchenko committed
716

717
  Description [Performs garbage collection on the BDD and ZDD unique tables.
Alan Mishchenko committed
718 719 720 721 722 723 724
  If clearCache is 0, the cache is not cleared. This should only be
  specified if the cache has been cleared right before calling
  cuddGarbageCollect. (As in the case of dynamic reordering.)
  Returns the total number of deleted nodes.]

  SideEffects [None]

725
  SeeAlso     []
Alan Mishchenko committed
726 727 728 729 730 731 732

******************************************************************************/
int
cuddGarbageCollect(
  DdManager * unique,
  int  clearCache)
{
733 734 735 736 737 738 739 740 741 742
    DdHook      *hook;
    DdCache     *cache = unique->cache;
    DdNode      *sentinel = &(unique->sentinel);
    DdNodePtr   *nodelist;
    int         i, j, deleted, totalDeleted, totalDeletedZ;
    DdCache     *c;
    DdNode      *node,*next;
    DdNodePtr   *lastP;
    int         slots;
    long        localTime;
Alan Mishchenko committed
743
#ifndef DD_UNSORTED_FREE_LIST
744 745 746 747 748 749 750
#ifdef DD_RED_BLACK_FREE_LIST
    DdNodePtr   tree;
#else
    DdNodePtr *memListTrav, *nxtNode;
    DdNode *downTrav, *sentry;
    int k;
#endif
Alan Mishchenko committed
751 752 753 754 755 756 757 758
#endif

#ifndef DD_NO_DEATH_ROW
    cuddClearDeathRow(unique);
#endif

    hook = unique->preGCHook;
    while (hook != NULL) {
759
        int res = (hook->f)(unique,"DD",NULL);
Alan Mishchenko committed
760 761 762
        if (res == 0) return(0);
        hook = hook->next;
    }
763 764 765 766 767 768 769 770

    if (unique->dead + unique->deadZ == 0) {
        hook = unique->postGCHook;
        while (hook != NULL) {
            int res = (hook->f)(unique,"DD",NULL);
            if (res == 0) return(0);
            hook = hook->next;
        }
Alan Mishchenko committed
771 772 773 774 775 776 777
        return(0);
    }

    /* If many nodes are being reclaimed, we want to resize the tables
    ** more aggressively, to reduce the frequency of garbage collection.
    */
    if (clearCache && unique->gcFrac == DD_GC_FRAC_LO &&
778 779
        unique->slots <= unique->looseUpTo && unique->stash != NULL) {
        unique->minDead = (unsigned) (DD_GC_FRAC_HI * (double) unique->slots);
Alan Mishchenko committed
780
#ifdef DD_VERBOSE
781 782
        (void) fprintf(unique->err,"GC fraction = %.2f\t", DD_GC_FRAC_HI);
        (void) fprintf(unique->err,"minDead = %d\n", unique->minDead);
Alan Mishchenko committed
783
#endif
784 785
        unique->gcFrac = DD_GC_FRAC_HI;
        return(0);
Alan Mishchenko committed
786 787 788 789 790 791 792
    }

    localTime = util_cpu_time();

    unique->garbageCollections++;
#ifdef DD_VERBOSE
    (void) fprintf(unique->err,
793 794 795 796 797
                   "garbage collecting (%d dead BDD nodes out of %d, min %d)...",
                   unique->dead, unique->keys, unique->minDead);
    (void) fprintf(unique->err,
                   "                   (%d dead ZDD nodes out of %d)...",
                   unique->deadZ, unique->keysZ);
Alan Mishchenko committed
798 799 800 801
#endif

    /* Remove references to garbage collected nodes from the cache. */
    if (clearCache) {
802 803 804 805 806 807 808 809 810 811 812 813 814
        slots = unique->cacheSlots;
        for (i = 0; i < slots; i++) {
            c = &cache[i];
            if (c->data != NULL) {
                if (cuddClean(c->f)->ref == 0 ||
                cuddClean(c->g)->ref == 0 ||
                (((ptruint)c->f & 0x2) && Cudd_Regular(c->h)->ref == 0) ||
                (c->data != DD_NON_CONSTANT &&
                Cudd_Regular(c->data)->ref == 0)) {
                    c->data = NULL;
                    unique->cachedeletions++;
                }
            }
Alan Mishchenko committed
815
        }
816
        cuddLocalCacheClearDead(unique);
Alan Mishchenko committed
817 818
    }

819
    /* Now return dead nodes to free list. Count them for sanity check. */
Alan Mishchenko committed
820 821
    totalDeleted = 0;
#ifndef DD_UNSORTED_FREE_LIST
822
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
823 824
    tree = NULL;
#endif
825
#endif
Alan Mishchenko committed
826 827

    for (i = 0; i < unique->size; i++) {
828 829 830 831 832 833 834 835 836 837 838 839
        if (unique->subtables[i].dead == 0) continue;
        nodelist = unique->subtables[i].nodelist;

        deleted = 0;
        slots = unique->subtables[i].slots;
        for (j = 0; j < slots; j++) {
            lastP = &(nodelist[j]);
            node = *lastP;
            while (node != sentinel) {
                next = node->next;
                if (node->ref == 0) {
                    deleted++;
Alan Mishchenko committed
840
#ifndef DD_UNSORTED_FREE_LIST
841
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
842 843 844 845
#ifdef __osf__
#pragma pointer_size save
#pragma pointer_size short
#endif
846
                    cuddOrderedInsert(&tree,node);
Alan Mishchenko committed
847 848 849
#ifdef __osf__
#pragma pointer_size restore
#endif
850
#endif
Alan Mishchenko committed
851
#else
852
                    cuddDeallocNode(unique,node);
Alan Mishchenko committed
853
#endif
854 855 856 857 858 859 860
                } else {
                    *lastP = node;
                    lastP = &(node->next);
                }
                node = next;
            }
            *lastP = sentinel;
Alan Mishchenko committed
861
        }
862 863
        if ((unsigned) deleted != unique->subtables[i].dead) {
            ddReportRefMess(unique, i, "cuddGarbageCollect");
Alan Mishchenko committed
864
        }
865 866 867
        totalDeleted += deleted;
        unique->subtables[i].keys -= deleted;
        unique->subtables[i].dead = 0;
Alan Mishchenko committed
868 869
    }
    if (unique->constants.dead != 0) {
870 871 872 873 874 875 876 877 878 879
        nodelist = unique->constants.nodelist;
        deleted = 0;
        slots = unique->constants.slots;
        for (j = 0; j < slots; j++) {
            lastP = &(nodelist[j]);
            node = *lastP;
            while (node != NULL) {
                next = node->next;
                if (node->ref == 0) {
                    deleted++;
Alan Mishchenko committed
880
#ifndef DD_UNSORTED_FREE_LIST
881
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
882 883 884 885
#ifdef __osf__
#pragma pointer_size save
#pragma pointer_size short
#endif
886
                    cuddOrderedInsert(&tree,node);
Alan Mishchenko committed
887 888 889
#ifdef __osf__
#pragma pointer_size restore
#endif
890
#endif
Alan Mishchenko committed
891
#else
892
                    cuddDeallocNode(unique,node);
Alan Mishchenko committed
893
#endif
894 895 896 897 898 899 900
                } else {
                    *lastP = node;
                    lastP = &(node->next);
                }
                node = next;
            }
            *lastP = NULL;
Alan Mishchenko committed
901
        }
902 903 904 905 906 907
        if ((unsigned) deleted != unique->constants.dead) {
            ddReportRefMess(unique, CUDD_CONST_INDEX, "cuddGarbageCollect");
        }
        totalDeleted += deleted;
        unique->constants.keys -= deleted;
        unique->constants.dead = 0;
Alan Mishchenko committed
908 909
    }
    if ((unsigned) totalDeleted != unique->dead) {
910
        ddReportRefMess(unique, -1, "cuddGarbageCollect");
Alan Mishchenko committed
911 912 913 914 915 916 917
    }
    unique->keys -= totalDeleted;
    unique->dead = 0;
#ifdef DD_STATS
    unique->nodesFreed += (double) totalDeleted;
#endif

918
    totalDeletedZ = 0;
Alan Mishchenko committed
919 920

    for (i = 0; i < unique->sizeZ; i++) {
921 922 923 924 925 926 927 928 929 930 931 932
        if (unique->subtableZ[i].dead == 0) continue;
        nodelist = unique->subtableZ[i].nodelist;

        deleted = 0;
        slots = unique->subtableZ[i].slots;
        for (j = 0; j < slots; j++) {
            lastP = &(nodelist[j]);
            node = *lastP;
            while (node != NULL) {
                next = node->next;
                if (node->ref == 0) {
                    deleted++;
Alan Mishchenko committed
933
#ifndef DD_UNSORTED_FREE_LIST
934
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
935 936 937 938
#ifdef __osf__
#pragma pointer_size save
#pragma pointer_size short
#endif
939
                    cuddOrderedInsert(&tree,node);
Alan Mishchenko committed
940 941 942
#ifdef __osf__
#pragma pointer_size restore
#endif
943
#endif
Alan Mishchenko committed
944
#else
945
                    cuddDeallocNode(unique,node);
Alan Mishchenko committed
946
#endif
947 948 949 950 951 952 953
                } else {
                    *lastP = node;
                    lastP = &(node->next);
                }
                node = next;
            }
            *lastP = NULL;
Alan Mishchenko committed
954
        }
955 956 957 958 959 960
        if ((unsigned) deleted != unique->subtableZ[i].dead) {
            ddReportRefMess(unique, i, "cuddGarbageCollect");
        }
        totalDeletedZ += deleted;
        unique->subtableZ[i].keys -= deleted;
        unique->subtableZ[i].dead = 0;
Alan Mishchenko committed
961 962 963 964 965
    }

    /* No need to examine the constant table for ZDDs.
    ** If we did we should be careful not to count whatever dead
    ** nodes we found there among the dead ZDD nodes. */
966 967
    if ((unsigned) totalDeletedZ != unique->deadZ) {
        ddReportRefMess(unique, -1, "cuddGarbageCollect");
Alan Mishchenko committed
968
    }
969
    unique->keysZ -= totalDeletedZ;
Alan Mishchenko committed
970 971
    unique->deadZ = 0;
#ifdef DD_STATS
972
    unique->nodesFreed += (double) totalDeletedZ;
Alan Mishchenko committed
973 974
#endif

975

Alan Mishchenko committed
976
#ifndef DD_UNSORTED_FREE_LIST
977
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
978
    unique->nextFree = cuddOrderedThread(tree,unique->nextFree);
979 980 981 982 983 984
#else
    memListTrav = unique->memoryList;
    sentry = NULL;
    while (memListTrav != NULL) {
        ptruint offset;
        nxtNode = (DdNodePtr *)memListTrav[0];
985 986 987 988 989
//        offset = (ptruint) memListTrav & (sizeof(DdNode) - 1);
//        memListTrav += (sizeof(DdNode) - offset) / sizeof(DdNodePtr);
        offset = (ptruint) memListTrav & (32 - 1);
        memListTrav += (32 - offset) / sizeof(DdNodePtr);

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
        downTrav = (DdNode *)memListTrav;
        k = 0;
        do {
            if (downTrav[k].ref == 0) {
                if (sentry == NULL) {
                    unique->nextFree = sentry = &downTrav[k];
                } else {
                    /* First hook sentry->next to the dead node and then
                    ** reassign sentry to the dead node. */
                    sentry = (sentry->next = &downTrav[k]);
                }
            }
        } while (++k < DD_MEM_CHUNK);
        memListTrav = nxtNode;
    }
    sentry->next = NULL;
#endif
Alan Mishchenko committed
1007 1008 1009 1010 1011 1012
#endif

    unique->GCTime += util_cpu_time() - localTime;

    hook = unique->postGCHook;
    while (hook != NULL) {
1013 1014 1015
        int res = (hook->f)(unique,"DD",NULL);
        if (res == 0) return(0);
        hook = hook->next;
Alan Mishchenko committed
1016 1017 1018 1019 1020 1021
    }

#ifdef DD_VERBOSE
    (void) fprintf(unique->err," done\n");
#endif

1022
    return(totalDeleted+totalDeletedZ);
Alan Mishchenko committed
1023

1024
} /* end of cuddGarbageCollect */
Alan Mishchenko committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046


/**Function********************************************************************

  Synopsis [Wrapper for cuddUniqueInterZdd.]

  Description [Wrapper for cuddUniqueInterZdd, which applies the ZDD
  reduction rule. Returns a pointer to the result node under normal
  conditions; NULL if reordering occurred or memory was exhausted.]

  SideEffects [None]

  SeeAlso     [cuddUniqueInterZdd]

******************************************************************************/
DdNode *
cuddZddGetNode(
  DdManager * zdd,
  int  id,
  DdNode * T,
  DdNode * E)
{
1047
    DdNode      *node;
Alan Mishchenko committed
1048 1049

    if (T == DD_ZERO(zdd))
1050
        return(E);
Alan Mishchenko committed
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 1076 1077 1078 1079
    node = cuddUniqueInterZdd(zdd, id, T, E);
    return(node);

} /* end of cuddZddGetNode */


/**Function********************************************************************

  Synopsis [Wrapper for cuddUniqueInterZdd that is independent of variable
  ordering.]

  Description [Wrapper for cuddUniqueInterZdd that is independent of
  variable ordering (IVO). This function does not require parameter
  index to precede the indices of the top nodes of g and h in the
  variable order.  Returns a pointer to the result node under normal
  conditions; NULL if reordering occurred or memory was exhausted.]

  SideEffects [None]

  SeeAlso     [cuddZddGetNode cuddZddIsop]

******************************************************************************/
DdNode *
cuddZddGetNodeIVO(
  DdManager * dd,
  int  index,
  DdNode * g,
  DdNode * h)
{
1080 1081 1082
    DdNode      *f, *r, *t;
    DdNode      *zdd_one = DD_ONE(dd);
    DdNode      *zdd_zero = DD_ZERO(dd);
Alan Mishchenko committed
1083 1084 1085

    f = cuddUniqueInterZdd(dd, index, zdd_one, zdd_zero);
    if (f == NULL) {
1086
        return(NULL);
Alan Mishchenko committed
1087 1088 1089 1090
    }
    cuddRef(f);
    t = cuddZddProduct(dd, f, g);
    if (t == NULL) {
1091 1092
        Cudd_RecursiveDerefZdd(dd, f);
        return(NULL);
Alan Mishchenko committed
1093 1094 1095 1096 1097
    }
    cuddRef(t);
    Cudd_RecursiveDerefZdd(dd, f);
    r = cuddZddUnion(dd, t, h);
    if (r == NULL) {
1098 1099
        Cudd_RecursiveDerefZdd(dd, t);
        return(NULL);
Alan Mishchenko committed
1100 1101 1102 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 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    }
    cuddRef(r);
    Cudd_RecursiveDerefZdd(dd, t);

    cuddDeref(r);
    return(r);

} /* end of cuddZddGetNodeIVO */


/**Function********************************************************************

  Synopsis    [Checks the unique table for the existence of an internal node.]

  Description [Checks the unique table for the existence of an internal
  node. If it does not exist, it creates a new one.  Does not
  modify the reference count of whatever is returned.  A newly created
  internal node comes back with a reference count 0.  For a newly
  created node, increments the reference counts of what T and E point
  to.  Returns a pointer to the new node if successful; NULL if memory
  is exhausted or if reordering took place.]

  SideEffects [None]

  SeeAlso     [cuddUniqueInterZdd]

******************************************************************************/
DdNode *
cuddUniqueInter(
  DdManager * unique,
  int  index,
  DdNode * T,
  DdNode * E)
{
    int pos;
    unsigned int level;
    int retval;
    DdNodePtr *nodelist;
    DdNode *looking;
    DdNodePtr *previousP;
    DdSubtable *subtable;
    int gcNumber;

#ifdef DD_UNIQUE_PROFILE
    unique->uniqueLookUps++;
#endif

    if (index >= unique->size) {
1148
        if (!ddResizeTable(unique,index)) return(NULL);
Alan Mishchenko committed
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    }

    level = unique->perm[index];
    subtable = &(unique->subtables[level]);

#ifdef DD_DEBUG
    assert(level < (unsigned) cuddI(unique,T->index));
    assert(level < (unsigned) cuddI(unique,Cudd_Regular(E)->index));
#endif

1159
    pos = ddHash(cuddF2L(T), cuddF2L(E), subtable->shift);
Alan Mishchenko committed
1160 1161 1162 1163 1164
    nodelist = subtable->nodelist;
    previousP = &(nodelist[pos]);
    looking = *previousP;

    while (T < cuddT(looking)) {
1165 1166
        previousP = &(looking->next);
        looking = *previousP;
Alan Mishchenko committed
1167
#ifdef DD_UNIQUE_PROFILE
1168
        unique->uniqueLinks++;
Alan Mishchenko committed
1169 1170 1171
#endif
    }
    while (T == cuddT(looking) && E < cuddE(looking)) {
1172 1173
        previousP = &(looking->next);
        looking = *previousP;
Alan Mishchenko committed
1174
#ifdef DD_UNIQUE_PROFILE
1175
        unique->uniqueLinks++;
Alan Mishchenko committed
1176 1177 1178
#endif
    }
    if (T == cuddT(looking) && E == cuddE(looking)) {
1179 1180 1181 1182
        if (looking->ref == 0) {
            cuddReclaim(unique,looking);
        }
        return(looking);
Alan Mishchenko committed
1183 1184 1185 1186 1187 1188
    }

    /* countDead is 0 if deads should be counted and ~0 if they should not. */
    if (unique->autoDyn &&
    unique->keys - (unique->dead & unique->countDead) >= unique->nextDyn) {
#ifdef DD_DEBUG
1189 1190 1191 1192
        retval = Cudd_DebugCheck(unique);
        if (retval != 0) return(NULL);
        retval = Cudd_CheckKeys(unique);
        if (retval != 0) return(NULL);
Alan Mishchenko committed
1193
#endif
1194 1195
        retval = Cudd_ReduceHeap(unique,unique->autoMethod,10); /* 10 = whatever */
        if (retval == 0) unique->reordered = 2;
Alan Mishchenko committed
1196
#ifdef DD_DEBUG
1197 1198 1199 1200
        retval = Cudd_DebugCheck(unique);
        if (retval != 0) unique->reordered = 2;
        retval = Cudd_CheckKeys(unique);
        if (retval != 0) unique->reordered = 2;
Alan Mishchenko committed
1201
#endif
1202
        return(NULL);
Alan Mishchenko committed
1203 1204 1205 1206
    }

    if (subtable->keys > subtable->maxKeys) {
        if (unique->gcEnabled &&
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
            ((unique->dead > unique->minDead) ||
            ((unique->dead > unique->minDead / 2) &&
            (subtable->dead > subtable->keys * 0.95)))) { /* too many dead */
            (void) cuddGarbageCollect(unique,1);
        } else {
            cuddRehash(unique,(int)level);
        }
        /* Update pointer to insertion point. In the case of rehashing,
        ** the slot may have changed. In the case of garbage collection,
        ** the predecessor may have been dead. */
1217
        pos = ddHash(cuddF2L(T), cuddF2L(E), subtable->shift);
1218 1219
        nodelist = subtable->nodelist;
        previousP = &(nodelist[pos]);
Alan Mishchenko committed
1220
        looking = *previousP;
1221 1222 1223 1224

        while (T < cuddT(looking)) {
            previousP = &(looking->next);
            looking = *previousP;
Alan Mishchenko committed
1225
#ifdef DD_UNIQUE_PROFILE
1226
            unique->uniqueLinks++;
Alan Mishchenko committed
1227
#endif
1228 1229 1230 1231
        }
        while (T == cuddT(looking) && E < cuddE(looking)) {
            previousP = &(looking->next);
            looking = *previousP;
Alan Mishchenko committed
1232
#ifdef DD_UNIQUE_PROFILE
1233
            unique->uniqueLinks++;
Alan Mishchenko committed
1234
#endif
1235
        }
Alan Mishchenko committed
1236 1237 1238 1239 1240
    }

    gcNumber = unique->garbageCollections;
    looking = cuddAllocNode(unique);
    if (looking == NULL) {
1241
        return(NULL);
Alan Mishchenko committed
1242 1243 1244 1245 1246
    }
    unique->keys++;
    subtable->keys++;

    if (gcNumber != unique->garbageCollections) {
1247
        DdNode *looking2;
1248
        pos = ddHash(cuddF2L(T), cuddF2L(E), subtable->shift);
1249 1250
        nodelist = subtable->nodelist;
        previousP = &(nodelist[pos]);
Alan Mishchenko committed
1251
        looking2 = *previousP;
1252 1253 1254 1255

        while (T < cuddT(looking2)) {
            previousP = &(looking2->next);
            looking2 = *previousP;
Alan Mishchenko committed
1256
#ifdef DD_UNIQUE_PROFILE
1257
            unique->uniqueLinks++;
Alan Mishchenko committed
1258
#endif
1259 1260 1261 1262
        }
        while (T == cuddT(looking2) && E < cuddE(looking2)) {
            previousP = &(looking2->next);
            looking2 = *previousP;
Alan Mishchenko committed
1263
#ifdef DD_UNIQUE_PROFILE
1264
            unique->uniqueLinks++;
Alan Mishchenko committed
1265
#endif
1266
        }
Alan Mishchenko committed
1267 1268 1269 1270 1271 1272
    }
    looking->index = index;
    cuddT(looking) = T;
    cuddE(looking) = E;
    looking->next = *previousP;
    *previousP = looking;
1273
    cuddSatInc(T->ref);         /* we know T is a regular pointer */
Alan Mishchenko committed
1274 1275 1276 1277 1278 1279
    cuddRef(E);

#ifdef DD_DEBUG
    cuddCheckCollisionOrdering(unique,level,pos);
#endif

1280 1281
//    assert( Cudd_Regular(T)->Id < 100000000 );
//    assert( Cudd_Regular(E)->Id < 100000000 );
Alan Mishchenko committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    return(looking);

} /* end of cuddUniqueInter */


/**Function********************************************************************

  Synopsis [Wrapper for cuddUniqueInter that is independent of variable
  ordering.]

  Description [Wrapper for cuddUniqueInter that is independent of
  variable ordering (IVO). This function does not require parameter
  index to precede the indices of the top nodes of T and E in the
  variable order.  Returns a pointer to the result node under normal
  conditions; NULL if reordering occurred or memory was exhausted.]

  SideEffects [None]

  SeeAlso     [cuddUniqueInter Cudd_MakeBddFromZddCover]

******************************************************************************/
DdNode *
cuddUniqueInterIVO(
  DdManager * unique,
  int  index,
  DdNode * T,
  DdNode * E)
{
    DdNode *result;
    DdNode *v;

    v = cuddUniqueInter(unique, index, DD_ONE(unique),
1314
                        Cudd_Not(DD_ONE(unique)));
Alan Mishchenko committed
1315
    if (v == NULL)
1316
        return(NULL);
Alan Mishchenko committed
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    cuddRef(v);
    result = cuddBddIteRecur(unique, v, T, E);
    Cudd_RecursiveDeref(unique, v);
    return(result);
}


/**Function********************************************************************

  Synopsis    [Checks the unique table for the existence of an internal
  ZDD node.]

  Description [Checks the unique table for the existence of an internal
  ZDD node. If it does not exist, it creates a new one.  Does not
  modify the reference count of whatever is returned.  A newly created
  internal node comes back with a reference count 0.  For a newly
  created node, increments the reference counts of what T and E point
  to.  Returns a pointer to the new node if successful; NULL if memory
  is exhausted or if reordering took place.]

  SideEffects [None]

  SeeAlso     [cuddUniqueInter]

******************************************************************************/
DdNode *
cuddUniqueInterZdd(
  DdManager * unique,
  int  index,
  DdNode * T,
  DdNode * E)
{
    int pos;
    unsigned int level;
    int retval;
    DdNodePtr *nodelist;
    DdNode *looking;
    DdSubtable *subtable;

#ifdef DD_UNIQUE_PROFILE
    unique->uniqueLookUps++;
#endif

    if (index >= unique->sizeZ) {
1361
        if (!cuddResizeTableZdd(unique,index)) return(NULL);
Alan Mishchenko committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    }

    level = unique->permZ[index];
    subtable = &(unique->subtableZ[level]);

#ifdef DD_DEBUG
    assert(level < (unsigned) cuddIZ(unique,T->index));
    assert(level < (unsigned) cuddIZ(unique,Cudd_Regular(E)->index));
#endif

    if (subtable->keys > subtable->maxKeys) {
        if (unique->gcEnabled && ((unique->deadZ > unique->minDead) ||
1374 1375 1376 1377 1378
        (10 * subtable->dead > 9 * subtable->keys))) {  /* too many dead */
            (void) cuddGarbageCollect(unique,1);
        } else {
            ddRehashZdd(unique,(int)level);
        }
Alan Mishchenko committed
1379 1380
    }

1381
    pos = ddHash(cuddF2L(T), cuddF2L(E), subtable->shift);
Alan Mishchenko committed
1382 1383 1384 1385 1386
    nodelist = subtable->nodelist;
    looking = nodelist[pos];

    while (looking != NULL) {
        if (cuddT(looking) == T && cuddE(looking) == E) {
1387 1388 1389 1390
            if (looking->ref == 0) {
                cuddReclaimZdd(unique,looking);
            }
            return(looking);
Alan Mishchenko committed
1391
        }
1392
        looking = looking->next;
Alan Mishchenko committed
1393
#ifdef DD_UNIQUE_PROFILE
1394
        unique->uniqueLinks++;
Alan Mishchenko committed
1395 1396 1397 1398 1399 1400 1401
#endif
    }

    /* countDead is 0 if deads should be counted and ~0 if they should not. */
    if (unique->autoDynZ &&
    unique->keysZ - (unique->deadZ & unique->countDead) >= unique->nextDyn) {
#ifdef DD_DEBUG
1402 1403 1404 1405
        retval = Cudd_DebugCheck(unique);
        if (retval != 0) return(NULL);
        retval = Cudd_CheckKeys(unique);
        if (retval != 0) return(NULL);
Alan Mishchenko committed
1406
#endif
1407 1408
        retval = Cudd_zddReduceHeap(unique,unique->autoMethodZ,10); /* 10 = whatever */
        if (retval == 0) unique->reordered = 2;
Alan Mishchenko committed
1409
#ifdef DD_DEBUG
1410 1411 1412 1413
        retval = Cudd_DebugCheck(unique);
        if (retval != 0) unique->reordered = 2;
        retval = Cudd_CheckKeys(unique);
        if (retval != 0) unique->reordered = 2;
Alan Mishchenko committed
1414
#endif
1415
        return(NULL);
Alan Mishchenko committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
    }

    unique->keysZ++;
    subtable->keys++;

    looking = cuddAllocNode(unique);
    if (looking == NULL) return(NULL);
    looking->index = index;
    cuddT(looking) = T;
    cuddE(looking) = E;
    looking->next = nodelist[pos];
    nodelist[pos] = looking;
    cuddRef(T);
    cuddRef(E);

    return(looking);

} /* end of cuddUniqueInterZdd */


/**Function********************************************************************

  Synopsis    [Checks the unique table for the existence of a constant node.]

  Description [Checks the unique table for the existence of a constant node.
  If it does not exist, it creates a new one.  Does not
  modify the reference count of whatever is returned.  A newly created
  internal node comes back with a reference count 0.  Returns a
  pointer to the new node.]

  SideEffects [None]

******************************************************************************/
DdNode *
cuddUniqueConst(
  DdManager * unique,
  CUDD_VALUE_TYPE  value)
{
    int pos;
    DdNodePtr *nodelist;
    DdNode *looking;
    hack split;

#ifdef DD_UNIQUE_PROFILE
    unique->uniqueLookUps++;
#endif

    if (unique->constants.keys > unique->constants.maxKeys) {
        if (unique->gcEnabled && ((unique->dead > unique->minDead) ||
1465 1466 1467 1468 1469
        (10 * unique->constants.dead > 9 * unique->constants.keys))) {  /* too many dead */
            (void) cuddGarbageCollect(unique,1);
        } else {
            cuddRehash(unique,CUDD_CONST_INDEX);
        }
Alan Mishchenko committed
1470 1471 1472 1473 1474
    }

    cuddAdjust(value); /* for the case of crippled infinities */

    if (ddAbs(value) < unique->epsilon) {
1475
        value = 0.0;
Alan Mishchenko committed
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    }
    split.value = value;

    pos = ddHash(split.bits[0], split.bits[1], unique->constants.shift);
    nodelist = unique->constants.nodelist;
    looking = nodelist[pos];

    /* Here we compare values both for equality and for difference less
     * than epsilon. The first comparison is required when values are
     * infinite, since Infinity - Infinity is NaN and NaN < X is 0 for
     * every X.
     */
    while (looking != NULL) {
        if (looking->type.value == value ||
1490 1491 1492 1493 1494
        ddEqualVal(looking->type.value,value,unique->epsilon)) {
            if (looking->ref == 0) {
                cuddReclaim(unique,looking);
            }
            return(looking);
Alan Mishchenko committed
1495
        }
1496
        looking = looking->next;
Alan Mishchenko committed
1497
#ifdef DD_UNIQUE_PROFILE
1498
        unique->uniqueLinks++;
Alan Mishchenko committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
#endif
    }

    unique->keys++;
    unique->constants.keys++;

    looking = cuddAllocNode(unique);
    if (looking == NULL) return(NULL);
    looking->index = CUDD_CONST_INDEX;
    looking->type.value = value;
    looking->next = nodelist[pos];
    nodelist[pos] = looking;

    return(looking);

} /* end of cuddUniqueConst */


/**Function********************************************************************

  Synopsis    [Rehashes a unique subtable.]

  Description [Doubles the size of a unique subtable and rehashes its
  contents.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
void
cuddRehash(
  DdManager * unique,
  int i)
{
    unsigned int slots, oldslots;
    int shift, oldshift;
    int j, pos;
    DdNodePtr *nodelist, *oldnodelist;
    DdNode *node, *next;
    DdNode *sentinel = &(unique->sentinel);
    hack split;
1541 1542
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
1543 1544

    if (unique->gcFrac == DD_GC_FRAC_HI && unique->slots > unique->looseUpTo) {
1545 1546
        unique->gcFrac = DD_GC_FRAC_LO;
        unique->minDead = (unsigned) (DD_GC_FRAC_LO * (double) unique->slots);
Alan Mishchenko committed
1547
#ifdef DD_VERBOSE
1548 1549
        (void) fprintf(unique->err,"GC fraction = %.2f\t", DD_GC_FRAC_LO);
        (void) fprintf(unique->err,"minDead = %d\n", unique->minDead);
Alan Mishchenko committed
1550 1551 1552 1553
#endif
    }

    if (unique->gcFrac != DD_GC_FRAC_MIN && unique->memused > unique->maxmem) {
1554 1555
        unique->gcFrac = DD_GC_FRAC_MIN;
        unique->minDead = (unsigned) (DD_GC_FRAC_MIN * (double) unique->slots);
Alan Mishchenko committed
1556
#ifdef DD_VERBOSE
1557 1558
        (void) fprintf(unique->err,"GC fraction = %.2f\t", DD_GC_FRAC_MIN);
        (void) fprintf(unique->err,"minDead = %d\n", unique->minDead);
Alan Mishchenko committed
1559
#endif
1560 1561
        cuddShrinkDeathRow(unique);
        if (cuddGarbageCollect(unique,1) > 0) return;
Alan Mishchenko committed
1562 1563 1564
    }

    if (i != CUDD_CONST_INDEX) {
1565 1566 1567
        oldslots = unique->subtables[i].slots;
        oldshift = unique->subtables[i].shift;
        oldnodelist = unique->subtables[i].nodelist;
Alan Mishchenko committed
1568

1569 1570 1571
        /* Compute the new size of the subtable. */
        slots = oldslots << 1;
        shift = oldshift - 1;
Alan Mishchenko committed
1572

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
        saveHandler = MMoutOfMemory;
        MMoutOfMemory = Cudd_OutOfMem;
        nodelist = ABC_ALLOC(DdNodePtr, slots);
        MMoutOfMemory = saveHandler;
        if (nodelist == NULL) {
            (void) fprintf(unique->err,
                           "Unable to resize subtable %d for lack of memory\n",
                           i);
            /* Prevent frequent resizing attempts. */
            (void) cuddGarbageCollect(unique,1);
            if (unique->stash != NULL) {
                ABC_FREE(unique->stash);
                unique->stash = NULL;
                /* Inhibit resizing of tables. */
                cuddSlowTableGrowth(unique);
            }
            return;
Alan Mishchenko committed
1590
        }
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
        unique->subtables[i].nodelist = nodelist;
        unique->subtables[i].slots = slots;
        unique->subtables[i].shift = shift;
        unique->subtables[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;

        /* Move the nodes from the old table to the new table.
        ** This code depends on the type of hash function.
        ** It assumes that the effect of doubling the size of the table
        ** is to retain one more bit of the 32-bit hash value.
        ** The additional bit is the LSB. */
        for (j = 0; (unsigned) j < oldslots; j++) {
            DdNodePtr *evenP, *oddP;
            node = oldnodelist[j];
            evenP = &(nodelist[j<<1]);
            oddP = &(nodelist[(j<<1)+1]);
            while (node != sentinel) {
                next = node->next;
1608
                pos = ddHash(cuddF2L(cuddT(node)), cuddF2L(cuddE(node)), shift);
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
                if (pos & 1) {
                    *oddP = node;
                    oddP = &(node->next);
                } else {
                    *evenP = node;
                    evenP = &(node->next);
                }
                node = next;
            }
            *evenP = *oddP = sentinel;
Alan Mishchenko committed
1619
        }
1620
        ABC_FREE(oldnodelist);
Alan Mishchenko committed
1621 1622

#ifdef DD_VERBOSE
1623 1624 1625 1626
        (void) fprintf(unique->err,
                       "rehashing layer %d: keys %d dead %d new size %d\n",
                       i, unique->subtables[i].keys,
                       unique->subtables[i].dead, slots);
Alan Mishchenko committed
1627 1628
#endif
    } else {
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
        oldslots = unique->constants.slots;
        oldshift = unique->constants.shift;
        oldnodelist = unique->constants.nodelist;

        /* The constant subtable is never subjected to reordering.
        ** Therefore, when it is resized, it is because it has just
        ** reached the maximum load. We can safely just double the size,
        ** with no need for the loop we use for the other tables.
        */
        slots = oldslots << 1;
        shift = oldshift - 1;
        saveHandler = MMoutOfMemory;
        MMoutOfMemory = Cudd_OutOfMem;
        nodelist = ABC_ALLOC(DdNodePtr, slots);
        MMoutOfMemory = saveHandler;
        if (nodelist == NULL) {
            (void) fprintf(unique->err,
                           "Unable to resize constant subtable for lack of memory\n");
            (void) cuddGarbageCollect(unique,1);
            for (j = 0; j < unique->size; j++) {
                unique->subtables[j].maxKeys <<= 1;
            }
            unique->constants.maxKeys <<= 1;
            return;
Alan Mishchenko committed
1653
        }
1654 1655 1656 1657 1658 1659
        unique->constants.slots = slots;
        unique->constants.shift = shift;
        unique->constants.maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
        unique->constants.nodelist = nodelist;
        for (j = 0; (unsigned) j < slots; j++) {
            nodelist[j] = NULL;
Alan Mishchenko committed
1660
        }
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        for (j = 0; (unsigned) j < oldslots; j++) {
            node = oldnodelist[j];
            while (node != NULL) {
                next = node->next;
                split.value = cuddV(node);
                pos = ddHash(split.bits[0], split.bits[1], shift);
                node->next = nodelist[pos];
                nodelist[pos] = node;
                node = next;
            }
        }
        ABC_FREE(oldnodelist);
Alan Mishchenko committed
1673 1674

#ifdef DD_VERBOSE
1675 1676 1677
        (void) fprintf(unique->err,
                       "rehashing constants: keys %d dead %d new size %d\n",
                       unique->constants.keys,unique->constants.dead,slots);
Alan Mishchenko committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
#endif
    }

    /* Update global data */

    unique->memused += (slots - oldslots) * sizeof(DdNodePtr);
    unique->slots += (slots - oldslots);
    ddFixLimits(unique);

} /* end of cuddRehash */


/**Function********************************************************************

  Synopsis    [Shrinks a subtable.]

  Description [Shrinks a subtable.]

  SideEffects [None]

  SeeAlso     [cuddRehash]

******************************************************************************/
void
cuddShrinkSubtable(
  DdManager *unique,
  int i)
{
    int j;
    int shift, posn;
    DdNodePtr *nodelist, *oldnodelist;
    DdNode *node, *next;
    DdNode *sentinel = &(unique->sentinel);
    unsigned int slots, oldslots;
1712 1713
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
1714 1715 1716 1717 1718 1719

    oldnodelist = unique->subtables[i].nodelist;
    oldslots = unique->subtables[i].slots;
    slots = oldslots >> 1;
    saveHandler = MMoutOfMemory;
    MMoutOfMemory = Cudd_OutOfMem;
Alan Mishchenko committed
1720
    nodelist = ABC_ALLOC(DdNodePtr, slots);
Alan Mishchenko committed
1721 1722
    MMoutOfMemory = saveHandler;
    if (nodelist == NULL) {
1723
        return;
Alan Mishchenko committed
1724 1725 1726 1727 1728 1729 1730
    }
    unique->subtables[i].nodelist = nodelist;
    unique->subtables[i].slots = slots;
    unique->subtables[i].shift++;
    unique->subtables[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
#ifdef DD_VERBOSE
    (void) fprintf(unique->err,
1731 1732
                   "shrunk layer %d (%d keys) from %d to %d slots\n",
                   i, unique->subtables[i].keys, oldslots, slots);
Alan Mishchenko committed
1733 1734 1735
#endif

    for (j = 0; (unsigned) j < slots; j++) {
1736
        nodelist[j] = sentinel;
Alan Mishchenko committed
1737 1738 1739
    }
    shift = unique->subtables[i].shift;
    for (j = 0; (unsigned) j < oldslots; j++) {
1740 1741 1742 1743 1744
        node = oldnodelist[j];
        while (node != sentinel) {
            DdNode *looking, *T, *E;
            DdNodePtr *previousP;
            next = node->next;
1745
            posn = ddHash(cuddF2L(cuddT(node)), cuddF2L(cuddE(node)), shift);
1746 1747 1748 1749 1750 1751 1752
            previousP = &(nodelist[posn]);
            looking = *previousP;
            T = cuddT(node);
            E = cuddE(node);
            while (T < cuddT(looking)) {
                previousP = &(looking->next);
                looking = *previousP;
Alan Mishchenko committed
1753
#ifdef DD_UNIQUE_PROFILE
1754 1755 1756 1757 1758 1759
                unique->uniqueLinks++;
#endif
            }
            while (T == cuddT(looking) && E < cuddE(looking)) {
                previousP = &(looking->next);
                looking = *previousP;
Alan Mishchenko committed
1760
#ifdef DD_UNIQUE_PROFILE
1761
                unique->uniqueLinks++;
Alan Mishchenko committed
1762
#endif
1763 1764 1765 1766
            }
            node->next = *previousP;
            *previousP = node;
            node = next;
Alan Mishchenko committed
1767 1768
        }
    }
Alan Mishchenko committed
1769
    ABC_FREE(oldnodelist);
Alan Mishchenko committed
1770 1771 1772 1773 1774

    unique->memused += ((long) slots - (long) oldslots) * sizeof(DdNode *);
    unique->slots += slots - oldslots;
    unique->minDead = (unsigned) (unique->gcFrac * (double) unique->slots);
    unique->cacheSlack = (int)
1775 1776
        ddMin(unique->maxCacheHard,DD_MAX_CACHE_TO_SLOTS_RATIO * unique->slots)
        - 2 * (int) unique->cacheSlots;
Alan Mishchenko committed
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806

} /* end of cuddShrinkSubtable */


/**Function********************************************************************

  Synopsis [Inserts n new subtables in a unique table at level.]

  Description [Inserts n new subtables in a unique table at level.
  The number n should be positive, and level should be an existing level.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [cuddDestroySubtables]

******************************************************************************/
int
cuddInsertSubtables(
  DdManager * unique,
  int  n,
  int  level)
{
    DdSubtable *newsubtables;
    DdNodePtr *newnodelist;
    DdNodePtr *newvars;
    DdNode *sentinel = &(unique->sentinel);
    int oldsize,newsize;
    int i,j,index,reorderSave;
    unsigned int numSlots = unique->initSlots;
1807
    int *newperm, *newinvperm, *newmap=NULL;
Alan Mishchenko committed
1808 1809 1810 1811 1812 1813 1814 1815 1816
    DdNode *one, *zero;

#ifdef DD_DEBUG
    assert(n > 0 && level < unique->size);
#endif

    oldsize = unique->size;
    /* Easy case: there is still room in the current table. */
    if (oldsize + n <= unique->maxSize) {
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
        /* Shift the tables at and below level. */
        for (i = oldsize - 1; i >= level; i--) {
            unique->subtables[i+n].slots    = unique->subtables[i].slots;
            unique->subtables[i+n].shift    = unique->subtables[i].shift;
            unique->subtables[i+n].keys     = unique->subtables[i].keys;
            unique->subtables[i+n].maxKeys  = unique->subtables[i].maxKeys;
            unique->subtables[i+n].dead     = unique->subtables[i].dead;
            unique->subtables[i+n].nodelist = unique->subtables[i].nodelist;
            unique->subtables[i+n].bindVar  = unique->subtables[i].bindVar;
            unique->subtables[i+n].varType  = unique->subtables[i].varType;
            unique->subtables[i+n].pairIndex  = unique->subtables[i].pairIndex;
            unique->subtables[i+n].varHandled = unique->subtables[i].varHandled;
            unique->subtables[i+n].varToBeGrouped =
                unique->subtables[i].varToBeGrouped;

            index                           = unique->invperm[i];
            unique->invperm[i+n]            = index;
            unique->perm[index]            += n;
Alan Mishchenko committed
1835
        }
1836
        /* Create new subtables. */
Alan Mishchenko committed
1837
        for (i = 0; i < n; i++) {
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
            unique->subtables[level+i].slots = numSlots;
            unique->subtables[level+i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            unique->subtables[level+i].keys = 0;
            unique->subtables[level+i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            unique->subtables[level+i].dead = 0;
            unique->subtables[level+i].bindVar = 0;
            unique->subtables[level+i].varType = CUDD_VAR_PRIMARY_INPUT;
            unique->subtables[level+i].pairIndex = 0;
            unique->subtables[level+i].varHandled = 0;
            unique->subtables[level+i].varToBeGrouped = CUDD_LAZY_NONE;

            unique->perm[oldsize+i] = level + i;
            unique->invperm[level+i] = oldsize + i;
            newnodelist = unique->subtables[level+i].nodelist =
                ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; (unsigned) j < numSlots; j++) {
                newnodelist[j] = sentinel;
            }
        }
        if (unique->map != NULL) {
            for (i = 0; i < n; i++) {
                unique->map[oldsize+i] = oldsize + i;
            }
Alan Mishchenko committed
1866 1867
        }
    } else {
1868 1869 1870 1871 1872
        /* The current table is too small: we need to allocate a new,
        ** larger one; move all old subtables, and initialize the new
        ** subtables.
        */
        newsize = oldsize + n + DD_DEFAULT_RESIZE;
Alan Mishchenko committed
1873
#ifdef DD_VERBOSE
1874 1875 1876
        (void) fprintf(unique->err,
                       "Increasing the table size from %d to %d\n",
            unique->maxSize, newsize);
Alan Mishchenko committed
1877
#endif
1878 1879 1880 1881 1882
        /* Allocate memory for new arrays (except nodelists). */
        newsubtables = ABC_ALLOC(DdSubtable,newsize);
        if (newsubtables == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
1883
        }
1884 1885 1886 1887 1888
        newvars = ABC_ALLOC(DdNodePtr,newsize);
        if (newvars == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            ABC_FREE(newsubtables);
            return(0);
Alan Mishchenko committed
1889
        }
1890 1891 1892 1893 1894 1895
        newperm = ABC_ALLOC(int,newsize);
        if (newperm == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            ABC_FREE(newsubtables);
            ABC_FREE(newvars);
            return(0);
Alan Mishchenko committed
1896
        }
1897 1898 1899 1900 1901 1902 1903
        newinvperm = ABC_ALLOC(int,newsize);
        if (newinvperm == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            ABC_FREE(newsubtables);
            ABC_FREE(newvars);
            ABC_FREE(newperm);
            return(0);
Alan Mishchenko committed
1904
        }
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
        if (unique->map != NULL) {
            newmap = ABC_ALLOC(int,newsize);
            if (newmap == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                ABC_FREE(newsubtables);
                ABC_FREE(newvars);
                ABC_FREE(newperm);
                ABC_FREE(newinvperm);
                return(0);
            }
            unique->memused += (newsize - unique->maxSize) * sizeof(int);
        }
        unique->memused += (newsize - unique->maxSize) * ((numSlots+1) *
            sizeof(DdNode *) + 2 * sizeof(int) + sizeof(DdSubtable));
        /* Copy levels before insertion points from old tables. */
        for (i = 0; i < level; i++) {
            newsubtables[i].slots = unique->subtables[i].slots;
            newsubtables[i].shift = unique->subtables[i].shift;
            newsubtables[i].keys = unique->subtables[i].keys;
            newsubtables[i].maxKeys = unique->subtables[i].maxKeys;
            newsubtables[i].dead = unique->subtables[i].dead;
            newsubtables[i].nodelist = unique->subtables[i].nodelist;
            newsubtables[i].bindVar = unique->subtables[i].bindVar;
            newsubtables[i].varType = unique->subtables[i].varType;
            newsubtables[i].pairIndex = unique->subtables[i].pairIndex;
            newsubtables[i].varHandled = unique->subtables[i].varHandled;
            newsubtables[i].varToBeGrouped = unique->subtables[i].varToBeGrouped;

            newvars[i] = unique->vars[i];
            newperm[i] = unique->perm[i];
            newinvperm[i] = unique->invperm[i];
        }
        /* Finish initializing permutation for new table to old one. */
        for (i = level; i < oldsize; i++) {
            newperm[i] = unique->perm[i];
        }
        /* Initialize new levels. */
        for (i = level; i < level + n; i++) {
            newsubtables[i].slots = numSlots;
            newsubtables[i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            newsubtables[i].keys = 0;
            newsubtables[i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            newsubtables[i].dead = 0;
            newsubtables[i].bindVar = 0;
            newsubtables[i].varType = CUDD_VAR_PRIMARY_INPUT;
            newsubtables[i].pairIndex = 0;
            newsubtables[i].varHandled = 0;
            newsubtables[i].varToBeGrouped = CUDD_LAZY_NONE;

            newperm[oldsize + i - level] = i;
            newinvperm[i] = oldsize + i - level;
            newnodelist = newsubtables[i].nodelist = ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                /* We are going to leak some memory.  We should clean up. */
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; (unsigned) j < numSlots; j++) {
                newnodelist[j] = sentinel;
            }
        }
        /* Copy the old tables for levels past the insertion point. */
        for (i = level; i < oldsize; i++) {
            newsubtables[i+n].slots    = unique->subtables[i].slots;
            newsubtables[i+n].shift    = unique->subtables[i].shift;
            newsubtables[i+n].keys     = unique->subtables[i].keys;
            newsubtables[i+n].maxKeys  = unique->subtables[i].maxKeys;
            newsubtables[i+n].dead     = unique->subtables[i].dead;
            newsubtables[i+n].nodelist = unique->subtables[i].nodelist;
            newsubtables[i+n].bindVar  = unique->subtables[i].bindVar;
            newsubtables[i+n].varType  = unique->subtables[i].varType;
            newsubtables[i+n].pairIndex  = unique->subtables[i].pairIndex;
            newsubtables[i+n].varHandled  = unique->subtables[i].varHandled;
            newsubtables[i+n].varToBeGrouped  =
                unique->subtables[i].varToBeGrouped;

            newvars[i]                 = unique->vars[i];
            index                      = unique->invperm[i];
            newinvperm[i+n]            = index;
            newperm[index]            += n;
        }
        /* Update the map. */
        if (unique->map != NULL) {
            for (i = 0; i < oldsize; i++) {
                newmap[i] = unique->map[i];
            }
            for (i = oldsize; i < oldsize + n; i++) {
                newmap[i] = i;
            }
            ABC_FREE(unique->map);
            unique->map = newmap;
        }
        /* Install the new tables and free the old ones. */
        ABC_FREE(unique->subtables);
        unique->subtables = newsubtables;
        unique->maxSize = newsize;
        ABC_FREE(unique->vars);
        unique->vars = newvars;
        ABC_FREE(unique->perm);
        unique->perm = newperm;
        ABC_FREE(unique->invperm);
        unique->invperm = newinvperm;
        /* Update the stack for iterative procedures. */
        if (newsize > unique->maxSizeZ) {
            ABC_FREE(unique->stack);
            unique->stack = ABC_ALLOC(DdNodePtr,newsize + 1);
            if (unique->stack == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            unique->stack[0] = NULL; /* to suppress harmless UMR */
            unique->memused +=
                (newsize - ddMax(unique->maxSize,unique->maxSizeZ))
                * sizeof(DdNode *);
Alan Mishchenko committed
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
        }
    }
    /* Update manager parameters to account for the new subtables. */
    unique->slots += n * numSlots;
    ddFixLimits(unique);
    unique->size += n;

    /* Now that the table is in a coherent state, create the new
    ** projection functions. We need to temporarily disable reordering,
    ** because we cannot reorder without projection functions in place.
    **/
    one = unique->one;
    zero = Cudd_Not(one);

    reorderSave = unique->autoDyn;
    unique->autoDyn = 0;
    for (i = oldsize; i < oldsize + n; i++) {
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
        unique->vars[i] = cuddUniqueInter(unique,i,one,zero);
        if (unique->vars[i] == NULL) {
            unique->autoDyn = reorderSave;
            /* Shift everything back so table remains coherent. */
            for (j = oldsize; j < i; j++) {
                Cudd_IterDerefBdd(unique,unique->vars[j]);
                cuddDeallocNode(unique,unique->vars[j]);
                unique->vars[j] = NULL;
            }
            for (j = level; j < oldsize; j++) {
                unique->subtables[j].slots    = unique->subtables[j+n].slots;
                unique->subtables[j].slots    = unique->subtables[j+n].slots;
                unique->subtables[j].shift    = unique->subtables[j+n].shift;
                unique->subtables[j].keys     = unique->subtables[j+n].keys;
                unique->subtables[j].maxKeys  =
                    unique->subtables[j+n].maxKeys;
                unique->subtables[j].dead     = unique->subtables[j+n].dead;
                ABC_FREE(unique->subtables[j].nodelist);
                unique->subtables[j].nodelist =
                    unique->subtables[j+n].nodelist;
                unique->subtables[j+n].nodelist = NULL;
                unique->subtables[j].bindVar  =
                    unique->subtables[j+n].bindVar;
                unique->subtables[j].varType  =
                    unique->subtables[j+n].varType;
                unique->subtables[j].pairIndex =
                    unique->subtables[j+n].pairIndex;
                unique->subtables[j].varHandled =
                    unique->subtables[j+n].varHandled;
                unique->subtables[j].varToBeGrouped =
                    unique->subtables[j+n].varToBeGrouped;
                index                         = unique->invperm[j+n];
                unique->invperm[j]            = index;
                unique->perm[index]          -= n;
            }
            unique->size = oldsize;
            unique->slots -= n * numSlots;
            ddFixLimits(unique);
            (void) Cudd_DebugCheck(unique);
            return(0);
        }
        cuddRef(unique->vars[i]);
Alan Mishchenko committed
2079 2080
    }
    if (unique->tree != NULL) {
2081 2082 2083
        unique->tree->size += n;
        unique->tree->index = unique->invperm[0];
        ddPatchTree(unique,unique->tree);
Alan Mishchenko committed
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
    }
    unique->autoDyn = reorderSave;

    return(1);

} /* end of cuddInsertSubtables */


/**Function********************************************************************

  Synopsis [Destroys the n most recently created subtables in a unique table.]

  Description [Destroys the n most recently created subtables in a unique
  table.  n should be positive. The subtables should not contain any live
  nodes, except the (isolated) projection function. The projection
  functions are freed.  Returns 1 if successful; 0 otherwise.]

  SideEffects [The variable map used for fast variable substitution is
  destroyed if it exists. In this case the cache is also cleared.]

  SeeAlso     [cuddInsertSubtables Cudd_SetVarMap]

******************************************************************************/
int
cuddDestroySubtables(
  DdManager * unique,
  int  n)
{
    DdSubtable *subtables;
    DdNodePtr *nodelist;
    DdNodePtr *vars;
    int firstIndex, lastIndex;
    int index, level, newlevel;
    int lowestLevel;
    int shift;
    int found;

    /* Sanity check and set up. */
    if (n <= 0) return(0);
    if (n > unique->size) n = unique->size;

    subtables = unique->subtables;
    vars = unique->vars;
    firstIndex = unique->size - n;
    lastIndex  = unique->size;

    /* Check for nodes labeled by the variables being destroyed
    ** that may still be in use.  It is allowed to destroy a variable
    ** only if there are no such nodes. Also, find the lowest level
    ** among the variables being destroyed. This will make further
    ** processing more efficient.
    */
    lowestLevel = unique->size;
    for (index = firstIndex; index < lastIndex; index++) {
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
        level = unique->perm[index];
        if (level < lowestLevel) lowestLevel = level;
        nodelist = subtables[level].nodelist;
        if (subtables[level].keys - subtables[level].dead != 1) return(0);
        /* The projection function should be isolated. If the ref count
        ** is 1, everything is OK. If the ref count is saturated, then
        ** we need to make sure that there are no nodes pointing to it.
        ** As for the external references, we assume the application is
        ** responsible for them.
        */
        if (vars[index]->ref != 1) {
            if (vars[index]->ref != DD_MAXREF) return(0);
            found = cuddFindParent(unique,vars[index]);
            if (found) {
                return(0);
            } else {
                vars[index]->ref = 1;
            }
Alan Mishchenko committed
2156
        }
2157
        Cudd_RecursiveDeref(unique,vars[index]);
Alan Mishchenko committed
2158 2159 2160 2161 2162 2163 2164 2165 2166
    }

    /* Collect garbage, because we cannot afford having dead nodes pointing
    ** to the dead nodes in the subtables being destroyed.
    */
    (void) cuddGarbageCollect(unique,1);

    /* Here we know we can destroy our subtables. */
    for (index = firstIndex; index < lastIndex; index++) {
2167 2168
        level = unique->perm[index];
        nodelist = subtables[level].nodelist;
Alan Mishchenko committed
2169
#ifdef DD_DEBUG
2170
        assert(subtables[level].keys == 0);
Alan Mishchenko committed
2171
#endif
2172 2173 2174 2175
        ABC_FREE(nodelist);
        unique->memused -= sizeof(DdNodePtr) * subtables[level].slots;
        unique->slots -= subtables[level].slots;
        unique->dead -= subtables[level].dead;
Alan Mishchenko committed
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
    }

    /* Here all subtables to be destroyed have their keys field == 0 and
    ** their hash tables have been freed.
    ** We now scan the subtables from level lowestLevel + 1 to level size - 1,
    ** shifting the subtables as required. We keep a running count of
    ** how many subtables have been moved, so that we know by how many
    ** positions each subtable should be shifted.
    */
    shift = 1;
    for (level = lowestLevel + 1; level < unique->size; level++) {
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
        if (subtables[level].keys == 0) {
            shift++;
            continue;
        }
        newlevel = level - shift;
        subtables[newlevel].slots = subtables[level].slots;
        subtables[newlevel].shift = subtables[level].shift;
        subtables[newlevel].keys = subtables[level].keys;
        subtables[newlevel].maxKeys = subtables[level].maxKeys;
        subtables[newlevel].dead = subtables[level].dead;
        subtables[newlevel].nodelist = subtables[level].nodelist;
        index = unique->invperm[level];
        unique->perm[index] = newlevel;
        unique->invperm[newlevel]  = index;
        subtables[newlevel].bindVar = subtables[level].bindVar;
        subtables[newlevel].varType = subtables[level].varType;
        subtables[newlevel].pairIndex = subtables[level].pairIndex;
        subtables[newlevel].varHandled = subtables[level].varHandled;
        subtables[newlevel].varToBeGrouped = subtables[level].varToBeGrouped;
Alan Mishchenko committed
2206 2207 2208 2209 2210
    }
    /* Destroy the map. If a surviving variable is
    ** mapped to a dying variable, and the map were used again,
    ** an out-of-bounds access to unique->vars would result. */
    if (unique->map != NULL) {
2211 2212 2213
        cuddCacheFlush(unique);
        ABC_FREE(unique->map);
        unique->map = NULL;
Alan Mishchenko committed
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
    }

    unique->minDead = (unsigned) (unique->gcFrac * (double) unique->slots);
    unique->size -= n;

    return(1);

} /* end of cuddDestroySubtables */


/**Function********************************************************************

  Synopsis [Increases the number of ZDD subtables in a unique table so
  that it meets or exceeds index.]

  Description [Increases the number of ZDD subtables in a unique table so
  that it meets or exceeds index.  When new ZDD variables are created, it
  is possible to preserve the functions unchanged, or it is possible to
  preserve the covers unchanged, but not both. cuddResizeTableZdd preserves
  the covers.  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [ddResizeTable]

******************************************************************************/
int
cuddResizeTableZdd(
  DdManager * unique,
  int  index)
{
    DdSubtable *newsubtables;
    DdNodePtr *newnodelist;
    int oldsize,newsize;
    int i,j,reorderSave;
    unsigned int numSlots = unique->initSlots;
    int *newperm, *newinvperm;

    oldsize = unique->sizeZ;
    /* Easy case: there is still room in the current table. */
    if (index < unique->maxSizeZ) {
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
        for (i = oldsize; i <= index; i++) {
            unique->subtableZ[i].slots = numSlots;
            unique->subtableZ[i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            unique->subtableZ[i].keys = 0;
            unique->subtableZ[i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            unique->subtableZ[i].dead = 0;
            unique->permZ[i] = i;
            unique->invpermZ[i] = i;
            newnodelist = unique->subtableZ[i].nodelist =
                ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; (unsigned) j < numSlots; j++) {
                newnodelist[j] = NULL;
            }
Alan Mishchenko committed
2273 2274
        }
    } else {
2275 2276 2277 2278 2279
        /* The current table is too small: we need to allocate a new,
        ** larger one; move all old subtables, and initialize the new
        ** subtables up to index included.
        */
        newsize = index + DD_DEFAULT_RESIZE;
Alan Mishchenko committed
2280
#ifdef DD_VERBOSE
2281 2282 2283
        (void) fprintf(unique->err,
                       "Increasing the ZDD table size from %d to %d\n",
            unique->maxSizeZ, newsize);
Alan Mishchenko committed
2284
#endif
2285 2286 2287 2288
        newsubtables = ABC_ALLOC(DdSubtable,newsize);
        if (newsubtables == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2289
        }
2290 2291 2292 2293
        newperm = ABC_ALLOC(int,newsize);
        if (newperm == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2294
        }
2295 2296 2297 2298
        newinvperm = ABC_ALLOC(int,newsize);
        if (newinvperm == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2299
        }
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
        unique->memused += (newsize - unique->maxSizeZ) * ((numSlots+1) *
            sizeof(DdNode *) + 2 * sizeof(int) + sizeof(DdSubtable));
        if (newsize > unique->maxSize) {
            ABC_FREE(unique->stack);
            unique->stack = ABC_ALLOC(DdNodePtr,newsize + 1);
            if (unique->stack == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            unique->stack[0] = NULL; /* to suppress harmless UMR */
            unique->memused +=
                (newsize - ddMax(unique->maxSize,unique->maxSizeZ))
                * sizeof(DdNode *);
        }
        for (i = 0; i < oldsize; i++) {
            newsubtables[i].slots = unique->subtableZ[i].slots;
            newsubtables[i].shift = unique->subtableZ[i].shift;
            newsubtables[i].keys = unique->subtableZ[i].keys;
            newsubtables[i].maxKeys = unique->subtableZ[i].maxKeys;
            newsubtables[i].dead = unique->subtableZ[i].dead;
            newsubtables[i].nodelist = unique->subtableZ[i].nodelist;
            newperm[i] = unique->permZ[i];
            newinvperm[i] = unique->invpermZ[i];
        }
        for (i = oldsize; i <= index; i++) {
            newsubtables[i].slots = numSlots;
            newsubtables[i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            newsubtables[i].keys = 0;
            newsubtables[i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            newsubtables[i].dead = 0;
            newperm[i] = i;
            newinvperm[i] = i;
            newnodelist = newsubtables[i].nodelist = ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; (unsigned) j < numSlots; j++) {
                newnodelist[j] = NULL;
            }
        }
        ABC_FREE(unique->subtableZ);
        unique->subtableZ = newsubtables;
        unique->maxSizeZ = newsize;
        ABC_FREE(unique->permZ);
        unique->permZ = newperm;
        ABC_FREE(unique->invpermZ);
        unique->invpermZ = newinvperm;
Alan Mishchenko committed
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
    }
    unique->slots += (index + 1 - unique->sizeZ) * numSlots;
    ddFixLimits(unique);
    unique->sizeZ = index + 1;

    /* Now that the table is in a coherent state, update the ZDD
    ** universe. We need to temporarily disable reordering,
    ** because we cannot reorder without universe in place.
    */

    reorderSave = unique->autoDynZ;
    unique->autoDynZ = 0;
    cuddZddFreeUniv(unique);
    if (!cuddZddInitUniv(unique)) {
2363 2364
        unique->autoDynZ = reorderSave;
        return(0);
Alan Mishchenko committed
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
    }
    unique->autoDynZ = reorderSave;

    return(1);

} /* end of cuddResizeTableZdd */


/**Function********************************************************************

  Synopsis    [Adjusts parameters of a table to slow down its growth.]

  Description []

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
void
cuddSlowTableGrowth(
  DdManager *unique)
{
    int i;

    unique->maxCacheHard = unique->cacheSlots - 1;
2391
    unique->cacheSlack = - (int) (unique->cacheSlots + 1);
Alan Mishchenko committed
2392
    for (i = 0; i < unique->size; i++) {
2393
        unique->subtables[i].maxKeys <<= 2;
Alan Mishchenko committed
2394 2395 2396 2397 2398 2399
    }
    unique->gcFrac = DD_GC_FRAC_MIN;
    unique->minDead = (unsigned) (DD_GC_FRAC_MIN * (double) unique->slots);
    cuddShrinkDeathRow(unique);
    (void) fprintf(unique->err,"Slowing down table growth: ");
    (void) fprintf(unique->err,"GC fraction = %.2f\t", unique->gcFrac);
2400
    (void) fprintf(unique->err,"minDead = %u\n", unique->minDead);
Alan Mishchenko committed
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430

} /* end of cuddSlowTableGrowth */


/*---------------------------------------------------------------------------*/
/* Definition of static functions                                            */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Rehashes a ZDD unique subtable.]

  Description []

  SideEffects [None]

  SeeAlso     [cuddRehash]

******************************************************************************/
static void
ddRehashZdd(
  DdManager * unique,
  int  i)
{
    unsigned int slots, oldslots;
    int shift, oldshift;
    int j, pos;
    DdNodePtr *nodelist, *oldnodelist;
    DdNode *node, *next;
2431 2432
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
2433 2434

    if (unique->slots > unique->looseUpTo) {
2435
        unique->minDead = (unsigned) (DD_GC_FRAC_LO * (double) unique->slots);
Alan Mishchenko committed
2436
#ifdef DD_VERBOSE
2437 2438 2439 2440 2441
        if (unique->gcFrac == DD_GC_FRAC_HI) {
            (void) fprintf(unique->err,"GC fraction = %.2f\t",
                           DD_GC_FRAC_LO);
            (void) fprintf(unique->err,"minDead = %d\n", unique->minDead);
        }
Alan Mishchenko committed
2442
#endif
2443
        unique->gcFrac = DD_GC_FRAC_LO;
Alan Mishchenko committed
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
    }

    assert(i != CUDD_MAXINDEX);
    oldslots = unique->subtableZ[i].slots;
    oldshift = unique->subtableZ[i].shift;
    oldnodelist = unique->subtableZ[i].nodelist;

    /* Compute the new size of the subtable. Normally, we just
    ** double.  However, after reordering, a table may be severely
    ** overloaded. Therefore, we iterate. */
    slots = oldslots;
    shift = oldshift;
    do {
2457 2458
        slots <<= 1;
        shift--;
Alan Mishchenko committed
2459 2460 2461 2462
    } while (slots * DD_MAX_SUBTABLE_DENSITY < unique->subtableZ[i].keys);

    saveHandler = MMoutOfMemory;
    MMoutOfMemory = Cudd_OutOfMem;
Alan Mishchenko committed
2463
    nodelist = ABC_ALLOC(DdNodePtr, slots);
Alan Mishchenko committed
2464 2465
    MMoutOfMemory = saveHandler;
    if (nodelist == NULL) {
2466 2467 2468 2469 2470 2471 2472 2473
        (void) fprintf(unique->err,
                       "Unable to resize ZDD subtable %d for lack of memory.\n",
                       i);
        (void) cuddGarbageCollect(unique,1);
        for (j = 0; j < unique->sizeZ; j++) {
            unique->subtableZ[j].maxKeys <<= 1;
        }
        return;
Alan Mishchenko committed
2474 2475 2476 2477 2478 2479
    }
    unique->subtableZ[i].nodelist = nodelist;
    unique->subtableZ[i].slots = slots;
    unique->subtableZ[i].shift = shift;
    unique->subtableZ[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
    for (j = 0; (unsigned) j < slots; j++) {
2480
        nodelist[j] = NULL;
Alan Mishchenko committed
2481 2482
    }
    for (j = 0; (unsigned) j < oldslots; j++) {
2483 2484 2485
        node = oldnodelist[j];
        while (node != NULL) {
            next = node->next;
2486
            pos = ddHash(cuddF2L(cuddT(node)), cuddF2L(cuddE(node)), shift);
2487 2488 2489 2490
            node->next = nodelist[pos];
            nodelist[pos] = node;
            node = next;
        }
Alan Mishchenko committed
2491
    }
Alan Mishchenko committed
2492
    ABC_FREE(oldnodelist);
Alan Mishchenko committed
2493 2494 2495

#ifdef DD_VERBOSE
    (void) fprintf(unique->err,
2496 2497 2498
                   "rehashing layer %d: keys %d dead %d new size %d\n",
                   i, unique->subtableZ[i].keys,
                   unique->subtableZ[i].dead, slots);
Alan Mishchenko committed
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
#endif

    /* Update global data. */
    unique->memused += (slots - oldslots) * sizeof(DdNode *);
    unique->slots += (slots - oldslots);
    ddFixLimits(unique);

} /* end of ddRehashZdd */


/**Function********************************************************************

  Synopsis [Increases the number of subtables in a unique table so
  that it meets or exceeds index.]

  Description [Increases the number of subtables in a unique table so
  that it meets or exceeds index. Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [cuddResizeTableZdd]

******************************************************************************/
static int
ddResizeTable(
  DdManager * unique,
  int index)
{
    DdSubtable *newsubtables;
    DdNodePtr *newnodelist;
    DdNodePtr *newvars;
    DdNode *sentinel = &(unique->sentinel);
    int oldsize,newsize;
    int i,j,reorderSave;
    int numSlots = unique->initSlots;
Alan Mishchenko committed
2534
    int *newperm, *newinvperm, *newmap = NULL;
Alan Mishchenko committed
2535 2536 2537 2538 2539 2540
    DdNode *one, *zero;

    oldsize = unique->size;
    /* Easy case: there is still room in the current table. */
    if (index < unique->maxSize) {
        for (i = oldsize; i <= index; i++) {
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
            unique->subtables[i].slots = numSlots;
            unique->subtables[i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            unique->subtables[i].keys = 0;
            unique->subtables[i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            unique->subtables[i].dead = 0;
            unique->subtables[i].bindVar = 0;
            unique->subtables[i].varType = CUDD_VAR_PRIMARY_INPUT;
            unique->subtables[i].pairIndex = 0;
            unique->subtables[i].varHandled = 0;
            unique->subtables[i].varToBeGrouped = CUDD_LAZY_NONE;

            unique->perm[i] = i;
            unique->invperm[i] = i;
            newnodelist = unique->subtables[i].nodelist =
                ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                for (j = oldsize; j < i; j++) {
                    ABC_FREE(unique->subtables[j].nodelist);
                }
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; j < numSlots; j++) {
                newnodelist[j] = sentinel;
            }
        }
        if (unique->map != NULL) {
            for (i = oldsize; i <= index; i++) {
                unique->map[i] = i;
            }
Alan Mishchenko committed
2572 2573
        }
    } else {
2574 2575 2576 2577 2578
        /* The current table is too small: we need to allocate a new,
        ** larger one; move all old subtables, and initialize the new
        ** subtables up to index included.
        */
        newsize = index + DD_DEFAULT_RESIZE;
Alan Mishchenko committed
2579
#ifdef DD_VERBOSE
2580 2581 2582
        (void) fprintf(unique->err,
                       "Increasing the table size from %d to %d\n",
                       unique->maxSize, newsize);
Alan Mishchenko committed
2583
#endif
2584 2585 2586 2587
        newsubtables = ABC_ALLOC(DdSubtable,newsize);
        if (newsubtables == NULL) {
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2588
        }
2589 2590 2591 2592 2593
        newvars = ABC_ALLOC(DdNodePtr,newsize);
        if (newvars == NULL) {
            ABC_FREE(newsubtables);
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2594
        }
2595 2596 2597 2598 2599 2600
        newperm = ABC_ALLOC(int,newsize);
        if (newperm == NULL) {
            ABC_FREE(newsubtables);
            ABC_FREE(newvars);
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
Alan Mishchenko committed
2601
        }
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
        newinvperm = ABC_ALLOC(int,newsize);
        if (newinvperm == NULL) {
            ABC_FREE(newsubtables);
            ABC_FREE(newvars);
            ABC_FREE(newperm);
            unique->errorCode = CUDD_MEMORY_OUT;
            return(0);
        }
        if (unique->map != NULL) {
            newmap = ABC_ALLOC(int,newsize);
            if (newmap == NULL) {
                ABC_FREE(newsubtables);
                ABC_FREE(newvars);
                ABC_FREE(newperm);
                ABC_FREE(newinvperm);
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            unique->memused += (newsize - unique->maxSize) * sizeof(int);
Alan Mishchenko committed
2621
        }
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
        unique->memused += (newsize - unique->maxSize) * ((numSlots+1) *
            sizeof(DdNode *) + 2 * sizeof(int) + sizeof(DdSubtable));
        if (newsize > unique->maxSizeZ) {
            ABC_FREE(unique->stack);
            unique->stack = ABC_ALLOC(DdNodePtr,newsize + 1);
            if (unique->stack == NULL) {
                ABC_FREE(newsubtables);
                ABC_FREE(newvars);
                ABC_FREE(newperm);
                ABC_FREE(newinvperm);
                if (unique->map != NULL) {
                    ABC_FREE(newmap);
                }
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            unique->stack[0] = NULL; /* to suppress harmless UMR */
            unique->memused +=
                (newsize - ddMax(unique->maxSize,unique->maxSizeZ))
                * sizeof(DdNode *);
Alan Mishchenko committed
2642 2643
        }
        for (i = 0; i < oldsize; i++) {
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
            newsubtables[i].slots = unique->subtables[i].slots;
            newsubtables[i].shift = unique->subtables[i].shift;
            newsubtables[i].keys = unique->subtables[i].keys;
            newsubtables[i].maxKeys = unique->subtables[i].maxKeys;
            newsubtables[i].dead = unique->subtables[i].dead;
            newsubtables[i].nodelist = unique->subtables[i].nodelist;
            newsubtables[i].bindVar = unique->subtables[i].bindVar;
            newsubtables[i].varType = unique->subtables[i].varType;
            newsubtables[i].pairIndex = unique->subtables[i].pairIndex;
            newsubtables[i].varHandled = unique->subtables[i].varHandled;
            newsubtables[i].varToBeGrouped = unique->subtables[i].varToBeGrouped;

            newvars[i] = unique->vars[i];
            newperm[i] = unique->perm[i];
            newinvperm[i] = unique->invperm[i];
Alan Mishchenko committed
2659 2660
        }
        for (i = oldsize; i <= index; i++) {
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
            newsubtables[i].slots = numSlots;
            newsubtables[i].shift = sizeof(int) * 8 -
                cuddComputeFloorLog2(numSlots);
            newsubtables[i].keys = 0;
            newsubtables[i].maxKeys = numSlots * DD_MAX_SUBTABLE_DENSITY;
            newsubtables[i].dead = 0;
            newsubtables[i].bindVar = 0;
            newsubtables[i].varType = CUDD_VAR_PRIMARY_INPUT;
            newsubtables[i].pairIndex = 0;
            newsubtables[i].varHandled = 0;
            newsubtables[i].varToBeGrouped = CUDD_LAZY_NONE;

            newperm[i] = i;
            newinvperm[i] = i;
            newnodelist = newsubtables[i].nodelist = ABC_ALLOC(DdNodePtr, numSlots);
            if (newnodelist == NULL) {
                unique->errorCode = CUDD_MEMORY_OUT;
                return(0);
            }
            for (j = 0; j < numSlots; j++) {
                newnodelist[j] = sentinel;
            }
Alan Mishchenko committed
2683
        }
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
        if (unique->map != NULL) {
            for (i = 0; i < oldsize; i++) {
                newmap[i] = unique->map[i];
            }
            for (i = oldsize; i <= index; i++) {
                newmap[i] = i;
            }
            ABC_FREE(unique->map);
            unique->map = newmap;
        }
        ABC_FREE(unique->subtables);
        unique->subtables = newsubtables;
        unique->maxSize = newsize;
        ABC_FREE(unique->vars);
        unique->vars = newvars;
        ABC_FREE(unique->perm);
        unique->perm = newperm;
        ABC_FREE(unique->invperm);
        unique->invperm = newinvperm;
Alan Mishchenko committed
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
    }

    /* Now that the table is in a coherent state, create the new
    ** projection functions. We need to temporarily disable reordering,
    ** because we cannot reorder without projection functions in place.
    **/
    one = unique->one;
    zero = Cudd_Not(one);

    unique->size = index + 1;
    unique->slots += (index + 1 - oldsize) * numSlots;
    ddFixLimits(unique);

    reorderSave = unique->autoDyn;
    unique->autoDyn = 0;
    for (i = oldsize; i <= index; i++) {
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
        unique->vars[i] = cuddUniqueInter(unique,i,one,zero);
        if (unique->vars[i] == NULL) {
            unique->autoDyn = reorderSave;
            for (j = oldsize; j < i; j++) {
                Cudd_IterDerefBdd(unique,unique->vars[j]);
                cuddDeallocNode(unique,unique->vars[j]);
                unique->vars[j] = NULL;
            }
            for (j = oldsize; j <= index; j++) {
                ABC_FREE(unique->subtables[j].nodelist);
                unique->subtables[j].nodelist = NULL;
            }
            unique->size = oldsize;
            unique->slots -= (index + 1 - oldsize) * numSlots;
            ddFixLimits(unique);
            return(0);
        }
        cuddRef(unique->vars[i]);
Alan Mishchenko committed
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    }
    unique->autoDyn = reorderSave;

    return(1);

} /* end of ddResizeTable */


/**Function********************************************************************

  Synopsis    [Searches the subtables above node for a parent.]

  Description [Searches the subtables above node for a parent. Returns 1
  as soon as one parent is found. Returns 0 is the search is fruitless.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddFindParent(
  DdManager * table,
  DdNode * node)
{
    int         i,j;
2763 2764 2765
    int         slots;
    DdNodePtr   *nodelist;
    DdNode      *f;
Alan Mishchenko committed
2766 2767

    for (i = cuddI(table,node->index) - 1; i >= 0; i--) {
2768 2769
        nodelist = table->subtables[i].nodelist;
        slots = table->subtables[i].slots;
Alan Mishchenko committed
2770

2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
        for (j = 0; j < slots; j++) {
            f = nodelist[j];
            while (cuddT(f) > node) {
                f = f->next;
            }
            while (cuddT(f) == node && Cudd_Regular(cuddE(f)) > node) {
                f = f->next;
            }
            if (cuddT(f) == node && Cudd_Regular(cuddE(f)) == node) {
                return(1);
            }
Alan Mishchenko committed
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
        }
    }

    return(0);

} /* end of cuddFindParent */


/**Function********************************************************************

  Synopsis    [Adjusts the values of table limits.]

  Description [Adjusts the values of table fields controlling the.
  sizes of subtables and computed table. If the computed table is too small
  according to the new values, it is resized.]

  SideEffects [Modifies manager fields. May resize computed table.]

  SeeAlso     []

******************************************************************************/
DD_INLINE
static void
ddFixLimits(
  DdManager *unique)
{
    unique->minDead = (unsigned) (unique->gcFrac * (double) unique->slots);
    unique->cacheSlack = (int) ddMin(unique->maxCacheHard,
2810 2811
        DD_MAX_CACHE_TO_SLOTS_RATIO * unique->slots) -
        2 * (int) unique->cacheSlots;
Alan Mishchenko committed
2812
    if (unique->cacheSlots < unique->slots/2 && unique->cacheSlack >= 0)
2813
        cuddCacheResize(unique);
Alan Mishchenko committed
2814 2815 2816 2817 2818 2819
    return;

} /* end of ddFixLimits */


#ifndef DD_UNSORTED_FREE_LIST
2820
#ifdef DD_RED_BLACK_FREE_LIST
Alan Mishchenko committed
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
/**Function********************************************************************

  Synopsis    [Inserts a DdNode in a red/black search tree.]

  Description [Inserts a DdNode in a red/black search tree. Nodes from
  the same "page" (defined by DD_PAGE_MASK) are linked in a LIFO list.]

  SideEffects [None]

  SeeAlso     [cuddOrderedThread]

******************************************************************************/
static void
cuddOrderedInsert(
  DdNodePtr * root,
  DdNodePtr node)
{
    DdNode *scan;
    DdNodePtr *scanP;
    DdNodePtr *stack[DD_STACK_SIZE];
    int stackN = 0;

    scanP = root;
    while ((scan = *scanP) != NULL) {
2845 2846 2847 2848 2849 2850 2851
        stack[stackN++] = scanP;
        if (DD_INSERT_COMPARE(node, scan) == 0) { /* add to page list */
            DD_NEXT(node) = DD_NEXT(scan);
            DD_NEXT(scan) = node;
            return;
        }
        scanP = (node < scan) ? &DD_LEFT(scan) : &DD_RIGHT(scan);
Alan Mishchenko committed
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
    }
    DD_RIGHT(node) = DD_LEFT(node) = DD_NEXT(node) = NULL;
    DD_COLOR(node) = DD_RED;
    *scanP = node;
    stack[stackN] = &node;
    cuddDoRebalance(stack,stackN);

} /* end of cuddOrderedInsert */


/**Function********************************************************************

  Synopsis    [Threads all the nodes of a search tree into a linear list.]

  Description [Threads all the nodes of a search tree into a linear
  list. For each node of the search tree, the "left" child, if non-null, has
  a lower address than its parent, and the "right" child, if non-null, has a
  higher address than its parent.
  The list is sorted in order of increasing addresses. The search
  tree is destroyed as a result of this operation. The last element of
  the linear list is made to point to the address passed in list. Each
  node if the search tree is a linearly-linked list of nodes from the
  same memory page (as defined in DD_PAGE_MASK). When a node is added to
  the linear list, all the elements of the linked list are added.]

  SideEffects [The search tree is destroyed as a result of this operation.]

  SeeAlso     [cuddOrderedInsert]

******************************************************************************/
static DdNode *
cuddOrderedThread(
  DdNode * root,
  DdNode * list)
{
    DdNode *current, *next, *prev, *end;

    current = root;
    /* The first word in the node is used to implement a stack that holds
    ** the nodes from the root of the tree to the current node. Here we
    ** put the root of the tree at the bottom of the stack.
    */
    *((DdNodePtr *) current) = NULL;

    while (current != NULL) {
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
        if (DD_RIGHT(current) != NULL) {
            /* If possible, we follow the "right" link. Eventually we'll
            ** find the node with the largest address in the current tree.
            ** In this phase we use the first word of a node to implemen
            ** a stack of the nodes on the path from the root to "current".
            ** Also, we disconnect the "right" pointers to indicate that
            ** we have already followed them.
            */
            next = DD_RIGHT(current);
            DD_RIGHT(current) = NULL;
            *((DdNodePtr *)next) = current;
            current = next;
Alan Mishchenko committed
2909
        } else {
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
            /* We can't proceed along the "right" links any further.
            ** Hence "current" is the largest element in the current tree.
            ** We make this node the new head of "list". (Repeating this
            ** operation until the tree is empty yields the desired linear
            ** threading of all nodes.)
            */
            prev = *((DdNodePtr *) current); /* save prev node on stack in prev */
            /* Traverse the linked list of current until the end. */
            for (end = current; DD_NEXT(end) != NULL; end = DD_NEXT(end));
            DD_NEXT(end) = list; /* attach "list" at end and make */
            list = current;   /* "current" the new head of "list" */
            /* Now, if current has a "left" child, we push it on the stack.
            ** Otherwise, we just continue with the parent of "current".
            */
            if (DD_LEFT(current) != NULL) {
                next = DD_LEFT(current);
                *((DdNodePtr *) next) = prev;
                current = next;
            } else {
                current = prev;
            }
Alan Mishchenko committed
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
        }
    }

    return(list);

} /* end of cuddOrderedThread */


/**Function********************************************************************

  Synopsis    [Performs the left rotation for red/black trees.]

  Description []

  SideEffects [None]

  SeeAlso     [cuddRotateRight]

******************************************************************************/
DD_INLINE
static void
cuddRotateLeft(
  DdNodePtr * nodeP)
{
    DdNode *newRoot;
    DdNode *oldRoot = *nodeP;

    *nodeP = newRoot = DD_RIGHT(oldRoot);
    DD_RIGHT(oldRoot) = DD_LEFT(newRoot);
    DD_LEFT(newRoot) = oldRoot;

} /* end of cuddRotateLeft */


/**Function********************************************************************

  Synopsis    [Performs the right rotation for red/black trees.]

  Description []

  SideEffects [None]

  SeeAlso     [cuddRotateLeft]

******************************************************************************/
DD_INLINE
static void
cuddRotateRight(
  DdNodePtr * nodeP)
{
    DdNode *newRoot;
    DdNode *oldRoot = *nodeP;

    *nodeP = newRoot = DD_LEFT(oldRoot);
    DD_LEFT(oldRoot) = DD_RIGHT(newRoot);
    DD_RIGHT(newRoot) = oldRoot;

} /* end of cuddRotateRight */


/**Function********************************************************************

  Synopsis    [Rebalances a red/black tree.]

  Description []

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static void
cuddDoRebalance(
  DdNodePtr ** stack,
  int  stackN)
{
    DdNodePtr *xP, *parentP, *grandpaP;
    DdNode *x, *y, *parent, *grandpa;

    xP = stack[stackN];
    x = *xP;
    /* Work our way back up, re-balancing the tree. */
    while (--stackN >= 0) {
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
        parentP = stack[stackN];
        parent = *parentP;
        if (DD_IS_BLACK(parent)) break;
        /* Since the root is black, here a non-null grandparent exists. */
        grandpaP = stack[stackN-1];
        grandpa = *grandpaP;
        if (parent == DD_LEFT(grandpa)) {
            y = DD_RIGHT(grandpa);
            if (y != NULL && DD_IS_RED(y)) {
                DD_COLOR(parent) = DD_BLACK;
                DD_COLOR(y) = DD_BLACK;
                DD_COLOR(grandpa) = DD_RED;
                x = grandpa;
                stackN--;
            } else {
                if (x == DD_RIGHT(parent)) {
                    cuddRotateLeft(parentP);
                    DD_COLOR(x) = DD_BLACK;
                } else {
                    DD_COLOR(parent) = DD_BLACK;
                }
                DD_COLOR(grandpa) = DD_RED;
                cuddRotateRight(grandpaP);
                break;
            }
Alan Mishchenko committed
3039
        } else {
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
            y = DD_LEFT(grandpa);
            if (y != NULL && DD_IS_RED(y)) {
                DD_COLOR(parent) = DD_BLACK;
                DD_COLOR(y) = DD_BLACK;
                DD_COLOR(grandpa) = DD_RED;
                x = grandpa;
                stackN--;
            } else {
                if (x == DD_LEFT(parent)) {
                    cuddRotateRight(parentP);
                    DD_COLOR(x) = DD_BLACK;
                } else {
                    DD_COLOR(parent) = DD_BLACK;
                }
                DD_COLOR(grandpa) = DD_RED;
                cuddRotateLeft(grandpaP);
            }
Alan Mishchenko committed
3057 3058 3059 3060 3061 3062
        }
    }
    DD_COLOR(*(stack[0])) = DD_BLACK;

} /* end of cuddDoRebalance */
#endif
3063
#endif
Alan Mishchenko committed
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086


/**Function********************************************************************

  Synopsis    [Fixes a variable tree after the insertion of new subtables.]

  Description [Fixes a variable tree after the insertion of new subtables.
  After such an insertion, the low fields of the tree below the insertion
  point are inconsistent.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static void
ddPatchTree(
  DdManager *dd,
  MtrNode *treenode)
{
    MtrNode *auxnode = treenode;

    while (auxnode != NULL) {
3087 3088 3089 3090 3091
        auxnode->low = dd->perm[auxnode->index];
        if (auxnode->child != NULL) {
            ddPatchTree(dd, auxnode->child);
        }
        auxnode = auxnode->younger;
Alan Mishchenko committed
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
    }

    return;

} /* end of ddPatchTree */


#ifdef DD_DEBUG
/**Function********************************************************************

  Synopsis    [Checks whether a collision list is ordered.]

  Description []

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddCheckCollisionOrdering(
  DdManager *unique,
  int i,
  int j)
{
    int slots;
    DdNode *node, *next;
    DdNodePtr *nodelist;
    DdNode *sentinel = &(unique->sentinel);

    nodelist = unique->subtables[i].nodelist;
    slots = unique->subtables[i].slots;
    node = nodelist[j];
    if (node == sentinel) return(1);
    next = node->next;
    while (next != sentinel) {
3128 3129 3130 3131 3132 3133 3134 3135
        if (cuddT(node) < cuddT(next) ||
            (cuddT(node) == cuddT(next) && cuddE(node) < cuddE(next))) {
            (void) fprintf(unique->err,
                           "Unordered list: index %u, position %d\n", i, j);
            return(0);
        }
        node = next;
        next = node->next;
Alan Mishchenko committed
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
    }
    return(1);

} /* end of cuddCheckCollisionOrdering */
#endif




/**Function********************************************************************

  Synopsis    [Reports problem in garbage collection.]

  Description []

  SideEffects [None]

  SeeAlso     [cuddGarbageCollect cuddGarbageCollectZdd]

******************************************************************************/
static void
ddReportRefMess(
  DdManager *unique /* manager */,
  int i /* table in which the problem occurred */,
3160
  const char *caller /* procedure that detected the problem */)
Alan Mishchenko committed
3161 3162
{
    if (i == CUDD_CONST_INDEX) {
3163 3164
        (void) fprintf(unique->err,
                           "%s: problem in constants\n", caller);
Alan Mishchenko committed
3165
    } else if (i != -1) {
3166 3167
        (void) fprintf(unique->err,
                           "%s: problem in table %d\n", caller, i);
Alan Mishchenko committed
3168 3169 3170 3171 3172 3173 3174 3175
    }
    (void) fprintf(unique->err, "  dead count != deleted\n");
    (void) fprintf(unique->err, "  This problem is often due to a missing \
call to Cudd_Ref\n  or to an extra call to Cudd_RecursiveDeref.\n  \
See the CUDD Programmer's Guide for additional details.");
    abort();

} /* end of ddReportRefMess */
3176 3177


3178 3179
ABC_NAMESPACE_IMPL_END