The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

2066 lines
53 KiB

2 months ago
  1. /**
  2. @file
  3. @ingroup cudd
  4. @brief Functions for dynamic variable reordering.
  5. @author Shipra Panda, Bernard Plessier, Fabio Somenzi
  6. @copyright@parblock
  7. Copyright (c) 1995-2015, Regents of the University of Colorado
  8. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions
  11. are met:
  12. Redistributions of source code must retain the above copyright
  13. notice, this list of conditions and the following disclaimer.
  14. Redistributions in binary form must reproduce the above copyright
  15. notice, this list of conditions and the following disclaimer in the
  16. documentation and/or other materials provided with the distribution.
  17. Neither the name of the University of Colorado nor the names of its
  18. contributors may be used to endorse or promote products derived from
  19. this software without specific prior written permission.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  24. COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  30. ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. POSSIBILITY OF SUCH DAMAGE.
  32. @endparblock
  33. */
  34. #include "util.h"
  35. #include "mtrInt.h"
  36. #include "cuddInt.h"
  37. /*---------------------------------------------------------------------------*/
  38. /* Constant declarations */
  39. /*---------------------------------------------------------------------------*/
  40. /*---------------------------------------------------------------------------*/
  41. /* Stucture declarations */
  42. /*---------------------------------------------------------------------------*/
  43. /*---------------------------------------------------------------------------*/
  44. /* Type declarations */
  45. /*---------------------------------------------------------------------------*/
  46. /*---------------------------------------------------------------------------*/
  47. /* Variable declarations */
  48. /*---------------------------------------------------------------------------*/
  49. /*---------------------------------------------------------------------------*/
  50. /* Macro declarations */
  51. /*---------------------------------------------------------------------------*/
  52. /** \cond */
  53. /*---------------------------------------------------------------------------*/
  54. /* Static function prototypes */
  55. /*---------------------------------------------------------------------------*/
  56. static int ddUniqueCompare (void const *ptrX, void const *ptrY);
  57. static Move * ddSwapAny (DdManager *table, int x, int y);
  58. static int ddSiftingAux (DdManager *table, int x, int xLow, int xHigh);
  59. static Move * ddSiftingUp (DdManager *table, int y, int xLow);
  60. static Move * ddSiftingDown (DdManager *table, int x, int xHigh);
  61. static int ddSiftingBackward (DdManager *table, int size, Move *moves);
  62. static int ddReorderPreprocess (DdManager *table);
  63. static int ddReorderPostprocess (DdManager *table);
  64. static int ddShuffle (DdManager *table, int *permutation);
  65. static int ddSiftUp (DdManager *table, int x, int xLow);
  66. static void bddFixTree (DdManager *table, MtrNode *treenode);
  67. static int ddUpdateMtrTree (DdManager *table, MtrNode *treenode, int *perm, int *invperm);
  68. static int ddCheckPermuation (DdManager *table, MtrNode *treenode, int *perm, int *invperm);
  69. /** \endcond */
  70. /*---------------------------------------------------------------------------*/
  71. /* Definition of exported functions */
  72. /*---------------------------------------------------------------------------*/
  73. /**
  74. @brief Main dynamic reordering routine.
  75. @details Calls one of the possible reordering procedures:
  76. <ul>
  77. <li>Swapping
  78. <li>Sifting
  79. <li>Symmetric Sifting
  80. <li>Group Sifting
  81. <li>Window Permutation
  82. <li>Simulated Annealing
  83. <li>Genetic Algorithm
  84. <li>Dynamic Programming (exact)
  85. </ul>
  86. For sifting, symmetric sifting, group sifting, and window
  87. permutation it is possible to request reordering to convergence.<p>
  88. The core of all methods is the reordering procedure
  89. cuddSwapInPlace() which swaps two adjacent variables and is based
  90. on Rudell's paper.
  91. @return 1 in case of success; 0 otherwise. In the case of symmetric
  92. sifting (with and without convergence) returns 1 plus the number of
  93. symmetric variables, in case of success.
  94. @sideeffect Changes the variable order for all diagrams and clears
  95. the cache.
  96. */
  97. int
  98. Cudd_ReduceHeap(
  99. DdManager * table /**< %DD manager */,
  100. Cudd_ReorderingType heuristic /**< method used for reordering */,
  101. int minsize /**< bound below which no reordering occurs */)
  102. {
  103. DdHook *hook;
  104. int result;
  105. unsigned int nextDyn;
  106. #ifdef DD_STATS
  107. unsigned int initialSize;
  108. unsigned int finalSize;
  109. #endif
  110. unsigned long localTime;
  111. /* Don't reorder if there are too many dead nodes. */
  112. if (table->keys - table->dead < (unsigned) minsize)
  113. return(1);
  114. if (heuristic == CUDD_REORDER_SAME) {
  115. heuristic = table->autoMethod;
  116. }
  117. if (heuristic == CUDD_REORDER_NONE) {
  118. return(1);
  119. }
  120. /* This call to Cudd_ReduceHeap does initiate reordering. Therefore
  121. ** we count it.
  122. */
  123. table->reorderings++;
  124. localTime = util_cpu_time();
  125. /* Run the hook functions. */
  126. hook = table->preReorderingHook;
  127. while (hook != NULL) {
  128. int res = (hook->f)(table, "BDD", (void *)heuristic);
  129. if (res == 0) return(0);
  130. hook = hook->next;
  131. }
  132. if (!ddReorderPreprocess(table)) return(0);
  133. table->ddTotalNumberSwapping = 0;
  134. if (table->keys > table->peakLiveNodes) {
  135. table->peakLiveNodes = table->keys;
  136. }
  137. #ifdef DD_STATS
  138. initialSize = (int) (table->keys - table->isolated);
  139. table->totalNISwaps = 0;
  140. switch(heuristic) {
  141. case CUDD_REORDER_RANDOM:
  142. case CUDD_REORDER_RANDOM_PIVOT:
  143. (void) fprintf(table->out,"#:I_RANDOM ");
  144. break;
  145. case CUDD_REORDER_SIFT:
  146. case CUDD_REORDER_SIFT_CONVERGE:
  147. case CUDD_REORDER_SYMM_SIFT:
  148. case CUDD_REORDER_SYMM_SIFT_CONV:
  149. case CUDD_REORDER_GROUP_SIFT:
  150. case CUDD_REORDER_GROUP_SIFT_CONV:
  151. (void) fprintf(table->out,"#:I_SIFTING ");
  152. break;
  153. case CUDD_REORDER_WINDOW2:
  154. case CUDD_REORDER_WINDOW3:
  155. case CUDD_REORDER_WINDOW4:
  156. case CUDD_REORDER_WINDOW2_CONV:
  157. case CUDD_REORDER_WINDOW3_CONV:
  158. case CUDD_REORDER_WINDOW4_CONV:
  159. (void) fprintf(table->out,"#:I_WINDOW ");
  160. break;
  161. case CUDD_REORDER_ANNEALING:
  162. (void) fprintf(table->out,"#:I_ANNEAL ");
  163. break;
  164. case CUDD_REORDER_GENETIC:
  165. (void) fprintf(table->out,"#:I_GENETIC ");
  166. break;
  167. case CUDD_REORDER_LINEAR:
  168. case CUDD_REORDER_LINEAR_CONVERGE:
  169. (void) fprintf(table->out,"#:I_LINSIFT ");
  170. break;
  171. case CUDD_REORDER_EXACT:
  172. (void) fprintf(table->out,"#:I_EXACT ");
  173. break;
  174. default:
  175. return(0);
  176. }
  177. (void) fprintf(table->out,"%8d: initial size",initialSize);
  178. #endif
  179. /* See if we should use alternate threshold for maximum growth. */
  180. if (table->reordCycle && table->reorderings % table->reordCycle == 0) {
  181. double saveGrowth = table->maxGrowth;
  182. table->maxGrowth = table->maxGrowthAlt;
  183. result = cuddTreeSifting(table,heuristic);
  184. table->maxGrowth = saveGrowth;
  185. } else {
  186. result = cuddTreeSifting(table,heuristic);
  187. }
  188. #ifdef DD_STATS
  189. (void) fprintf(table->out,"\n");
  190. finalSize = (int) (table->keys - table->isolated);
  191. (void) fprintf(table->out,"#:F_REORDER %8d: final size\n",finalSize);
  192. (void) fprintf(table->out,"#:T_REORDER %8g: total time (sec)\n",
  193. ((double)(util_cpu_time() - localTime)/1000.0));
  194. (void) fprintf(table->out,"#:N_REORDER %8d: total swaps\n",
  195. table->ddTotalNumberSwapping);
  196. (void) fprintf(table->out,"#:M_REORDER %8d: NI swaps\n",
  197. table->totalNISwaps);
  198. #endif
  199. if (result == 0)
  200. return(0);
  201. if (!ddReorderPostprocess(table))
  202. return(0);
  203. if (table->realign) {
  204. if (!cuddZddAlignToBdd(table))
  205. return(0);
  206. }
  207. nextDyn = (table->keys - table->constants.keys + 1) *
  208. DD_DYN_RATIO + table->constants.keys;
  209. if (table->reorderings < 20 || nextDyn > table->nextDyn)
  210. table->nextDyn = nextDyn;
  211. else
  212. table->nextDyn += 20;
  213. if (table->randomizeOrder != 0) {
  214. table->nextDyn += Cudd_Random(table) & table->randomizeOrder;
  215. }
  216. table->reordered = 1;
  217. /* Run hook functions. */
  218. hook = table->postReorderingHook;
  219. while (hook != NULL) {
  220. int res = (hook->f)(table, "BDD", (void *)(ptruint)localTime);
  221. if (res == 0) return(0);
  222. hook = hook->next;
  223. }
  224. /* Update cumulative reordering time. */
  225. table->reordTime += util_cpu_time() - localTime;
  226. return(result);
  227. } /* end of Cudd_ReduceHeap */
  228. /**
  229. @brief Reorders variables according to given permutation.
  230. @details The i-th entry of the permutation array contains the index
  231. of the variable that should be brought to the i-th level. The size
  232. of the array should be equal or greater to the number of variables
  233. currently in use.
  234. @return 1 in case of success; 0 otherwise.
  235. @sideeffect Changes the variable order for all diagrams and clears
  236. the cache.
  237. @see Cudd_ReduceHeap
  238. */
  239. int
  240. Cudd_ShuffleHeap(
  241. DdManager * table /**< %DD manager */,
  242. int * permutation /**< required variable permutation */)
  243. {
  244. int result;
  245. int i;
  246. int identity = 1;
  247. int *perm;
  248. /* Don't waste time in case of identity permutation. */
  249. for (i = 0; i < table->size; i++) {
  250. if (permutation[i] != table->invperm[i]) {
  251. identity = 0;
  252. break;
  253. }
  254. }
  255. if (identity == 1) {
  256. return(1);
  257. }
  258. if (!ddReorderPreprocess(table)) return(0);
  259. if (table->keys > table->peakLiveNodes) {
  260. table->peakLiveNodes = table->keys;
  261. }
  262. perm = ALLOC(int, table->size);
  263. for (i = 0; i < table->size; i++)
  264. perm[permutation[i]] = i;
  265. if (!ddCheckPermuation(table,table->tree,perm,permutation)) {
  266. FREE(perm);
  267. return(0);
  268. }
  269. if (!ddUpdateMtrTree(table,table->tree,perm,permutation)) {
  270. FREE(perm);
  271. return(0);
  272. }
  273. FREE(perm);
  274. result = ddShuffle(table,permutation);
  275. if (!ddReorderPostprocess(table)) return(0);
  276. return(result);
  277. } /* end of Cudd_ShuffleHeap */
  278. /*---------------------------------------------------------------------------*/
  279. /* Definition of internal functions */
  280. /*---------------------------------------------------------------------------*/
  281. /**
  282. @brief Dynamically allocates a Node.
  283. @details This procedure is similar to cuddAllocNode in Cudd_Table.c,
  284. but it does not attempt garbage collection, because during
  285. reordering there are no dead nodes.
  286. @return a pointer to a new node if successful; NULL is memory is
  287. full.
  288. @sideeffect None
  289. @see cuddAllocNode
  290. */
  291. DdNode *
  292. cuddDynamicAllocNode(
  293. DdManager * table)
  294. {
  295. int i;
  296. DdNodePtr *mem;
  297. DdNode *list, *node;
  298. extern DD_OOMFP MMoutOfMemory;
  299. DD_OOMFP saveHandler;
  300. if (table->nextFree == NULL) { /* free list is empty */
  301. /* Try to allocate a new block. */
  302. saveHandler = MMoutOfMemory;
  303. MMoutOfMemory = table->outOfMemCallback;
  304. mem = (DdNodePtr *) ALLOC(DdNode, DD_MEM_CHUNK + 1);
  305. MMoutOfMemory = saveHandler;
  306. if (mem == NULL && table->stash != NULL) {
  307. FREE(table->stash);
  308. table->stash = NULL;
  309. /* Inhibit resizing of tables. */
  310. table->maxCacheHard = table->cacheSlots - 1;
  311. table->cacheSlack = - (int) (table->cacheSlots + 1);
  312. for (i = 0; i < table->size; i++) {
  313. table->subtables[i].maxKeys <<= 2;
  314. }
  315. mem = (DdNodePtr *) ALLOC(DdNode,DD_MEM_CHUNK + 1);
  316. }
  317. if (mem == NULL) {
  318. /* Out of luck. Call the default handler to do
  319. ** whatever it specifies for a failed malloc. If this
  320. ** handler returns, then set error code, print
  321. ** warning, and return. */
  322. (*MMoutOfMemory)(sizeof(DdNode)*(DD_MEM_CHUNK + 1));
  323. table->errorCode = CUDD_MEMORY_OUT;
  324. #ifdef DD_VERBOSE
  325. (void) fprintf(table->err,
  326. "cuddDynamicAllocNode: out of memory");
  327. (void) fprintf(table->err,"Memory in use = %lu\n",
  328. table->memused);
  329. #endif
  330. return(NULL);
  331. } else { /* successful allocation; slice memory */
  332. size_t offset;
  333. table->memused += (DD_MEM_CHUNK + 1) * sizeof(DdNode);
  334. mem[0] = (DdNode *) table->memoryList;
  335. table->memoryList = mem;
  336. /* Here we rely on the fact that the size of a DdNode is a
  337. ** power of 2 and a multiple of the size of a pointer.
  338. ** If we align one node, all the others will be aligned
  339. ** as well. */
  340. offset = (size_t) mem & (sizeof(DdNode) - 1);
  341. mem += (sizeof(DdNode) - offset) / sizeof(DdNodePtr);
  342. #ifdef DD_DEBUG
  343. assert(((size_t) mem & (sizeof(DdNode) - 1)) == 0);
  344. #endif
  345. list = (DdNode *) mem;
  346. i = 1;
  347. do {
  348. list[i - 1].ref = 0;
  349. list[i - 1].next = &list[i];
  350. } while (++i < DD_MEM_CHUNK);
  351. list[DD_MEM_CHUNK-1].ref = 0;
  352. list[DD_MEM_CHUNK - 1].next = NULL;
  353. table->nextFree = &list[0];
  354. }
  355. } /* if free list empty */
  356. node = table->nextFree;
  357. table->nextFree = node->next;
  358. return (node);
  359. } /* end of cuddDynamicAllocNode */
  360. /**
  361. @brief Implementation of Rudell's sifting algorithm.
  362. @details Assumes that no dead nodes are present.
  363. <ol>
  364. <li> Order all the variables according to the number of entries
  365. in each unique table.
  366. <li> Sift the variable up and down, remembering each time the
  367. total size of the %DD heap.
  368. <li> Select the best permutation.
  369. <li> Repeat 3 and 4 for all variables.
  370. </ol>
  371. @return 1 if successful; 0 otherwise.
  372. @sideeffect None
  373. */
  374. int
  375. cuddSifting(
  376. DdManager * table,
  377. int lower,
  378. int upper)
  379. {
  380. int i;
  381. IndexKey *var;
  382. int size;
  383. int x;
  384. int result;
  385. #ifdef DD_STATS
  386. int previousSize;
  387. #endif
  388. size = table->size;
  389. /* Find order in which to sift variables. */
  390. var = ALLOC(IndexKey,size);
  391. if (var == NULL) {
  392. table->errorCode = CUDD_MEMORY_OUT;
  393. goto cuddSiftingOutOfMem;
  394. }
  395. for (i = 0; i < size; i++) {
  396. x = table->perm[i];
  397. var[i].index = i;
  398. var[i].keys = table->subtables[x].keys;
  399. }
  400. util_qsort(var,size,sizeof(IndexKey),ddUniqueCompare);
  401. /* Now sift. */
  402. for (i = 0; i < ddMin(table->siftMaxVar,size); i++) {
  403. if (table->ddTotalNumberSwapping >= table->siftMaxSwap)
  404. break;
  405. if (util_cpu_time() - table->startTime + table->reordTime
  406. > table->timeLimit) {
  407. table->autoDyn = 0; /* prevent further reordering */
  408. break;
  409. }
  410. if (table->terminationCallback != NULL &&
  411. table->terminationCallback(table->tcbArg)) {
  412. table->autoDyn = 0; /* prevent further reordering */
  413. break;
  414. }
  415. x = table->perm[var[i].index];
  416. if (x < lower || x > upper || table->subtables[x].bindVar == 1)
  417. continue;
  418. #ifdef DD_STATS
  419. previousSize = (int) (table->keys - table->isolated);
  420. #endif
  421. result = ddSiftingAux(table, x, lower, upper);
  422. if (!result) goto cuddSiftingOutOfMem;
  423. #ifdef DD_STATS
  424. if (table->keys < (unsigned) previousSize + table->isolated) {
  425. (void) fprintf(table->out,"-");
  426. } else if (table->keys > (unsigned) previousSize + table->isolated) {
  427. (void) fprintf(table->out,"+"); /* should never happen */
  428. (void) fprintf(table->err,"\nSize increased from %d to %u while sifting variable %d\n", previousSize, table->keys - table->isolated, var[i].index);
  429. } else {
  430. (void) fprintf(table->out,"=");
  431. }
  432. fflush(table->out);
  433. #endif
  434. }
  435. FREE(var);
  436. return(1);
  437. cuddSiftingOutOfMem:
  438. if (var != NULL) FREE(var);
  439. return(0);
  440. } /* end of cuddSifting */
  441. /**
  442. @brief Reorders variables by a sequence of (non-adjacent) swaps.
  443. @details Implementation of Plessier's algorithm that reorders
  444. variables by a sequence of (non-adjacent) swaps.
  445. <ol>
  446. <li> Select two variables (RANDOM or HEURISTIC).
  447. <li> Permute these variables.
  448. <li> If the nodes have decreased accept the permutation.
  449. <li> Otherwise reconstruct the original heap.
  450. <li> Loop.
  451. </ol>
  452. @return 1 in case of success; 0 otherwise.
  453. @sideeffect None
  454. */
  455. int
  456. cuddSwapping(
  457. DdManager * table,
  458. int lower,
  459. int upper,
  460. Cudd_ReorderingType heuristic)
  461. {
  462. int i, j;
  463. int max, keys;
  464. int nvars;
  465. int x, y;
  466. int iterate;
  467. int previousSize;
  468. Move *moves, *move;
  469. int pivot = 0;
  470. int modulo;
  471. int result;
  472. #ifdef DD_DEBUG
  473. /* Sanity check */
  474. assert(lower >= 0 && upper < table->size && lower <= upper);
  475. #endif
  476. nvars = upper - lower + 1;
  477. iterate = nvars;
  478. for (i = 0; i < iterate; i++) {
  479. if (table->ddTotalNumberSwapping >= table->siftMaxSwap)
  480. break;
  481. if (heuristic == CUDD_REORDER_RANDOM_PIVOT) {
  482. max = -1;
  483. for (j = lower; j <= upper; j++) {
  484. if ((keys = table->subtables[j].keys) > max) {
  485. max = keys;
  486. pivot = j;
  487. }
  488. }
  489. modulo = upper - pivot;
  490. if (modulo == 0) {
  491. y = pivot;
  492. } else{
  493. y = pivot + 1 + ((int) Cudd_Random(table) % modulo);
  494. }
  495. modulo = pivot - lower - 1;
  496. if (modulo < 1) {
  497. x = lower;
  498. } else{
  499. do {
  500. x = (int) Cudd_Random(table) % modulo;
  501. } while (x == y);
  502. }
  503. } else {
  504. x = ((int) Cudd_Random(table) % nvars) + lower;
  505. do {
  506. y = ((int) Cudd_Random(table) % nvars) + lower;
  507. } while (x == y);
  508. }
  509. previousSize = (int) (table->keys - table->isolated);
  510. moves = ddSwapAny(table,x,y);
  511. if (moves == NULL) goto cuddSwappingOutOfMem;
  512. result = ddSiftingBackward(table,previousSize,moves);
  513. if (!result) goto cuddSwappingOutOfMem;
  514. while (moves != NULL) {
  515. move = moves->next;
  516. cuddDeallocMove(table, moves);
  517. moves = move;
  518. }
  519. #ifdef DD_STATS
  520. if (table->keys < (unsigned) previousSize + table->isolated) {
  521. (void) fprintf(table->out,"-");
  522. } else if (table->keys > (unsigned) previousSize + table->isolated) {
  523. (void) fprintf(table->out,"+"); /* should never happen */
  524. } else {
  525. (void) fprintf(table->out,"=");
  526. }
  527. fflush(table->out);
  528. #endif
  529. #if 0
  530. (void) fprintf(table->out,"#:t_SWAPPING %8d: tmp size\n",
  531. table->keys - table->isolated);
  532. #endif
  533. }
  534. return(1);
  535. cuddSwappingOutOfMem:
  536. while (moves != NULL) {
  537. move = moves->next;
  538. cuddDeallocMove(table, moves);
  539. moves = move;
  540. }
  541. return(0);
  542. } /* end of cuddSwapping */
  543. /**
  544. @brief Finds the next subtable with a larger index.
  545. @return the index.
  546. @sideeffect None
  547. @see cuddNextLow
  548. */
  549. int
  550. cuddNextHigh(
  551. DdManager * table,
  552. int x)
  553. {
  554. (void) table; /* avoid warning */
  555. return(x+1);
  556. } /* end of cuddNextHigh */
  557. /**
  558. @brief Finds the next subtable with a smaller index.
  559. @return the index.
  560. @sideeffect None
  561. @see cuddNextHigh
  562. */
  563. int
  564. cuddNextLow(
  565. DdManager * table,
  566. int x)
  567. {
  568. (void) table; /* avoid warning */
  569. return(x-1);
  570. } /* end of cuddNextLow */
  571. /**
  572. @brief Swaps two adjacent variables.
  573. @details It assumes that no dead nodes are present on entry to this
  574. procedure. The procedure then guarantees that no dead nodes will be
  575. present when it terminates. cuddSwapInPlace assumes that x &lt; y.
  576. @return the number of keys in the table if successful; 0 otherwise.
  577. @sideeffect None
  578. */
  579. int
  580. cuddSwapInPlace(
  581. DdManager * table,
  582. int x,
  583. int y)
  584. {
  585. DdNodePtr *xlist, *ylist;
  586. int xindex, yindex;
  587. int xslots, yslots;
  588. int xshift, yshift;
  589. int oldxkeys, oldykeys;
  590. int newxkeys, newykeys;
  591. int comple, newcomplement;
  592. int i;
  593. Cudd_VariableType varType;
  594. Cudd_LazyGroupType groupType;
  595. int posn;
  596. int isolated;
  597. DdNode *f,*f0,*f1,*f01,*f00,*f11,*f10,*newf1,*newf0;
  598. DdNode *g,*next;
  599. DdNodePtr *previousP;
  600. DdNode *tmp;
  601. DdNode *sentinel = &(table->sentinel);
  602. extern DD_OOMFP MMoutOfMemory;
  603. DD_OOMFP saveHandler;
  604. #ifdef DD_DEBUG
  605. int count,idcheck;
  606. #endif
  607. #ifdef DD_DEBUG
  608. assert(x < y);
  609. assert(cuddNextHigh(table,x) == y);
  610. assert(table->subtables[x].keys != 0);
  611. assert(table->subtables[y].keys != 0);
  612. assert(table->subtables[x].dead == 0);
  613. assert(table->subtables[y].dead == 0);
  614. #endif
  615. table->ddTotalNumberSwapping++;
  616. /* Get parameters of x subtable. */
  617. xindex = table->invperm[x];
  618. xlist = table->subtables[x].nodelist;
  619. oldxkeys = table->subtables[x].keys;
  620. xslots = table->subtables[x].slots;
  621. xshift = table->subtables[x].shift;
  622. /* Get parameters of y subtable. */
  623. yindex = table->invperm[y];
  624. ylist = table->subtables[y].nodelist;
  625. oldykeys = table->subtables[y].keys;
  626. yslots = table->subtables[y].slots;
  627. yshift = table->subtables[y].shift;
  628. if (!cuddTestInteract(table,xindex,yindex)) {
  629. #ifdef DD_STATS
  630. table->totalNISwaps++;
  631. #endif
  632. newxkeys = oldxkeys;
  633. newykeys = oldykeys;
  634. } else {
  635. newxkeys = 0;
  636. newykeys = oldykeys;
  637. /* Check whether the two projection functions involved in this
  638. ** swap are isolated. At the end, we'll be able to tell how many
  639. ** isolated projection functions are there by checking only these
  640. ** two functions again. This is done to eliminate the isolated
  641. ** projection functions from the node count.
  642. */
  643. isolated = - ((table->vars[xindex]->ref == 1) +
  644. (table->vars[yindex]->ref == 1));
  645. /* The nodes in the x layer that do not depend on
  646. ** y will stay there; the others are put in a chain.
  647. ** The chain is handled as a LIFO; g points to the beginning.
  648. */
  649. g = NULL;
  650. if ((oldxkeys >= xslots || (unsigned) xslots == table->initSlots) &&
  651. oldxkeys <= DD_MAX_SUBTABLE_DENSITY * xslots) {
  652. for (i = 0; i < xslots; i++) {
  653. previousP = &(xlist[i]);
  654. f = *previousP;
  655. while (f != sentinel) {
  656. next = f->next;
  657. f1 = cuddT(f); f0 = cuddE(f);
  658. if (f1->index != (DdHalfWord) yindex &&
  659. Cudd_Regular(f0)->index != (DdHalfWord) yindex) {
  660. /* stays */
  661. newxkeys++;
  662. *previousP = f;
  663. previousP = &(f->next);
  664. } else {
  665. f->index = yindex;
  666. f->next = g;
  667. g = f;
  668. }
  669. f = next;
  670. } /* while there are elements in the collision chain */
  671. *previousP = sentinel;
  672. } /* for each slot of the x subtable */
  673. } else { /* resize xlist */
  674. DdNode *h = NULL;
  675. DdNodePtr *newxlist;
  676. unsigned int newxslots;
  677. int newxshift;
  678. /* Empty current xlist. Nodes that stay go to list h;
  679. ** nodes that move go to list g. */
  680. for (i = 0; i < xslots; i++) {
  681. f = xlist[i];
  682. while (f != sentinel) {
  683. next = f->next;
  684. f1 = cuddT(f); f0 = cuddE(f);
  685. if (f1->index != (DdHalfWord) yindex &&
  686. Cudd_Regular(f0)->index != (DdHalfWord) yindex) {
  687. /* stays */
  688. f->next = h;
  689. h = f;
  690. newxkeys++;
  691. } else {
  692. f->index = yindex;
  693. f->next = g;
  694. g = f;
  695. }
  696. f = next;
  697. } /* while there are elements in the collision chain */
  698. } /* for each slot of the x subtable */
  699. /* Decide size of new subtable. */
  700. newxshift = xshift;
  701. newxslots = xslots;
  702. while ((unsigned) oldxkeys > DD_MAX_SUBTABLE_DENSITY * newxslots) {
  703. newxshift--;
  704. newxslots <<= 1;
  705. }
  706. while ((unsigned) oldxkeys < newxslots &&
  707. newxslots > table->initSlots) {
  708. newxshift++;
  709. newxslots >>= 1;
  710. }
  711. /* Try to allocate new table. Be ready to back off. */
  712. saveHandler = MMoutOfMemory;
  713. MMoutOfMemory = table->outOfMemCallback;
  714. newxlist = ALLOC(DdNodePtr, newxslots);
  715. MMoutOfMemory = saveHandler;
  716. if (newxlist == NULL) {
  717. (void) fprintf(table->err, "Unable to resize subtable %d for lack of memory\n", i);
  718. } else {
  719. table->slots += ((int) newxslots - xslots);
  720. table->minDead = (unsigned)
  721. (table->gcFrac * (double) table->slots);
  722. table->cacheSlack = (int)
  723. ddMin(table->maxCacheHard, DD_MAX_CACHE_TO_SLOTS_RATIO
  724. * table->slots) - 2 * (int) table->cacheSlots;
  725. table->memused +=
  726. ((int) newxslots - xslots) * sizeof(DdNodePtr);
  727. FREE(xlist);
  728. xslots = newxslots;
  729. xshift = newxshift;
  730. xlist = newxlist;
  731. }
  732. /* Initialize new subtable. */
  733. for (i = 0; i < xslots; i++) {
  734. xlist[i] = sentinel;
  735. }
  736. /* Move nodes that were parked in list h to their new home. */
  737. f = h;
  738. while (f != NULL) {
  739. next = f->next;
  740. f1 = cuddT(f);
  741. f0 = cuddE(f);
  742. /* Check xlist for pair (f11,f01). */
  743. posn = ddHash(f1, f0, xshift);
  744. /* For each element tmp in collision list xlist[posn]. */
  745. previousP = &(xlist[posn]);
  746. tmp = *previousP;
  747. while (f1 < cuddT(tmp)) {
  748. previousP = &(tmp->next);
  749. tmp = *previousP;
  750. }
  751. while (f1 == cuddT(tmp) && f0 < cuddE(tmp)) {
  752. previousP = &(tmp->next);
  753. tmp = *previousP;
  754. }
  755. f->next = *previousP;
  756. *previousP = f;
  757. f = next;
  758. }
  759. }
  760. #ifdef DD_COUNT
  761. table->swapSteps += oldxkeys - newxkeys;
  762. #endif
  763. /* Take care of the x nodes that must be re-expressed.
  764. ** They form a linked list pointed by g. Their index has been
  765. ** already changed to yindex.
  766. */
  767. f = g;
  768. while (f != NULL) {
  769. next = f->next;
  770. /* Find f1, f0, f11, f10, f01, f00. */
  771. f1 = cuddT(f);
  772. #ifdef DD_DEBUG
  773. assert(!(Cudd_IsComplement(f1)));
  774. #endif
  775. if ((int) f1->index == yindex) {
  776. f11 = cuddT(f1); f10 = cuddE(f1);
  777. } else {
  778. f11 = f10 = f1;
  779. }
  780. #ifdef DD_DEBUG
  781. assert(!(Cudd_IsComplement(f11)));
  782. #endif
  783. f0 = cuddE(f);
  784. comple = Cudd_IsComplement(f0);
  785. f0 = Cudd_Regular(f0);
  786. if ((int) f0->index == yindex) {
  787. f01 = cuddT(f0); f00 = cuddE(f0);
  788. } else {
  789. f01 = f00 = f0;
  790. }
  791. if (comple) {
  792. f01 = Cudd_Not(f01);
  793. f00 = Cudd_Not(f00);
  794. }
  795. /* Decrease ref count of f1. */
  796. cuddSatDec(f1->ref);
  797. /* Create the new T child. */
  798. if (f11 == f01) {
  799. newf1 = f11;
  800. cuddSatInc(newf1->ref);
  801. } else {
  802. /* Check xlist for triple (xindex,f11,f01). */
  803. posn = ddHash(f11, f01, xshift);
  804. /* For each element newf1 in collision list xlist[posn]. */
  805. previousP = &(xlist[posn]);
  806. newf1 = *previousP;
  807. while (f11 < cuddT(newf1)) {
  808. previousP = &(newf1->next);
  809. newf1 = *previousP;
  810. }
  811. while (f11 == cuddT(newf1) && f01 < cuddE(newf1)) {
  812. previousP = &(newf1->next);
  813. newf1 = *previousP;
  814. }
  815. if (cuddT(newf1) == f11 && cuddE(newf1) == f01) {
  816. cuddSatInc(newf1->ref);
  817. } else { /* no match */
  818. newf1 = cuddDynamicAllocNode(table);
  819. if (newf1 == NULL)
  820. goto cuddSwapOutOfMem;
  821. newf1->index = xindex; newf1->ref = 1;
  822. cuddT(newf1) = f11;
  823. cuddE(newf1) = f01;
  824. /* Insert newf1 in the collision list xlist[posn];
  825. ** increase the ref counts of f11 and f01.
  826. */
  827. newxkeys++;
  828. newf1->next = *previousP;
  829. *previousP = newf1;
  830. cuddSatInc(f11->ref);
  831. tmp = Cudd_Regular(f01);
  832. cuddSatInc(tmp->ref);
  833. }
  834. }
  835. cuddT(f) = newf1;
  836. #ifdef DD_DEBUG
  837. assert(!(Cudd_IsComplement(newf1)));
  838. #endif
  839. /* Do the same for f0, keeping complement dots into account. */
  840. /* Decrease ref count of f0. */
  841. tmp = Cudd_Regular(f0);
  842. cuddSatDec(tmp->ref);
  843. /* Create the new E child. */
  844. if (f10 == f00) {
  845. newf0 = f00;
  846. tmp = Cudd_Regular(newf0);
  847. cuddSatInc(tmp->ref);
  848. } else {
  849. /* make sure f10 is regular */
  850. newcomplement = Cudd_IsComplement(f10);
  851. if (newcomplement) {
  852. f10 = Cudd_Not(f10);
  853. f00 = Cudd_Not(f00);
  854. }
  855. /* Check xlist for triple (xindex,f10,f00). */
  856. posn = ddHash(f10, f00, xshift);
  857. /* For each element newf0 in collision list xlist[posn]. */
  858. previousP = &(xlist[posn]);
  859. newf0 = *previousP;
  860. while (f10 < cuddT(newf0)) {
  861. previousP = &(newf0->next);
  862. newf0 = *previousP;
  863. }
  864. while (f10 == cuddT(newf0) && f00 < cuddE(newf0)) {
  865. previousP = &(newf0->next);
  866. newf0 = *previousP;
  867. }
  868. if (cuddT(newf0) == f10 && cuddE(newf0) == f00) {
  869. cuddSatInc(newf0->ref);
  870. } else { /* no match */
  871. newf0 = cuddDynamicAllocNode(table);
  872. if (newf0 == NULL)
  873. goto cuddSwapOutOfMem;
  874. newf0->index = xindex; newf0->ref = 1;
  875. cuddT(newf0) = f10;
  876. cuddE(newf0) = f00;
  877. /* Insert newf0 in the collision list xlist[posn];
  878. ** increase the ref counts of f10 and f00.
  879. */
  880. newxkeys++;
  881. newf0->next = *previousP;
  882. *previousP = newf0;
  883. cuddSatInc(f10->ref);
  884. tmp = Cudd_Regular(f00);
  885. cuddSatInc(tmp->ref);
  886. }
  887. if (newcomplement) {
  888. newf0 = Cudd_Not(newf0);
  889. }
  890. }
  891. cuddE(f) = newf0;
  892. /* Insert the modified f in ylist.
  893. ** The modified f does not already exists in ylist.
  894. ** (Because of the uniqueness of the cofactors.)
  895. */
  896. posn = ddHash(newf1, newf0, yshift);
  897. newykeys++;
  898. previousP = &(ylist[posn]);
  899. tmp = *previousP;
  900. while (newf1 < cuddT(tmp)) {
  901. previousP = &(tmp->next);
  902. tmp = *previousP;
  903. }
  904. while (newf1 == cuddT(tmp) && newf0 < cuddE(tmp)) {
  905. previousP = &(tmp->next);
  906. tmp = *previousP;
  907. }
  908. f->next = *previousP;
  909. *previousP = f;
  910. f = next;
  911. } /* while f != NULL */
  912. /* GC the y layer. */
  913. /* For each node f in ylist. */
  914. for (i = 0; i < yslots; i++) {
  915. previousP = &(ylist[i]);
  916. f = *previousP;
  917. while (f != sentinel) {
  918. next = f->next;
  919. if (f->ref == 0) {
  920. tmp = cuddT(f);
  921. cuddSatDec(tmp->ref);
  922. tmp = Cudd_Regular(cuddE(f));
  923. cuddSatDec(tmp->ref);
  924. cuddDeallocNode(table,f);
  925. newykeys--;
  926. } else {
  927. *previousP = f;
  928. previousP = &(f->next);
  929. }
  930. f = next;
  931. } /* while f */
  932. *previousP = sentinel;
  933. } /* for i */
  934. #ifdef DD_DEBUG
  935. #if 0
  936. (void) fprintf(table->out,"Swapping %d and %d\n",x,y);
  937. #endif
  938. count = 0;
  939. idcheck = 0;
  940. for (i = 0; i < yslots; i++) {
  941. f = ylist[i];
  942. while (f != sentinel) {
  943. count++;
  944. if (f->index != (DdHalfWord) yindex)
  945. idcheck++;
  946. f = f->next;
  947. }
  948. }
  949. if (count != newykeys) {
  950. (void) fprintf(table->out,
  951. "Error in finding newykeys\toldykeys = %d\tnewykeys = %d\tactual = %d\n",
  952. oldykeys,newykeys,count);
  953. }
  954. if (idcheck != 0)
  955. (void) fprintf(table->out,
  956. "Error in id's of ylist\twrong id's = %d\n",
  957. idcheck);
  958. count = 0;
  959. idcheck = 0;
  960. for (i = 0; i < xslots; i++) {
  961. f = xlist[i];
  962. while (f != sentinel) {
  963. count++;
  964. if (f->index != (DdHalfWord) xindex)
  965. idcheck++;
  966. f = f->next;
  967. }
  968. }
  969. if (count != newxkeys) {
  970. (void) fprintf(table->out,
  971. "Error in finding newxkeys\toldxkeys = %d \tnewxkeys = %d \tactual = %d\n",
  972. oldxkeys,newxkeys,count);
  973. }
  974. if (idcheck != 0)
  975. (void) fprintf(table->out,
  976. "Error in id's of xlist\twrong id's = %d\n",
  977. idcheck);
  978. #endif
  979. isolated += (table->vars[xindex]->ref == 1) +
  980. (table->vars[yindex]->ref == 1);
  981. table->isolated += (unsigned int) isolated;
  982. }
  983. /* Set the appropriate fields in table. */
  984. table->subtables[x].nodelist = ylist;
  985. table->subtables[x].slots = yslots;
  986. table->subtables[x].shift = yshift;
  987. table->subtables[x].keys = newykeys;
  988. table->subtables[x].maxKeys = yslots * DD_MAX_SUBTABLE_DENSITY;
  989. i = table->subtables[x].bindVar;
  990. table->subtables[x].bindVar = table->subtables[y].bindVar;
  991. table->subtables[y].bindVar = i;
  992. /* Adjust fields for lazy sifting. */
  993. varType = table->subtables[x].varType;
  994. table->subtables[x].varType = table->subtables[y].varType;
  995. table->subtables[y].varType = varType;
  996. i = table->subtables[x].pairIndex;
  997. table->subtables[x].pairIndex = table->subtables[y].pairIndex;
  998. table->subtables[y].pairIndex = i;
  999. i = table->subtables[x].varHandled;
  1000. table->subtables[x].varHandled = table->subtables[y].varHandled;
  1001. table->subtables[y].varHandled = i;
  1002. groupType = table->subtables[x].varToBeGrouped;
  1003. table->subtables[x].varToBeGrouped = table->subtables[y].varToBeGrouped;
  1004. table->subtables[y].varToBeGrouped = groupType;
  1005. table->subtables[y].nodelist = xlist;
  1006. table->subtables[y].slots = xslots;
  1007. table->subtables[y].shift = xshift;
  1008. table->subtables[y].keys = newxkeys;
  1009. table->subtables[y].maxKeys = xslots * DD_MAX_SUBTABLE_DENSITY;
  1010. table->perm[xindex] = y; table->perm[yindex] = x;
  1011. table->invperm[x] = yindex; table->invperm[y] = xindex;
  1012. table->keys += newxkeys + newykeys - oldxkeys - oldykeys;
  1013. return((int)(table->keys - table->isolated));
  1014. cuddSwapOutOfMem:
  1015. (void) fprintf(table->err,"Error: cuddSwapInPlace out of memory\n");
  1016. return (0);
  1017. } /* end of cuddSwapInPlace */
  1018. /**
  1019. @brief Reorders %BDD variables according to the order of the %ZDD
  1020. variables.
  1021. @details This function can be called at the end of %ZDD
  1022. reordering to insure that the order of the %BDD variables is
  1023. consistent with the order of the %ZDD variables. The number of %ZDD
  1024. variables must be a multiple of the number of %BDD variables. Let
  1025. <code>M</code> be the ratio of the two numbers. cuddBddAlignToZdd
  1026. then considers the %ZDD variables from <code>M*i</code> to
  1027. <code>(M+1)*i-1</code> as corresponding to %BDD variable
  1028. <code>i</code>. This function should be normally called from
  1029. Cudd_zddReduceHeap, which clears the cache.
  1030. @return 1 in case of success; 0 otherwise.
  1031. @sideeffect Changes the %BDD variable order for all diagrams and performs
  1032. garbage collection of the %BDD unique table.
  1033. @see Cudd_ShuffleHeap Cudd_zddReduceHeap
  1034. */
  1035. int
  1036. cuddBddAlignToZdd(
  1037. DdManager * table /**< %DD manager */)
  1038. {
  1039. int *invperm; /* permutation array */
  1040. int M; /* ratio of ZDD variables to BDD variables */
  1041. int i; /* loop index */
  1042. int result; /* return value */
  1043. /* We assume that a ratio of 0 is OK. */
  1044. if (table->size == 0)
  1045. return(1);
  1046. M = table->sizeZ / table->size;
  1047. /* Check whether the number of ZDD variables is a multiple of the
  1048. ** number of BDD variables.
  1049. */
  1050. if (M * table->size != table->sizeZ)
  1051. return(0);
  1052. /* Create and initialize the inverse permutation array. */
  1053. invperm = ALLOC(int,table->size);
  1054. if (invperm == NULL) {
  1055. table->errorCode = CUDD_MEMORY_OUT;
  1056. return(0);
  1057. }
  1058. for (i = 0; i < table->sizeZ; i += M) {
  1059. int indexZ = table->invpermZ[i];
  1060. int index = indexZ / M;
  1061. invperm[i / M] = index;
  1062. }
  1063. /* Eliminate dead nodes. Do not scan the cache again, because we
  1064. ** assume that Cudd_zddReduceHeap has already cleared it.
  1065. */
  1066. cuddGarbageCollect(table,0);
  1067. /* Initialize number of isolated projection functions. */
  1068. table->isolated = 0;
  1069. for (i = 0; i < table->size; i++) {
  1070. if (table->vars[i]->ref == 1) table->isolated++;
  1071. }
  1072. /* Initialize the interaction matrix. */
  1073. result = cuddInitInteract(table);
  1074. if (result == 0) return(0);
  1075. result = ddShuffle(table, invperm);
  1076. FREE(invperm);
  1077. /* Free interaction matrix. */
  1078. FREE(table->interact);
  1079. /* Fix the BDD variable group tree. */
  1080. bddFixTree(table,table->tree);
  1081. return(result);
  1082. } /* end of cuddBddAlignToZdd */
  1083. /*---------------------------------------------------------------------------*/
  1084. /* Definition of static functions */
  1085. /*---------------------------------------------------------------------------*/
  1086. /**
  1087. @brief Comparison function used by qsort.
  1088. @details Used to order the variables according to the number of keys
  1089. in the subtables.
  1090. @return the difference in number of keys between the two variables
  1091. being compared.
  1092. @sideeffect None
  1093. */
  1094. static int
  1095. ddUniqueCompare(
  1096. void const * ptrX,
  1097. void const * ptrY)
  1098. {
  1099. IndexKey const * pX = (IndexKey const *) ptrX;
  1100. IndexKey const * pY = (IndexKey const *) ptrY;
  1101. #if 0
  1102. /* This would make the order stable, which would be good because of
  1103. * it would platform-independent, but instability often produces
  1104. * smaller BDDs.
  1105. */
  1106. if (pY->keys == pX->keys) {
  1107. return(pX->index - pY->index);
  1108. }
  1109. #endif
  1110. return(pY->keys - pX->keys);
  1111. } /* end of ddUniqueCompare */
  1112. /**
  1113. @brief Swaps any two variables.
  1114. @return the set of moves.
  1115. @sideeffect None
  1116. */
  1117. static Move *
  1118. ddSwapAny(
  1119. DdManager * table,
  1120. int x,
  1121. int y)
  1122. {
  1123. Move *move, *moves;
  1124. int xRef,yRef;
  1125. int xNext,yNext;
  1126. int size;
  1127. int limitSize;
  1128. int tmp;
  1129. if (x >y) {
  1130. tmp = x; x = y; y = tmp;
  1131. }
  1132. xRef = x; yRef = y;
  1133. xNext = cuddNextHigh(table,x);
  1134. yNext = cuddNextLow(table,y);
  1135. moves = NULL;
  1136. limitSize = (int) (table->keys - table->isolated);
  1137. for (;;) {
  1138. if ( xNext == yNext) {
  1139. size = cuddSwapInPlace(table,x,xNext);
  1140. if (size == 0) goto ddSwapAnyOutOfMem;
  1141. move = (Move *) cuddDynamicAllocNode(table);
  1142. if (move == NULL) goto ddSwapAnyOutOfMem;
  1143. move->x = x;
  1144. move->y = xNext;
  1145. move->size = size;
  1146. move->next = moves;
  1147. moves = move;
  1148. size = cuddSwapInPlace(table,yNext,y);
  1149. if (size == 0) goto ddSwapAnyOutOfMem;
  1150. move = (Move *) cuddDynamicAllocNode(table);
  1151. if (move == NULL) goto ddSwapAnyOutOfMem;
  1152. move->x = yNext;
  1153. move->y = y;
  1154. move->size = size;
  1155. move->next = moves;
  1156. moves = move;
  1157. size = cuddSwapInPlace(table,x,xNext);
  1158. if (size == 0) goto ddSwapAnyOutOfMem;
  1159. move = (Move *) cuddDynamicAllocNode(table);
  1160. if (move == NULL) goto ddSwapAnyOutOfMem;
  1161. move->x = x;
  1162. move->y = xNext;
  1163. move->size = size;
  1164. move->next = moves;
  1165. moves = move;
  1166. tmp = x; x = y; y = tmp;
  1167. } else if (x == yNext) {
  1168. size = cuddSwapInPlace(table,x,xNext);
  1169. if (size == 0) goto ddSwapAnyOutOfMem;
  1170. move = (Move *) cuddDynamicAllocNode(table);
  1171. if (move == NULL) goto ddSwapAnyOutOfMem;
  1172. move->x = x;
  1173. move->y = xNext;
  1174. move->size = size;
  1175. move->next = moves;
  1176. moves = move;
  1177. tmp = x; x = y; y = tmp;
  1178. } else {
  1179. size = cuddSwapInPlace(table,x,xNext);
  1180. if (size == 0) goto ddSwapAnyOutOfMem;
  1181. move = (Move *) cuddDynamicAllocNode(table);
  1182. if (move == NULL) goto ddSwapAnyOutOfMem;
  1183. move->x = x;
  1184. move->y = xNext;
  1185. move->size = size;
  1186. move->next = moves;
  1187. moves = move;
  1188. size = cuddSwapInPlace(table,yNext,y);
  1189. if (size == 0) goto ddSwapAnyOutOfMem;
  1190. move = (Move *) cuddDynamicAllocNode(table);
  1191. if (move == NULL) goto ddSwapAnyOutOfMem;
  1192. move->x = yNext;
  1193. move->y = y;
  1194. move->size = size;
  1195. move->next = moves;
  1196. moves = move;
  1197. x = xNext;
  1198. y = yNext;
  1199. }
  1200. xNext = cuddNextHigh(table,x);
  1201. yNext = cuddNextLow(table,y);
  1202. if (xNext > yRef) break;
  1203. if ((double) size > table->maxGrowth * (double) limitSize) break;
  1204. if (size < limitSize) limitSize = size;
  1205. }
  1206. if (yNext>=xRef) {
  1207. size = cuddSwapInPlace(table,yNext,y);
  1208. if (size == 0) goto ddSwapAnyOutOfMem;
  1209. move = (Move *) cuddDynamicAllocNode(table);
  1210. if (move == NULL) goto ddSwapAnyOutOfMem;
  1211. move->x = yNext;
  1212. move->y = y;
  1213. move->size = size;
  1214. move->next = moves;
  1215. moves = move;
  1216. }
  1217. return(moves);
  1218. ddSwapAnyOutOfMem:
  1219. while (moves != NULL) {
  1220. move = moves->next;
  1221. cuddDeallocMove(table, moves);
  1222. moves = move;
  1223. }
  1224. return(NULL);
  1225. } /* end of ddSwapAny */
  1226. /**
  1227. @brief Given xLow <= x <= xHigh moves x up and down between the
  1228. boundaries.
  1229. @details Finds the best position and does the required changes.
  1230. @return 1 if successful; 0 otherwise.
  1231. @sideeffect None
  1232. */
  1233. static int
  1234. ddSiftingAux(
  1235. DdManager * table,
  1236. int x,
  1237. int xLow,
  1238. int xHigh)
  1239. {
  1240. Move *move;
  1241. Move *moveUp; /* list of up moves */
  1242. Move *moveDown; /* list of down moves */
  1243. int initialSize;
  1244. int result;
  1245. initialSize = (int) (table->keys - table->isolated);
  1246. moveDown = NULL;
  1247. moveUp = NULL;
  1248. if (x == xLow) {
  1249. moveDown = ddSiftingDown(table,x,xHigh);
  1250. /* At this point x --> xHigh unless bounding occurred. */
  1251. if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1252. /* Move backward and stop at best position. */
  1253. result = ddSiftingBackward(table,initialSize,moveDown);
  1254. if (!result) goto ddSiftingAuxOutOfMem;
  1255. } else if (x == xHigh) {
  1256. moveUp = ddSiftingUp(table,x,xLow);
  1257. /* At this point x --> xLow unless bounding occurred. */
  1258. if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1259. /* Move backward and stop at best position. */
  1260. result = ddSiftingBackward(table,initialSize,moveUp);
  1261. if (!result) goto ddSiftingAuxOutOfMem;
  1262. } else if ((x - xLow) > (xHigh - x)) { /* must go down first: shorter */
  1263. moveDown = ddSiftingDown(table,x,xHigh);
  1264. /* At this point x --> xHigh unless bounding occurred. */
  1265. if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1266. if (moveDown != NULL) {
  1267. x = moveDown->y;
  1268. }
  1269. moveUp = ddSiftingUp(table,x,xLow);
  1270. if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1271. /* Move backward and stop at best position */
  1272. result = ddSiftingBackward(table,initialSize,moveUp);
  1273. if (!result) goto ddSiftingAuxOutOfMem;
  1274. } else { /* must go up first: shorter */
  1275. moveUp = ddSiftingUp(table,x,xLow);
  1276. /* At this point x --> xLow unless bounding occurred. */
  1277. if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1278. if (moveUp != NULL) {
  1279. x = moveUp->x;
  1280. }
  1281. moveDown = ddSiftingDown(table,x,xHigh);
  1282. if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
  1283. /* Move backward and stop at best position. */
  1284. result = ddSiftingBackward(table,initialSize,moveDown);
  1285. if (!result) goto ddSiftingAuxOutOfMem;
  1286. }
  1287. while (moveDown != NULL) {
  1288. move = moveDown->next;
  1289. cuddDeallocMove(table, moveDown);
  1290. moveDown = move;
  1291. }
  1292. while (moveUp != NULL) {
  1293. move = moveUp->next;
  1294. cuddDeallocMove(table, moveUp);
  1295. moveUp = move;
  1296. }
  1297. return(1);
  1298. ddSiftingAuxOutOfMem:
  1299. if (moveDown != (Move *) CUDD_OUT_OF_MEM) {
  1300. while (moveDown != NULL) {
  1301. move = moveDown->next;
  1302. cuddDeallocMove(table, moveDown);
  1303. moveDown = move;
  1304. }
  1305. }
  1306. if (moveUp != (Move *) CUDD_OUT_OF_MEM) {
  1307. while (moveUp != NULL) {
  1308. move = moveUp->next;
  1309. cuddDeallocMove(table, moveUp);
  1310. moveUp = move;
  1311. }
  1312. }
  1313. return(0);
  1314. } /* end of ddSiftingAux */
  1315. /**
  1316. @brief Sifts a variable up.
  1317. @details Moves y up until either it reaches the bound (xLow) or the
  1318. size of the %DD heap increases too much.
  1319. @return the set of moves in case of success; NULL if memory is full.
  1320. @sideeffect None
  1321. */
  1322. static Move *
  1323. ddSiftingUp(
  1324. DdManager * table,
  1325. int y,
  1326. int xLow)
  1327. {
  1328. Move *moves;
  1329. Move *move;
  1330. int x;
  1331. int size;
  1332. int limitSize;
  1333. int xindex, yindex;
  1334. int isolated;
  1335. int L; /* lower bound on DD size */
  1336. #ifdef DD_DEBUG
  1337. int checkL;
  1338. int z;
  1339. int zindex;
  1340. #endif
  1341. moves = NULL;
  1342. yindex = table->invperm[y];
  1343. /* Initialize the lower bound.
  1344. ** The part of the DD below y will not change.
  1345. ** The part of the DD above y that does not interact with y will not
  1346. ** change. The rest may vanish in the best case, except for
  1347. ** the nodes at level xLow, which will not vanish, regardless.
  1348. */
  1349. limitSize = L = (int) (table->keys - table->isolated);
  1350. for (x = xLow + 1; x < y; x++) {
  1351. xindex = table->invperm[x];
  1352. if (cuddTestInteract(table,xindex,yindex)) {
  1353. isolated = table->vars[xindex]->ref == 1;
  1354. L -= table->subtables[x].keys - isolated;
  1355. }
  1356. }
  1357. isolated = table->vars[yindex]->ref == 1;
  1358. L -= (int) table->subtables[y].keys - isolated;
  1359. x = cuddNextLow(table,y);
  1360. while (x >= xLow && L <= limitSize) {
  1361. xindex = table->invperm[x];
  1362. #ifdef DD_DEBUG
  1363. checkL = (int) (table->keys - table->isolated);
  1364. for (z = xLow + 1; z < y; z++) {
  1365. zindex = table->invperm[z];
  1366. if (cuddTestInteract(table,zindex,yindex)) {
  1367. isolated = table->vars[zindex]->ref == 1;
  1368. checkL -= (int) table->subtables[z].keys - isolated;
  1369. }
  1370. }
  1371. isolated = table->vars[yindex]->ref == 1;
  1372. checkL -= (int) table->subtables[y].keys - isolated;
  1373. assert(L == checkL);
  1374. #endif
  1375. size = cuddSwapInPlace(table,x,y);
  1376. if (size == 0) goto ddSiftingUpOutOfMem;
  1377. /* Update the lower bound. */
  1378. if (cuddTestInteract(table,xindex,yindex)) {
  1379. isolated = table->vars[xindex]->ref == 1;
  1380. L += (int) table->subtables[y].keys - isolated;
  1381. }
  1382. move = (Move *) cuddDynamicAllocNode(table);
  1383. if (move == NULL) goto ddSiftingUpOutOfMem;
  1384. move->x = x;
  1385. move->y = y;
  1386. move->size = size;
  1387. move->next = moves;
  1388. moves = move;
  1389. if ((double) size > (double) limitSize * table->maxGrowth) break;
  1390. if (size < limitSize) limitSize = size;
  1391. y = x;
  1392. x = cuddNextLow(table,y);
  1393. }
  1394. return(moves);
  1395. ddSiftingUpOutOfMem:
  1396. while (moves != NULL) {
  1397. move = moves->next;
  1398. cuddDeallocMove(table, moves);
  1399. moves = move;
  1400. }
  1401. return((Move *) CUDD_OUT_OF_MEM);
  1402. } /* end of ddSiftingUp */
  1403. /**
  1404. @brief Sifts a variable down.
  1405. @details Moves x down until either it reaches the bound (xHigh) or
  1406. the size of the %DD heap increases too much.
  1407. @return the set of moves in case of success; NULL if memory is full.
  1408. @sideeffect None
  1409. */
  1410. static Move *
  1411. ddSiftingDown(
  1412. DdManager * table,
  1413. int x,
  1414. int xHigh)
  1415. {
  1416. Move *moves;
  1417. Move *move;
  1418. int y;
  1419. int size;
  1420. int R; /* upper bound on node decrease */
  1421. int limitSize;
  1422. int xindex, yindex;
  1423. int isolated;
  1424. #ifdef DD_DEBUG
  1425. int checkR;
  1426. int z;
  1427. int zindex;
  1428. #endif
  1429. moves = NULL;
  1430. /* Initialize R */
  1431. xindex = table->invperm[x];
  1432. limitSize = size = (int) (table->keys - table->isolated);
  1433. R = 0;
  1434. for (y = xHigh; y > x; y--) {
  1435. yindex = table->invperm[y];
  1436. if (cuddTestInteract(table,xindex,yindex)) {
  1437. isolated = table->vars[yindex]->ref == 1;
  1438. R += (int) table->subtables[y].keys - isolated;
  1439. }
  1440. }
  1441. y = cuddNextHigh(table,x);
  1442. while (y <= xHigh && size - R < limitSize) {
  1443. #ifdef DD_DEBUG
  1444. checkR = 0;
  1445. for (z = xHigh; z > x; z--) {
  1446. zindex = table->invperm[z];
  1447. if (cuddTestInteract(table,xindex,zindex)) {
  1448. isolated = table->vars[zindex]->ref == 1;
  1449. checkR += (int) table->subtables[z].keys - isolated;
  1450. }
  1451. }
  1452. assert(R == checkR);
  1453. #endif
  1454. /* Update upper bound on node decrease. */
  1455. yindex = table->invperm[y];
  1456. if (cuddTestInteract(table,xindex,yindex)) {
  1457. isolated = table->vars[yindex]->ref == 1;
  1458. R -= (int) table->subtables[y].keys - isolated;
  1459. }
  1460. size = cuddSwapInPlace(table,x,y);
  1461. if (size == 0) goto ddSiftingDownOutOfMem;
  1462. move = (Move *) cuddDynamicAllocNode(table);
  1463. if (move == NULL) goto ddSiftingDownOutOfMem;
  1464. move->x = x;
  1465. move->y = y;
  1466. move->size = size;
  1467. move->next = moves;
  1468. moves = move;
  1469. if ((double) size > (double) limitSize * table->maxGrowth) break;
  1470. if (size < limitSize) limitSize = size;
  1471. x = y;
  1472. y = cuddNextHigh(table,x);
  1473. }
  1474. return(moves);
  1475. ddSiftingDownOutOfMem:
  1476. while (moves != NULL) {
  1477. move = moves->next;
  1478. cuddDeallocMove(table, moves);
  1479. moves = move;
  1480. }
  1481. return((Move *) CUDD_OUT_OF_MEM);
  1482. } /* end of ddSiftingDown */
  1483. /**
  1484. @brief Given a set of moves, returns the %DD heap to the position
  1485. giving the minimum size.
  1486. @details In case of ties, returns to the closest position giving the
  1487. minimum size.
  1488. @return 1 in case of success; 0 otherwise.
  1489. @sideeffect None
  1490. */
  1491. static int
  1492. ddSiftingBackward(
  1493. DdManager * table,
  1494. int size,
  1495. Move * moves)
  1496. {
  1497. Move *move;
  1498. int res;
  1499. for (move = moves; move != NULL; move = move->next) {
  1500. if (move->size < size) {
  1501. size = move->size;
  1502. }
  1503. }
  1504. for (move = moves; move != NULL; move = move->next) {
  1505. if (move->size == size) return(1);
  1506. res = cuddSwapInPlace(table,(int)move->x,(int)move->y);
  1507. if (!res) return(0);
  1508. }
  1509. return(1);
  1510. } /* end of ddSiftingBackward */
  1511. /**
  1512. @brief Prepares the %DD heap for dynamic reordering.
  1513. @details Does garbage collection, to guarantee that there are no
  1514. dead nodes; clears the cache, which is invalidated by dynamic
  1515. reordering; initializes the number of isolated projection functions;
  1516. and initializes the interaction matrix.
  1517. @return 1 in case of success; 0 otherwise.
  1518. @sideeffect None
  1519. */
  1520. static int
  1521. ddReorderPreprocess(
  1522. DdManager * table)
  1523. {
  1524. int i;
  1525. int res;
  1526. /* Clear the cache. */
  1527. cuddCacheFlush(table);
  1528. cuddLocalCacheClearAll(table);
  1529. /* Eliminate dead nodes. Do not scan the cache again. */
  1530. cuddGarbageCollect(table,0);
  1531. /* Initialize number of isolated projection functions. */
  1532. table->isolated = 0;
  1533. for (i = 0; i < table->size; i++) {
  1534. if (table->vars[i]->ref == 1) table->isolated++;
  1535. }
  1536. /* Initialize the interaction matrix. */
  1537. res = cuddInitInteract(table);
  1538. if (res == 0) return(0);
  1539. return(1);
  1540. } /* end of ddReorderPreprocess */
  1541. /**
  1542. @brief Cleans up at the end of reordering.
  1543. @sideeffect None
  1544. */
  1545. static int
  1546. ddReorderPostprocess(
  1547. DdManager * table)
  1548. {
  1549. #ifdef DD_VERBOSE
  1550. (void) fflush(table->out);
  1551. #endif
  1552. /* Free interaction matrix. */
  1553. FREE(table->interact);
  1554. return(1);
  1555. } /* end of ddReorderPostprocess */
  1556. /**
  1557. @brief Reorders variables according to a given permutation.
  1558. @details The i-th permutation array contains the index of the
  1559. variable that should be brought to the i-th level. ddShuffle assumes
  1560. that no dead nodes are present and that the interaction matrix is
  1561. properly initialized. The reordering is achieved by a series of
  1562. upward sifts.
  1563. @return 1 if successful; 0 otherwise.
  1564. @sideeffect None
  1565. */
  1566. static int
  1567. ddShuffle(
  1568. DdManager * table,
  1569. int * permutation)
  1570. {
  1571. int index;
  1572. int level;
  1573. int position;
  1574. int numvars;
  1575. int result;
  1576. #ifdef DD_STATS
  1577. unsigned long localTime;
  1578. int initialSize;
  1579. int finalSize;
  1580. int previousSize;
  1581. #endif
  1582. table->ddTotalNumberSwapping = 0;
  1583. #ifdef DD_STATS
  1584. localTime = util_cpu_time();
  1585. initialSize = table->keys - table->isolated;
  1586. (void) fprintf(table->out,"#:I_SHUFFLE %8d: initial size\n",
  1587. initialSize);
  1588. table->totalNISwaps = 0;
  1589. #endif
  1590. numvars = table->size;
  1591. for (level = 0; level < numvars; level++) {
  1592. index = permutation[level];
  1593. position = table->perm[index];
  1594. #ifdef DD_STATS
  1595. previousSize = table->keys - table->isolated;
  1596. #endif
  1597. result = ddSiftUp(table,position,level);
  1598. if (!result) return(0);
  1599. #ifdef DD_STATS
  1600. if (table->keys < (unsigned) previousSize + table->isolated) {
  1601. (void) fprintf(table->out,"-");
  1602. } else if (table->keys > (unsigned) previousSize + table->isolated) {
  1603. (void) fprintf(table->out,"+"); /* should never happen */
  1604. } else {
  1605. (void) fprintf(table->out,"=");
  1606. }
  1607. fflush(table->out);
  1608. #endif
  1609. }
  1610. #ifdef DD_STATS
  1611. (void) fprintf(table->out,"\n");
  1612. finalSize = table->keys - table->isolated;
  1613. (void) fprintf(table->out,"#:F_SHUFFLE %8d: final size\n",finalSize);
  1614. (void) fprintf(table->out,"#:T_SHUFFLE %8g: total time (sec)\n",
  1615. ((double)(util_cpu_time() - localTime)/1000.0));
  1616. (void) fprintf(table->out,"#:N_SHUFFLE %8d: total swaps\n",
  1617. table->ddTotalNumberSwapping);
  1618. (void) fprintf(table->out,"#:M_SHUFFLE %8d: NI swaps\n",
  1619. table->totalNISwaps);
  1620. #endif
  1621. return(1);
  1622. } /* end of ddShuffle */
  1623. /**
  1624. @brief Moves one variable up.
  1625. @details Takes a variable from position x and sifts it up to
  1626. position xLow; xLow should be less than or equal to x.
  1627. @return 1 if successful; 0 otherwise
  1628. @sideeffect None
  1629. */
  1630. static int
  1631. ddSiftUp(
  1632. DdManager * table,
  1633. int x,
  1634. int xLow)
  1635. {
  1636. int y;
  1637. int size;
  1638. y = cuddNextLow(table,x);
  1639. while (y >= xLow) {
  1640. size = cuddSwapInPlace(table,y,x);
  1641. if (size == 0) {
  1642. return(0);
  1643. }
  1644. x = y;
  1645. y = cuddNextLow(table,x);
  1646. }
  1647. return(1);
  1648. } /* end of ddSiftUp */
  1649. /**
  1650. @brief Fixes the %BDD variable group tree after a shuffle.
  1651. @details Assumes that the order of the variables in a terminal node
  1652. has not been changed.
  1653. @sideeffect Changes the %BDD variable group tree.
  1654. */
  1655. static void
  1656. bddFixTree(
  1657. DdManager * table,
  1658. MtrNode * treenode)
  1659. {
  1660. if (treenode == NULL) return;
  1661. treenode->low = ((int) treenode->index < table->size) ?
  1662. (MtrHalfWord) table->perm[treenode->index] : treenode->index;
  1663. if (treenode->child != NULL) {
  1664. bddFixTree(table, treenode->child);
  1665. }
  1666. if (treenode->younger != NULL)
  1667. bddFixTree(table, treenode->younger);
  1668. if (treenode->parent != NULL && treenode->low < treenode->parent->low) {
  1669. treenode->parent->low = treenode->low;
  1670. treenode->parent->index = treenode->index;
  1671. }
  1672. return;
  1673. } /* end of bddFixTree */
  1674. /**
  1675. @brief Updates the %BDD variable group tree before a shuffle.
  1676. @return 1 if successful; 0 otherwise.
  1677. @sideeffect Changes the %BDD variable group tree.
  1678. */
  1679. static int
  1680. ddUpdateMtrTree(
  1681. DdManager * table,
  1682. MtrNode * treenode,
  1683. int * perm,
  1684. int * invperm)
  1685. {
  1686. unsigned int i, size;
  1687. int index, level, minLevel, maxLevel, minIndex;
  1688. if (treenode == NULL) return(1);
  1689. minLevel = CUDD_MAXINDEX;
  1690. maxLevel = 0;
  1691. minIndex = -1;
  1692. /* i : level */
  1693. for (i = treenode->low; i < treenode->low + treenode->size; i++) {
  1694. index = table->invperm[i];
  1695. level = perm[index];
  1696. if (level < minLevel) {
  1697. minLevel = level;
  1698. minIndex = index;
  1699. }
  1700. if (level > maxLevel)
  1701. maxLevel = level;
  1702. }
  1703. size = maxLevel - minLevel + 1;
  1704. if (minIndex == -1) return(0);
  1705. if (size == treenode->size) {
  1706. treenode->low = minLevel;
  1707. treenode->index = minIndex;
  1708. } else {
  1709. return(0);
  1710. }
  1711. if (treenode->child != NULL) {
  1712. if (!ddUpdateMtrTree(table, treenode->child, perm, invperm))
  1713. return(0);
  1714. }
  1715. if (treenode->younger != NULL) {
  1716. if (!ddUpdateMtrTree(table, treenode->younger, perm, invperm))
  1717. return(0);
  1718. }
  1719. return(1);
  1720. }
  1721. /**
  1722. @brief Checks the %BDD variable group tree before a shuffle.
  1723. @return 1 if successful; 0 otherwise.
  1724. @sideeffect Changes the %BDD variable group tree.
  1725. */
  1726. static int
  1727. ddCheckPermuation(
  1728. DdManager * table,
  1729. MtrNode * treenode,
  1730. int * perm,
  1731. int * invperm)
  1732. {
  1733. unsigned int i, size;
  1734. int index, level, minLevel, maxLevel;
  1735. if (treenode == NULL) return(1);
  1736. minLevel = table->size;
  1737. maxLevel = 0;
  1738. /* i : level */
  1739. for (i = treenode->low; i < treenode->low + treenode->size; i++) {
  1740. index = table->invperm[i];
  1741. level = perm[index];
  1742. if (level < minLevel)
  1743. minLevel = level;
  1744. if (level > maxLevel)
  1745. maxLevel = level;
  1746. }
  1747. size = maxLevel - minLevel + 1;
  1748. if (size != treenode->size)
  1749. return(0);
  1750. if (treenode->child != NULL) {
  1751. if (!ddCheckPermuation(table, treenode->child, perm, invperm))
  1752. return(0);
  1753. }
  1754. if (treenode->younger != NULL) {
  1755. if (!ddCheckPermuation(table, treenode->younger, perm, invperm))
  1756. return(0);
  1757. }
  1758. return(1);
  1759. }