abcExact.c 108 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/**CFile****************************************************************

  FileName    [abcExact.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Network and node package.]

  Synopsis    [Find minimum size networks with a SAT solver.]

  Author      [Mathias Soeken]

  Affiliation [EPFL]

  Date        [Ver. 1.0. Started - July 15, 2016.]

  Revision    [$Id: abcFanio.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]

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

/* This implementation is based on Exercises 477 and 478 in
 * Donald E. Knuth TAOCP Fascicle 6 (Satisfiability) Section 7.2.2.2
 */

#include "base/abc/abc.h"

27
#include "aig/gia/gia.h"
28 29 30
#include "misc/util/utilTruth.h"
#include "misc/vec/vecInt.h"
#include "misc/vec/vecPtr.h"
31
#include "proof/cec/cec.h"
32 33 34 35 36 37 38 39 40
#include "sat/bsat/satSolver.h"

ABC_NAMESPACE_IMPL_START


////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

Mathias Soeken committed
41 42 43 44 45 46
/***********************************************************************

  Synopsis    [Some truth table helper functions.]

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

47 48 49 50 51 52 53 54 55 56 57
static word s_Truths8[32] = {
    ABC_CONST(0xAAAAAAAAAAAAAAAA), ABC_CONST(0xAAAAAAAAAAAAAAAA), ABC_CONST(0xAAAAAAAAAAAAAAAA), ABC_CONST(0xAAAAAAAAAAAAAAAA),
    ABC_CONST(0xCCCCCCCCCCCCCCCC), ABC_CONST(0xCCCCCCCCCCCCCCCC), ABC_CONST(0xCCCCCCCCCCCCCCCC), ABC_CONST(0xCCCCCCCCCCCCCCCC),
    ABC_CONST(0xF0F0F0F0F0F0F0F0), ABC_CONST(0xF0F0F0F0F0F0F0F0), ABC_CONST(0xF0F0F0F0F0F0F0F0), ABC_CONST(0xF0F0F0F0F0F0F0F0),
    ABC_CONST(0xFF00FF00FF00FF00), ABC_CONST(0xFF00FF00FF00FF00), ABC_CONST(0xFF00FF00FF00FF00), ABC_CONST(0xFF00FF00FF00FF00),
    ABC_CONST(0xFFFF0000FFFF0000), ABC_CONST(0xFFFF0000FFFF0000), ABC_CONST(0xFFFF0000FFFF0000), ABC_CONST(0xFFFF0000FFFF0000),
    ABC_CONST(0xFFFFFFFF00000000), ABC_CONST(0xFFFFFFFF00000000), ABC_CONST(0xFFFFFFFF00000000), ABC_CONST(0xFFFFFFFF00000000),
    ABC_CONST(0x0000000000000000), ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0x0000000000000000), ABC_CONST(0xFFFFFFFFFFFFFFFF),
    ABC_CONST(0x0000000000000000), ABC_CONST(0x0000000000000000), ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0xFFFFFFFFFFFFFFFF)
};

Mathias Soeken committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
static word s_Truths8Neg[32] = {
    ABC_CONST(0x5555555555555555), ABC_CONST(0x5555555555555555), ABC_CONST(0x5555555555555555), ABC_CONST(0x5555555555555555),
    ABC_CONST(0x3333333333333333), ABC_CONST(0x3333333333333333), ABC_CONST(0x3333333333333333), ABC_CONST(0x3333333333333333),
    ABC_CONST(0x0F0F0F0F0F0F0F0F), ABC_CONST(0x0F0F0F0F0F0F0F0F), ABC_CONST(0x0F0F0F0F0F0F0F0F), ABC_CONST(0x0F0F0F0F0F0F0F0F),
    ABC_CONST(0x00FF00FF00FF00FF), ABC_CONST(0x00FF00FF00FF00FF), ABC_CONST(0x00FF00FF00FF00FF), ABC_CONST(0x00FF00FF00FF00FF),
    ABC_CONST(0x0000FFFF0000FFFF), ABC_CONST(0x0000FFFF0000FFFF), ABC_CONST(0x0000FFFF0000FFFF), ABC_CONST(0x0000FFFF0000FFFF),
    ABC_CONST(0x00000000FFFFFFFF), ABC_CONST(0x00000000FFFFFFFF), ABC_CONST(0x00000000FFFFFFFF), ABC_CONST(0x00000000FFFFFFFF),
    ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0x0000000000000000), ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0x0000000000000000),
    ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0xFFFFFFFFFFFFFFFF), ABC_CONST(0x0000000000000000), ABC_CONST(0x0000000000000000)
};

static int Abc_TtIsSubsetWithMask( word * pSmall, word * pLarge, word * pMask, int nWords )
{
    int w;
    for ( w = 0; w < nWords; ++w )
        if ( ( pSmall[w] & pLarge[w] & pMask[w] ) != ( pSmall[w] & pMask[w] ) )
            return 0;
    return 1;
}

Mathias Soeken committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
static int Abc_TtCofsOppositeWithMask( word * pTruth, word * pMask, int nWords, int iVar )
{
    if ( iVar < 6 )
    {
        int w, Shift = ( 1 << iVar );
        for ( w = 0; w < nWords; ++w )
            if ( ( ( pTruth[w] << Shift ) & s_Truths6[iVar] & pMask[w] ) != ( ~pTruth[w] & s_Truths6[iVar] & pMask[w] ) )
                return 0;
        return 1;
    }
    else
    {
        int w, Step = ( 1 << ( iVar - 6 ) );
        word * p = pTruth, * m = pMask, * pLimit = pTruth + nWords;
        for ( ; p < pLimit; p += 2 * Step, m += 2 * Step )
            for ( w = 0; w < Step; ++w )
                if ( ( p[w] & m[w] ) != ( ~p[w + Step] & m[w + Step] ) )
                    return 0;
        return 1;
    }
}

Mathias Soeken committed
100 101
// checks whether we can decompose as OP(x^p, g) where OP in {AND, OR} and p in {0, 1}
// returns p if OP = AND, and 2 + p if OP = OR
Mathias Soeken committed
102
static int Abc_TtIsTopDecomposable( word * pTruth, word * pMask, int nWords, int iVar )
Mathias Soeken committed
103
{
Mathias Soeken committed
104
    assert( iVar < 8 );
Mathias Soeken committed
105

Mathias Soeken committed
106 107 108 109 110
    if ( Abc_TtIsSubsetWithMask( pTruth, &s_Truths8[iVar << 2], pMask, nWords ) ) return 1;
    if ( Abc_TtIsSubsetWithMask( pTruth, &s_Truths8Neg[iVar << 2], pMask, nWords ) ) return 2;
    if ( Abc_TtIsSubsetWithMask( &s_Truths8[iVar << 2], pTruth, pMask, nWords ) ) return 3;
    if ( Abc_TtIsSubsetWithMask( &s_Truths8Neg[iVar << 2], pTruth, pMask, nWords ) ) return 4;
    if ( Abc_TtCofsOppositeWithMask( pTruth, pMask, nWords, iVar ) ) return 5;
Mathias Soeken committed
111 112 113 114 115 116

    return 0;
}

// checks whether we can decompose as OP(x1, OP(x2, OP(x3, ...))) where pVars = {x1, x2, x3, ...}
// OP can be different and vars can be complemented
Mathias Soeken committed
117
static int Abc_TtIsStairDecomposable( word * pTruth, int nWords, int * pVars, int nSize, int * pStairFunc )
Mathias Soeken committed
118 119 120
{
    int i, d;
    word pMask[4];
Mathias Soeken committed
121
    word pCopy[4];
Mathias Soeken committed
122

Mathias Soeken committed
123
    Abc_TtCopy( pCopy, pTruth, nWords, 0 );
Mathias Soeken committed
124 125 126 127
    Abc_TtMask( pMask, nWords, nWords * 64 );

    for ( i = 0; i < nSize; ++i )
    {
Mathias Soeken committed
128 129 130 131 132
        d = Abc_TtIsTopDecomposable( pCopy, pMask, nWords, pVars[i] );
        if ( !d )
            return 0; /* not decomposable */

        pStairFunc[i] = d;
Mathias Soeken committed
133 134 135 136 137 138 139 140 141 142 143

        switch ( d )
        {
        case 1: /* AND(x, g) */
        case 4: /* OR(!x, g) */
            Abc_TtAnd( pMask, pMask, &s_Truths8[pVars[i] << 2], nWords, 0 );
            break;
        case 2: /* AND(!x, g) */
        case 3: /* OR(x, g) */
            Abc_TtAnd( pMask, pMask, &s_Truths8Neg[pVars[i] << 2], nWords, 0 );
            break;
Mathias Soeken committed
144 145 146
        case 5:
            Abc_TtXor( pCopy, pCopy, &s_Truths8[pVars[i] << 2], nWords, 0 );
            break;
Mathias Soeken committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 197 198 199 200 201 202
        }
    }

    return 1; /* decomposable */
}

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

  Synopsis    [Some printing utilities.]

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

static inline void Abc_DebugPrint( const char* str, int fCond )
{
    if ( fCond )
    {
        printf( "%s", str );
        fflush( stdout );
    }
}

static inline void Abc_DebugPrintInt( const char* fmt, int n, int fCond )
{
    if ( fCond )
    {
        printf( fmt, n );
        fflush( stdout );
    }
}

static inline void Abc_DebugPrintIntInt( const char* fmt, int n1, int n2, int fCond )
{
    if ( fCond )
    {
        printf( fmt, n1, n2 );
        fflush( stdout );
    }
}

static inline void Abc_DebugErase( int n, int fCond )
{
    int i;
    if ( fCond )
    {
        for ( i = 0; i < n; ++i )
            printf( "\b" );
        fflush( stdout );
    }
}

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

  Synopsis    [BMS.]

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

203 204 205 206
#define ABC_EXACT_SOL_NVARS  0
#define ABC_EXACT_SOL_NFUNC  1
#define ABC_EXACT_SOL_NGATES 2

Mathias Soeken committed
207 208 209 210 211 212 213 214
#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"

215 216 217
typedef struct Ses_Man_t_ Ses_Man_t;
struct Ses_Man_t_
{
Mathias Soeken committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    sat_solver * pSat;                  /* SAT solver */

    word *       pSpec;                 /* specification */
    int          bSpecInv;              /* remembers whether spec was inverted for normalization */
    int          nSpecVars;             /* number of variables in specification */
    int          nSpecFunc;             /* number of functions to synthesize */
    int          nSpecWords;            /* number of words for function */
    int          nRows;                 /* number of rows in the specification (without 0) */
    int          nMaxDepth;             /* maximum depth (-1 if depth is not constrained) */
    int          nMaxDepthTmp;          /* temporary copy to modify nMaxDepth temporarily */
    int *        pArrTimeProfile;       /* arrival times of inputs (NULL if arrival times are ignored) */
    int          pArrTimeProfileTmp[8]; /* temporary copy to modify pArrTimeProfile temporarily */
    int          nArrTimeDelta;         /* delta to the original arrival times (arrival times are normalized to have 0 as minimum element) */
    int          nArrTimeMax;           /* maximum normalized arrival time */
    int          nBTLimit;              /* conflict limit */
    int          fMakeAIG;              /* create AIG instead of general network */
    int          fVerbose;              /* be verbose */
    int          fVeryVerbose;          /* be very verbose */
    int          fExtractVerbose;       /* be verbose about solution extraction */
    int          fSatVerbose;           /* be verbose about SAT solving */
Mathias Soeken committed
238
    int          fReasonVerbose;        /* be verbose about give-up reasons */
Mathias Soeken committed
239
    word         pTtValues[4];          /* truth table values to assign */
Mathias Soeken committed
240 241
    Vec_Int_t *  vPolar;                /* variables with positive polarity */
    Vec_Int_t *  vAssump;               /* assumptions */
Mathias Soeken committed
242 243
    int          nRandRowAssigns;       /* number of random row assignments to initialize CEGAR */
    int          fKeepRowAssigns;       /* if 1, keep counter examples in CEGAR for next number of gates */
Mathias Soeken committed
244 245

    int          nGates;                /* number of gates */
Mathias Soeken committed
246
    int          nStartGates;           /* number of gates to start search (-1), i.e., to start from 1 gate, one needs to specify 0 */
Mathias Soeken committed
247
    int          nMaxGates;             /* maximum number of gates given max. delay and arrival times */
Mathias Soeken committed
248
    int          fDecStructure;         /* set to 1 or higher if nSpecFunc = 1 and f = x_i OP g(X \ {x_i}), otherwise 0 (determined when solving) */
Mathias Soeken committed
249
    int          pDecVars;              /* mask of variables that can be decomposed at top-level */
Mathias Soeken committed
250 251
    Vec_Int_t *  vStairDecVars;         /* list of stair decomposable variables */
    int          pStairDecFunc[8];      /* list of stair decomposable functions */
Mathias Soeken committed
252
    word         pTtObjs[100];          /* temporary truth tables */
Mathias Soeken committed
253 254 255 256 257 258 259

    int          nSimVars;              /* number of simulation vars x(i, t) */
    int          nOutputVars;           /* number of output variables g(h, i) */
    int          nGateVars;             /* number of gate variables f(i, p, q) */
    int          nSelectVars;           /* number of select variables s(i, j, k) */
    int          nDepthVars;            /* number of depth variables d(i, j) */

Mathias Soeken committed
260
    int          nSimOffset;            /* offset where gate variables start */
Mathias Soeken committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    int          nOutputOffset;         /* offset where output variables start */
    int          nGateOffset;           /* offset where gate variables start */
    int          nSelectOffset;         /* offset where select variables start */
    int          nDepthOffset;          /* offset where depth variables start */

    int          fHitResLimit;          /* SAT solver gave up due to resource limit */

    abctime      timeSat;               /* SAT runtime */
    abctime      timeSatSat;            /* SAT runtime (sat instance) */
    abctime      timeSatUnsat;          /* SAT runtime (unsat instance) */
    abctime      timeSatUndef;          /* SAT runtime (undef instance) */
    abctime      timeInstance;          /* creating instance runtime */
    abctime      timeTotal;             /* all runtime */

    int          nSatCalls;             /* number of SAT calls */
    int          nUnsatCalls;           /* number of UNSAT calls */
    int          nUndefCalls;           /* number of UNDEF calls */
278 279

    int          nDebugOffset;          /* for debug printing */
280 281
};

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
/***********************************************************************

  Synopsis    [Store truth tables based on normalized arrival times.]

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

// The hash table is a list of pointers to Ses_TruthEntry_t elements, which
// are arranged in a linked list, each of which pointing to a linked list
// of Ses_TimesEntry_t elements which contain the char* representation of the
// optimum netlist according to then normalized arrival times:

typedef struct Ses_TimesEntry_t_ Ses_TimesEntry_t;
struct Ses_TimesEntry_t_
{
    int                pArrTimeProfile[8]; /* normalized arrival time profile */
297
    int                fResLimit;          /* solution found after resource limit */
298 299 300 301 302 303 304 305
    Ses_TimesEntry_t * next;               /* linked list pointer */
    char *             pNetwork;           /* pointer to char array representation of optimum network */
};

typedef struct Ses_TruthEntry_t_ Ses_TruthEntry_t;
struct Ses_TruthEntry_t_
{
    word               pTruth[4]; /* truth table for comparison */
306
    int                nVars;     /* number of variables */
307 308 309 310 311 312 313 314
    Ses_TruthEntry_t * next;      /* linked list pointer */
    Ses_TimesEntry_t * head;      /* pointer to head of sub list with arrival times */
};

#define SES_STORE_TABLE_SIZE 1024
typedef struct Ses_Store_t_ Ses_Store_t;
struct Ses_Store_t_
{
315
    int                fMakeAIG;                       /* create AIG instead of general network */
316
    int                fVerbose;                       /* be verbose */
317
    int                fVeryVerbose;                   /* be very verbose */
318
    int                nBTLimit;                       /* conflict limit */
319
    int                nEntriesCount;                  /* number of entries */
320
    int                nValidEntriesCount;             /* number of entries with network */
321
    Ses_TruthEntry_t * pEntries[SES_STORE_TABLE_SIZE]; /* hash table for truth table entries */
322
    sat_solver       * pSat;                           /* own SAT solver instance to reuse when calling exact algorithm */
323
    FILE             * pDebugEntries;                  /* debug unsynth. (rl) entries */
Mathias Soeken committed
324
    char             * szDBName;                       /* if given, database is written every time a new entry is added */
325

Mathias Soeken committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    /* statistics */
    unsigned long      nCutCount;                      /* number of cuts investigated */
    unsigned long      pCutCount[9];                   /* -> per cut size */
    unsigned long      nUnsynthesizedImp;              /* number of cuts which couldn't be optimized at all, opt. stopped because of imp. constraints */
    unsigned long      pUnsynthesizedImp[9];           /* -> per cut size */
    unsigned long      nUnsynthesizedRL;               /* number of cuts which couldn't be optimized at all, opt. stopped because of resource limits */
    unsigned long      pUnsynthesizedRL[9];            /* -> per cut size */
    unsigned long      nSynthesizedTrivial;            /* number of cuts which could be synthesized trivially (n < 2) */
    unsigned long      pSynthesizedTrivial[9];         /* -> per cut size */
    unsigned long      nSynthesizedImp;                /* number of cuts which could be synthesized, opt. stopped because of imp. constraints */
    unsigned long      pSynthesizedImp[9];             /* -> per cut size */
    unsigned long      nSynthesizedRL;                 /* number of cuts which could be synthesized, opt. stopped because of resource limits */
    unsigned long      pSynthesizedRL[9];              /* -> per cut size */
    unsigned long      nCacheHits;                     /* number of cache hits */
    unsigned long      pCacheHits[9];                  /* -> per cut size */
341 342 343 344 345 346 347 348 349 350 351 352

    unsigned long      nSatCalls;                      /* number of total SAT calls */
    unsigned long      nUnsatCalls;                    /* number of total UNSAT calls */
    unsigned long      nUndefCalls;                    /* number of total UNDEF calls */

    abctime            timeExact;                      /* Exact synthesis runtime */
    abctime            timeSat;                        /* SAT runtime */
    abctime            timeSatSat;                     /* SAT runtime (sat instance) */
    abctime            timeSatUnsat;                   /* SAT runtime (unsat instance) */
    abctime            timeSatUndef;                   /* SAT runtime (undef instance) */
    abctime            timeInstance;                   /* creating instance runtime */
    abctime            timeTotal;                      /* all runtime */
353 354 355 356
};

static Ses_Store_t * s_pSesStore = NULL;

357 358 359 360
////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

361
static int Abc_NormalizeArrivalTimes( int * pArrTimeProfile, int nVars, int * maxNormalized )
362
{
363
    int * p = pArrTimeProfile, * pEnd = pArrTimeProfile + nVars;
364 365 366 367 368 369 370
    int delta = *p;

    while ( ++p < pEnd )
        if ( *p < delta )
            delta = *p;

    *maxNormalized = 0;
371
    p = pArrTimeProfile;
372 373 374 375 376 377 378 379 380 381 382 383 384
    while ( p < pEnd )
    {
        *p -= delta;
        if ( *p > *maxNormalized )
            *maxNormalized = *p;
        ++p;
    }

    *maxNormalized += 1;

    return delta;
}

385
static inline Ses_Store_t * Ses_StoreAlloc( int nBTLimit, int fMakeAIG, int fVerbose )
386 387
{
    Ses_Store_t * pStore = ABC_CALLOC( Ses_Store_t, 1 );
Mathias Soeken committed
388 389 390
    pStore->fMakeAIG           = fMakeAIG;
    pStore->fVerbose           = fVerbose;
    pStore->nBTLimit           = nBTLimit;
391
    memset( pStore->pEntries, 0, sizeof(pStore->pEntries) );
392

393 394
    pStore->pSat = sat_solver_new();

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    return pStore;
}

static inline void Ses_StoreClean( Ses_Store_t * pStore )
{
    int i;
    Ses_TruthEntry_t * pTEntry, * pTEntry2;
    Ses_TimesEntry_t * pTiEntry, * pTiEntry2;

    for ( i = 0; i < SES_STORE_TABLE_SIZE; ++i )
        if ( pStore->pEntries[i] )
        {
            pTEntry = pStore->pEntries[i];

            while ( pTEntry )
            {
                pTiEntry = pTEntry->head;
                while ( pTiEntry )
                {
                    ABC_FREE( pTiEntry->pNetwork );
                    pTiEntry2 = pTiEntry;
                    pTiEntry = pTiEntry->next;
                    ABC_FREE( pTiEntry2 );
                }
                pTEntry2 = pTEntry;
                pTEntry = pTEntry->next;
                ABC_FREE( pTEntry2 );
            }
        }

425
    sat_solver_delete( pStore->pSat );
Mathias Soeken committed
426 427 428

    if ( pStore->szDBName )
        ABC_FREE( pStore->szDBName );
429 430 431
    ABC_FREE( pStore );
}

432
static inline int Ses_StoreTableHash( word * pTruth, int nVars )
433 434 435 436
{
    static int s_Primes[4] = { 1291, 1699, 1999, 2357 };
    int i;
    unsigned uHash = 0;
437
    for ( i = 0; i < Abc_TtWordNum( nVars ); ++i )
438 439 440 441
        uHash ^= pTruth[i] * s_Primes[i & 0xf];
    return (int)(uHash % SES_STORE_TABLE_SIZE );
}

442
static inline int Ses_StoreTruthEqual( Ses_TruthEntry_t * pEntry, word * pTruth, int nVars )
443 444
{
    int i;
445 446 447 448

    if ( pEntry->nVars != nVars )
        return 0;

449
    for ( i = 0; i < Abc_TtWordNum( nVars ); ++i )
450
        if ( pEntry->pTruth[i] != pTruth[i] )
451 452 453 454
            return 0;
    return 1;
}

455
static inline void Ses_StoreTruthCopy( Ses_TruthEntry_t * pEntry, word * pTruthSrc, int nVars )
456 457
{
    int i;
458
    pEntry->nVars = nVars;
459
    for ( i = 0; i < Abc_TtWordNum( nVars ); ++i )
460
        pEntry->pTruth[i] = pTruthSrc[i];
461 462
}

463
static inline int Ses_StoreTimesEqual( int * pTimes1, int * pTimes2, int nVars )
464 465
{
    int i;
466
    for ( i = 0; i < nVars; ++i )
467 468 469 470 471
        if ( pTimes1[i] != pTimes2[i] )
            return 0;
    return 1;
}

472
static inline void Ses_StoreTimesCopy( int * pTimesDest, int * pTimesSrc, int nVars )
473 474
{
    int i;
475
    for ( i = 0; i < nVars; ++i )
476 477 478
        pTimesDest[i] = pTimesSrc[i];
}

479 480 481 482 483 484 485 486 487 488 489 490 491
static inline void Ses_StorePrintEntry( Ses_TruthEntry_t * pEntry, Ses_TimesEntry_t * pTiEntry )
{
    int i;

    printf( "f = " );
    Abc_TtPrintHexRev( stdout, pEntry->pTruth, pEntry->nVars );
    printf( ", n = %d", pEntry->nVars );
    printf( ", arrival =" );
    for ( i = 0; i < pEntry->nVars; ++i )
        printf( " %d", pTiEntry->pArrTimeProfile[i] );
    printf( "\n" );
}

Mathias Soeken committed
492
static inline void Ses_StorePrintDebugEntry( Ses_Store_t * pStore, word * pTruth, int nVars, int * pNormalArrTime, int nMaxDepth, char * pSol, int nStartGates )
493 494 495 496 497
{
    int l;

    fprintf( pStore->pDebugEntries, "abc -c \"exact -v -C %d", pStore->nBTLimit );
    if ( s_pSesStore->fMakeAIG ) fprintf( pStore->pDebugEntries, " -a" );
Mathias Soeken committed
498
    fprintf( pStore->pDebugEntries, " -S %d -D %d -A", nStartGates + 1, nMaxDepth );
499 500 501 502
    for ( l = 0; l < nVars; ++l )
        fprintf( pStore->pDebugEntries, "%c%d", ( l == 0 ? ' ' : ',' ), pNormalArrTime[l] );
    fprintf( pStore->pDebugEntries, " " );
    Abc_TtPrintHexRev( pStore->pDebugEntries, pTruth, nVars );
Mathias Soeken committed
503 504 505 506 507
    fprintf( pStore->pDebugEntries, "\" # " );

    if ( !pSol )
        fprintf( pStore->pDebugEntries, "no " );
    fprintf( pStore->pDebugEntries, "solution found before\n" );
508 509
}

Mathias Soeken committed
510 511 512 513 514 515 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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
static void Abc_ExactNormalizeArrivalTimesForNetwork( int nVars, int * pArrTimeProfile, char * pSol )
{
    int nGates, i, j, k, nMax;
    Vec_Int_t * vLevels;

    nGates = pSol[ABC_EXACT_SOL_NGATES];

    /* printf( "NORMALIZE\n" ); */
    /* printf( "  #vars  = %d\n", nVars ); */
    /* printf( "  #gates = %d\n", nGates ); */

    vLevels = Vec_IntAllocArrayCopy( pArrTimeProfile, nVars );

    /* compute level of each gate based on arrival time profile (to compute depth) */
    for ( i = 0; i < nGates; ++i )
    {
        j = pSol[3 + i * 4 + 2];
        k = pSol[3 + i * 4 + 3];

        Vec_IntPush( vLevels, Abc_MaxInt( Vec_IntEntry( vLevels, j ), Vec_IntEntry( vLevels, k ) ) + 1 );

        /* printf( "  gate %d = (%d,%d)\n", nVars + i, j, k ); */
    }

    /* Vec_IntPrint( vLevels ); */

    /* reset all levels except for the last one */
    for ( i = 0; i < nVars + nGates - 1; ++i )
        Vec_IntSetEntry( vLevels, i, Vec_IntEntry( vLevels, nVars + nGates - 1 ) );

    /* Vec_IntPrint( vLevels ); */

    /* compute levels from top to bottom */
    for ( i = nGates - 1; i >= 0; --i )
    {
        j = pSol[3 + i * 4 + 2];
        k = pSol[3 + i * 4 + 3];

        Vec_IntSetEntry( vLevels, j, Abc_MinInt( Vec_IntEntry( vLevels, j ), Vec_IntEntry( vLevels, nVars + i ) - 1 ) );
        Vec_IntSetEntry( vLevels, k, Abc_MinInt( Vec_IntEntry( vLevels, k ), Vec_IntEntry( vLevels, nVars + i ) - 1 ) );
    }

    /* Vec_IntPrint( vLevels ); */

    /* normalize arrival times */
    Abc_NormalizeArrivalTimes( Vec_IntArray( vLevels ), nVars, &nMax );
    memcpy( pArrTimeProfile, Vec_IntArray( vLevels ), sizeof(int) * nVars );

    /* printf( "  nMax = %d\n", nMax ); */
    /* Vec_IntPrint( vLevels ); */

    Vec_IntFree( vLevels );
}

Mathias Soeken committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
static void Ses_StoreWrite( Ses_Store_t * pStore, const char * pFilename, int fSynthImp, int fSynthRL, int fUnsynthImp, int fUnsynthRL )
{
    int i;
    char zero = '\0';
    unsigned long nEntries = 0;
    Ses_TruthEntry_t * pTEntry;
    Ses_TimesEntry_t * pTiEntry;
    FILE * pFile;

    pFile = fopen( pFilename, "wb" );
    if (pFile == NULL)
    {
        printf( "cannot open file \"%s\" for writing\n", pFilename );
        return;
    }

    if ( fSynthImp )   nEntries += pStore->nSynthesizedImp;
    if ( fSynthRL )    nEntries += pStore->nSynthesizedRL;
    if ( fUnsynthImp ) nEntries += pStore->nUnsynthesizedImp;
    if ( fUnsynthRL )  nEntries += pStore->nUnsynthesizedRL;
    fwrite( &nEntries, sizeof( unsigned long ), 1, pFile );

    for ( i = 0; i < SES_STORE_TABLE_SIZE; ++i )
        if ( pStore->pEntries[i] )
        {
            pTEntry = pStore->pEntries[i];

            while ( pTEntry )
            {
                pTiEntry = pTEntry->head;
                while ( pTiEntry )
                {
                    if ( !fSynthImp && pTiEntry->pNetwork && !pTiEntry->fResLimit )    { pTiEntry = pTiEntry->next; continue; }
                    if ( !fSynthRL && pTiEntry->pNetwork && pTiEntry->fResLimit )      { pTiEntry = pTiEntry->next; continue; }
                    if ( !fUnsynthImp && !pTiEntry->pNetwork && !pTiEntry->fResLimit ) { pTiEntry = pTiEntry->next; continue; }
                    if ( !fUnsynthRL && !pTiEntry->pNetwork && pTiEntry->fResLimit )   { pTiEntry = pTiEntry->next; continue; }

                    fwrite( pTEntry->pTruth, sizeof( word ), 4, pFile );
                    fwrite( &pTEntry->nVars, sizeof( int ), 1, pFile );
                    fwrite( pTiEntry->pArrTimeProfile, sizeof( int ), 8, pFile );
                    fwrite( &pTiEntry->fResLimit, sizeof( int ), 1, pFile );

                    if ( pTiEntry->pNetwork )
                    {
                        fwrite( pTiEntry->pNetwork, sizeof( char ), 3 + 4 * pTiEntry->pNetwork[ABC_EXACT_SOL_NGATES] + 2 + pTiEntry->pNetwork[ABC_EXACT_SOL_NVARS], pFile );
                    }
                    else
                    {
                        fwrite( &zero, sizeof( char ), 1, pFile );
                        fwrite( &zero, sizeof( char ), 1, pFile );
                        fwrite( &zero, sizeof( char ), 1, pFile );
                    }

                    pTiEntry = pTiEntry->next;
                }
                pTEntry = pTEntry->next;
            }
        }


    fclose( pFile );
}

627
// pArrTimeProfile is normalized
628
// returns 1 if and only if a new TimesEntry has been created
629
int Ses_StoreAddEntry( Ses_Store_t * pStore, word * pTruth, int nVars, int * pArrTimeProfile, char * pSol, int fResLimit )
630
{
631
    int key, fAdded;
632 633 634
    Ses_TruthEntry_t * pTEntry;
    Ses_TimesEntry_t * pTiEntry;

Mathias Soeken committed
635 636 637
    if ( pSol )
        Abc_ExactNormalizeArrivalTimesForNetwork( nVars, pArrTimeProfile, pSol );

638
    key = Ses_StoreTableHash( pTruth, nVars );
639 640 641 642 643
    pTEntry = pStore->pEntries[key];

    /* does truth table already exist? */
    while ( pTEntry )
    {
644
        if ( Ses_StoreTruthEqual( pTEntry, pTruth, nVars ) )
645 646 647 648 649 650 651 652 653
            break;
        else
            pTEntry = pTEntry->next;
    }

    /* entry does not yet exist, so create new one and enqueue */
    if ( !pTEntry )
    {
        pTEntry = ABC_CALLOC( Ses_TruthEntry_t, 1 );
654
        Ses_StoreTruthCopy( pTEntry, pTruth, nVars );
655 656 657 658 659 660 661 662
        pTEntry->next = pStore->pEntries[key];
        pStore->pEntries[key] = pTEntry;
    }

    /* does arrival time already exist? */
    pTiEntry = pTEntry->head;
    while ( pTiEntry )
    {
663
        if ( Ses_StoreTimesEqual( pArrTimeProfile, pTiEntry->pArrTimeProfile, nVars ) )
664 665 666 667 668 669 670 671 672
            break;
        else
            pTiEntry = pTiEntry->next;
    }

    /* entry does not yet exist, so create new one and enqueue */
    if ( !pTiEntry )
    {
        pTiEntry = ABC_CALLOC( Ses_TimesEntry_t, 1 );
673
        Ses_StoreTimesCopy( pTiEntry->pArrTimeProfile, pArrTimeProfile, nVars );
674
        pTiEntry->pNetwork = pSol;
675
        pTiEntry->fResLimit = fResLimit;
676 677 678 679
        pTiEntry->next = pTEntry->head;
        pTEntry->head = pTiEntry;

        /* item has been added */
680
        fAdded = 1;
681
        pStore->nEntriesCount++;
682 683
        if ( pSol )
            pStore->nValidEntriesCount++;
684 685
    }
    else
Mathias Soeken committed
686
    {
Mathias Soeken committed
687
        //assert( 0 );
688
        /* item was already present */
689
        fAdded = 0;
Mathias Soeken committed
690
    }
691

692 693 694 695 696
    /* statistics */
    if ( pSol )
    {
        if ( fResLimit )
        {
Mathias Soeken committed
697 698
            pStore->nSynthesizedRL++;
            pStore->pSynthesizedRL[nVars]++;
699 700 701
        }
        else
        {
Mathias Soeken committed
702 703
            pStore->nSynthesizedImp++;
            pStore->pSynthesizedImp[nVars]++;
704 705 706 707 708 709
        }
    }
    else
    {
        if ( fResLimit )
        {
Mathias Soeken committed
710 711
            pStore->nUnsynthesizedRL++;
            pStore->pUnsynthesizedRL[nVars]++;
712 713 714
        }
        else
        {
Mathias Soeken committed
715 716
            pStore->nUnsynthesizedImp++;
            pStore->pUnsynthesizedImp[nVars]++;
717 718 719
        }
    }

Mathias Soeken committed
720 721 722
    if ( fAdded && pStore->szDBName )
        Ses_StoreWrite( pStore, pStore->szDBName, 1, 0, 0, 0 );

723
    return fAdded;
724 725
}

726 727
// pArrTimeProfile is normalized
// returns 1 if entry was in store, pSol may still be 0 if it couldn't be computed
Mathias Soeken committed
728
int Ses_StoreGetEntrySimple( Ses_Store_t * pStore, word * pTruth, int nVars, int * pArrTimeProfile, char ** pSol )
729
{
730
    int key;
731 732 733
    Ses_TruthEntry_t * pTEntry;
    Ses_TimesEntry_t * pTiEntry;

734
    key = Ses_StoreTableHash( pTruth, nVars );
735 736 737 738 739
    pTEntry = pStore->pEntries[key];

    /* find truth table entry */
    while ( pTEntry )
    {
740
        if ( Ses_StoreTruthEqual( pTEntry, pTruth, nVars ) )
741 742 743 744 745 746 747 748 749 750 751 752 753
            break;
        else
            pTEntry = pTEntry->next;
    }

    /* no entry found? */
    if ( !pTEntry )
        return 0;

    /* find times entry */
    pTiEntry = pTEntry->head;
    while ( pTiEntry )
    {
754
        if ( Ses_StoreTimesEqual( pArrTimeProfile, pTiEntry->pArrTimeProfile, nVars ) )
755 756 757 758 759 760 761 762 763
            break;
        else
            pTiEntry = pTiEntry->next;
    }

    /* no entry found? */
    if ( !pTiEntry )
        return 0;

764 765
    *pSol = pTiEntry->pNetwork;
    return 1;
766
}
767

Mathias Soeken committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
int Ses_StoreGetEntry( Ses_Store_t * pStore, word * pTruth, int nVars, int * pArrTimeProfile, char ** pSol )
{
    int key;
    Ses_TruthEntry_t * pTEntry;
    Ses_TimesEntry_t * pTiEntry;
    int pTimes[8];

    key = Ses_StoreTableHash( pTruth, nVars );
    pTEntry = pStore->pEntries[key];

    /* find truth table entry */
    while ( pTEntry )
    {
        if ( Ses_StoreTruthEqual( pTEntry, pTruth, nVars ) )
            break;
        else
            pTEntry = pTEntry->next;
    }

    /* no entry found? */
    if ( !pTEntry )
        return 0;

    /* find times entry */
    pTiEntry = pTEntry->head;
    while ( pTiEntry )
    {
        /* found after normalization wrt. to network */
        if ( pTiEntry->pNetwork )
        {
            memcpy( pTimes, pArrTimeProfile, sizeof(int) * nVars );
            Abc_ExactNormalizeArrivalTimesForNetwork( nVars, pTimes, pTiEntry->pNetwork );

            if ( Ses_StoreTimesEqual( pTimes, pTiEntry->pArrTimeProfile, nVars ) )
                break;
        }
        /* found for non synthesized network */
        else if ( Ses_StoreTimesEqual( pArrTimeProfile, pTiEntry->pArrTimeProfile, nVars ) )
            break;
        else
            pTiEntry = pTiEntry->next;
    }

    /* no entry found? */
    if ( !pTiEntry )
        return 0;

    *pSol = pTiEntry->pNetwork;
    return 1;
}

819
static void Ses_StoreRead( Ses_Store_t * pStore, const char * pFilename, int fSynthImp, int fSynthRL, int fUnsynthImp, int fUnsynthRL )
820
{
821 822
    int i;
    unsigned long nEntries;
823
    word pTruth[4];
824
    int nVars, fResLimit;
825 826 827 828
    int pArrTimeProfile[8];
    char pHeader[3];
    char * pNetwork;
    FILE * pFile;
Alan Mishchenko committed
829
    int value;
830

Mathias Soeken committed
831 832 833 834 835 836
    if ( pStore->szDBName )
    {
        printf( "cannot read from database when szDBName is set" );
        return;
    }

837 838 839 840 841 842 843
    pFile = fopen( pFilename, "rb" );
    if (pFile == NULL)
    {
        printf( "cannot open file \"%s\" for reading\n", pFilename );
        return;
    }

844
    value = fread( &nEntries, sizeof( unsigned long ), 1, pFile );
845

Alan Mishchenko committed
846
    for ( i = 0; i < (int)nEntries; ++i )
847
    {
Alan Mishchenko committed
848 849 850
        value = fread( pTruth, sizeof( word ), 4, pFile );
        value = fread( &nVars, sizeof( int ), 1, pFile );
        value = fread( pArrTimeProfile, sizeof( int ), 8, pFile );
851
        value = fread( &fResLimit, sizeof( int ), 1, pFile );
Alan Mishchenko committed
852
        value = fread( pHeader, sizeof( char ), 3, pFile );
853

854 855 856 857 858 859 860 861 862 863 864
        if ( pHeader[0] == '\0' )
            pNetwork = NULL;
        else
        {
            pNetwork = ABC_CALLOC( char, 3 + 4 * pHeader[ABC_EXACT_SOL_NGATES] + 2 + pHeader[ABC_EXACT_SOL_NVARS] );
            pNetwork[0] = pHeader[0];
            pNetwork[1] = pHeader[1];
            pNetwork[2] = pHeader[2];

            value = fread( pNetwork + 3, sizeof( char ), 4 * pHeader[ABC_EXACT_SOL_NGATES] + 2 + pHeader[ABC_EXACT_SOL_NVARS], pFile );
        }
865

866 867 868 869
        if ( !fSynthImp && pNetwork && !fResLimit )    continue;
        if ( !fSynthRL && pNetwork && fResLimit )      continue;
        if ( !fUnsynthImp && !pNetwork && !fResLimit ) continue;
        if ( !fUnsynthRL && !pNetwork && fResLimit )   continue;
870

871
        Ses_StoreAddEntry( pStore, pTruth, nVars, pArrTimeProfile, pNetwork, fResLimit );
872 873 874
    }

    fclose( pFile );
875

Alan Mishchenko committed
876
    printf( "read %lu entries from file\n", (long)nEntries );
877 878
}

Mathias Soeken committed
879 880 881
// computes top decomposition of variables wrt. to AND and OR
static inline void Ses_ManComputeTopDec( Ses_Man_t * pSes )
{
Mathias Soeken committed
882 883
    int l;
    word pMask[4];
Mathias Soeken committed
884

Mathias Soeken committed
885
    Abc_TtMask( pMask, pSes->nSpecWords, pSes->nSpecWords * 64 );
Mathias Soeken committed
886 887

    for ( l = 0; l < pSes->nSpecVars; ++l )
Mathias Soeken committed
888 889
        if ( Abc_TtIsTopDecomposable( pSes->pSpec, pMask, pSes->nSpecWords, l ) )
            pSes->pDecVars |= ( 1 << l );
Mathias Soeken committed
890 891
}

892
static inline Ses_Man_t * Ses_ManAlloc( word * pTruth, int nVars, int nFunc, int nMaxDepth, int * pArrTimeProfile, int fMakeAIG, int nBTLimit, int fVerbose )
893 894
{
    int h, i;
895 896 897 898 899

    Ses_Man_t * p = ABC_CALLOC( Ses_Man_t, 1 );
    p->pSat       = NULL;
    p->bSpecInv   = 0;
    for ( h = 0; h < nFunc; ++h )
900
        if ( pTruth[h << 2] & 1 )
901
        {
902 903
            for ( i = 0; i < 4; ++i )
                pTruth[(h << 2) + i] = ~pTruth[(h << 2) + i];
904 905
            p->bSpecInv |= ( 1 << h );
        }
906 907 908
    p->pSpec           = pTruth;
    p->nSpecVars       = nVars;
    p->nSpecFunc       = nFunc;
909
    p->nSpecWords      = Abc_TtWordNum( nVars );
910 911
    p->nRows           = ( 1 << nVars ) - 1;
    p->nMaxDepth       = nMaxDepth;
912 913
    p->pArrTimeProfile = nMaxDepth >= 0 ? pArrTimeProfile : NULL;
    if ( p->pArrTimeProfile )
914
        p->nArrTimeDelta = Abc_NormalizeArrivalTimes( p->pArrTimeProfile, nVars, &p->nArrTimeMax );
915
    else
916
        p->nArrTimeDelta = p->nArrTimeMax = 0;
917 918 919 920 921
    p->fMakeAIG        = fMakeAIG;
    p->nBTLimit        = nBTLimit;
    p->fVerbose        = fVerbose;
    p->fVeryVerbose    = 0;
    p->fExtractVerbose = 0;
922
    p->fSatVerbose     = 0;
Mathias Soeken committed
923 924 925
    p->vPolar          = Vec_IntAlloc( 100 );
    p->vAssump         = Vec_IntAlloc( 10 );
    p->vStairDecVars   = Vec_IntAlloc( nVars );
Mathias Soeken committed
926 927
    p->nRandRowAssigns = 2 * nVars;
    p->fKeepRowAssigns = 0;
928

Mathias Soeken committed
929 930 931
    if ( p->nSpecFunc == 1 )
        Ses_ManComputeTopDec( p );

Mathias Soeken committed
932 933
    srand( 0xCAFE );

934 935 936
    return p;
}

937
static inline void Ses_ManCleanLight( Ses_Man_t * pSes )
938
{
939
    int h, i;
940 941
    for ( h = 0; h < pSes->nSpecFunc; ++h )
        if ( ( pSes->bSpecInv >> h ) & 1 )
942 943 944
            for ( i = 0; i < 4; ++i )
                pSes->pSpec[(h << 2) + i] = ~( pSes->pSpec[(h << 2) + i] );

945
    if ( pSes->pArrTimeProfile )
946
        for ( i = 0; i < pSes->nSpecVars; ++i )
947
            pSes->pArrTimeProfile[i] += pSes->nArrTimeDelta;
948

Mathias Soeken committed
949 950 951 952
    Vec_IntFree( pSes->vPolar );
    Vec_IntFree( pSes->vAssump );
    Vec_IntFree( pSes->vStairDecVars );

953 954 955 956 957
    ABC_FREE( pSes );
}

static inline void Ses_ManClean( Ses_Man_t * pSes )
{
958 959
    if ( pSes->pSat )
        sat_solver_delete( pSes->pSat );
960
    Ses_ManCleanLight( pSes );
961 962 963 964 965 966 967 968 969 970 971 972
}

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

  Synopsis    [Access variables based on indexes.]

***********************************************************************/
static inline int Ses_ManSimVar( Ses_Man_t * pSes, int i, int t )
{
    assert( i < pSes->nGates );
    assert( t < pSes->nRows );

Mathias Soeken committed
973
    return pSes->nSimOffset + pSes->nRows * i + t;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
}

static inline int Ses_ManOutputVar( Ses_Man_t * pSes, int h, int i )
{
    assert( h < pSes->nSpecFunc );
    assert( i < pSes->nGates );

    return pSes->nOutputOffset + pSes->nGates * h + i;
}

static inline int Ses_ManGateVar( Ses_Man_t * pSes, int i, int p, int q )
{
    assert( i < pSes->nGates );
    assert( p < 2 );
    assert( q < 2 );
    assert( p > 0 || q > 0 );

    return pSes->nGateOffset + i * 3 + ( p << 1 ) + q - 1;
}

static inline int Ses_ManSelectVar( Ses_Man_t * pSes, int i, int j, int k )
{
    int a;
    int offset;

    assert( i < pSes->nGates );
    assert( k < pSes->nSpecVars + i );
    assert( j < k );

    offset = pSes->nSelectOffset;
    for ( a = pSes->nSpecVars; a < pSes->nSpecVars + i; ++a )
        offset += a * ( a - 1 ) / 2;

    return offset + ( -j * ( 1 + j - 2 * ( pSes->nSpecVars + i ) ) ) / 2 + ( k - j - 1 );
}

1010 1011 1012
static inline int Ses_ManDepthVar( Ses_Man_t * pSes, int i, int j )
{
    assert( i < pSes->nGates );
1013
    assert( j <= pSes->nArrTimeMax + i );
1014

1015
    return pSes->nDepthOffset + i * pSes->nArrTimeMax + ( ( i * ( i + 1 ) ) / 2 ) + j;
1016 1017
}

1018 1019
/**Function*************************************************************

Mathias Soeken committed
1020 1021 1022 1023 1024 1025 1026
  Synopsis    [Compute truth table from a solution.]

***********************************************************************/
static word * Ses_ManDeriveTruth( Ses_Man_t * pSes, char * pSol, int fInvert )
{
    int i, f, j, k, w, nGates = pSol[ABC_EXACT_SOL_NGATES];
    char * p;
Alan Mishchenko committed
1027
    word * pTruth = NULL, * pTruth0, * pTruth1;
Mathias Soeken committed
1028 1029 1030 1031 1032 1033 1034 1035 1036
    assert( pSol[ABC_EXACT_SOL_NFUNC] == 1 );

    p = pSol + 3;

    memset( pSes->pTtObjs, 0, sizeof( word ) * 4 * nGates );

    for ( i = 0; i < nGates; ++i )
    {
        f = *p++;
1037
        assert( *p == 2 ), p++;
Mathias Soeken committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
        j = *p++;
        k = *p++;

        pTruth0 = j < pSes->nSpecVars ? &s_Truths8[j << 2] : &pSes->pTtObjs[( j - pSes->nSpecVars ) << 2];
        pTruth1 = k < pSes->nSpecVars ? &s_Truths8[k << 2] : &pSes->pTtObjs[( k - pSes->nSpecVars ) << 2];

        pTruth = &pSes->pTtObjs[i << 2];

        if ( f & 1 )
            for ( w = 0; w < pSes->nSpecWords; ++w )
                pTruth[w] |= ~pTruth0[w] & pTruth1[w];
        if ( ( f >> 1 ) & 1 )
            for ( w = 0; w < pSes->nSpecWords; ++w )
                pTruth[w] |= pTruth0[w] & ~pTruth1[w];
        if ( ( f >> 2 ) & 1 )
            for ( w = 0; w < pSes->nSpecWords; ++w )
                pTruth[w] |= pTruth0[w] & pTruth1[w];
    }

    assert( Abc_Lit2Var( *p ) == nGates - 1 );
    if ( fInvert && Abc_LitIsCompl( *p ) )
        Abc_TtNot( pTruth, pSes->nSpecWords );

    return pTruth;
}

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

1066 1067 1068 1069 1070 1071 1072
  Synopsis    [Setup variables to find network with nGates gates.]

***********************************************************************/
static void Ses_ManCreateVars( Ses_Man_t * pSes, int nGates )
{
    int i;

1073
    if ( pSes->fSatVerbose )
1074
    {
Mathias Soeken committed
1075
        printf( "create variables for network with %d functions over %d variables and %d/%d gates\n", pSes->nSpecFunc, pSes->nSpecVars, nGates, pSes->nMaxGates );
1076 1077 1078 1079 1080 1081 1082 1083 1084
    }

    pSes->nGates      = nGates;
    pSes->nSimVars    = nGates * pSes->nRows;
    pSes->nOutputVars = pSes->nSpecFunc * nGates;
    pSes->nGateVars   = nGates * 3;
    pSes->nSelectVars = 0;
    for ( i = pSes->nSpecVars; i < pSes->nSpecVars + nGates; ++i )
        pSes->nSelectVars += ( i * ( i - 1 ) ) / 2;
1085
    pSes->nDepthVars = pSes->nMaxDepth > 0 ? nGates * pSes->nArrTimeMax + ( nGates * ( nGates + 1 ) ) / 2 : 0;
1086

Mathias Soeken committed
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    /* pSes->nSimOffset    = 0; */
    /* pSes->nOutputOffset = pSes->nSimVars; */
    /* pSes->nGateOffset   = pSes->nSimVars + pSes->nOutputVars; */
    /* pSes->nSelectOffset = pSes->nSimVars + pSes->nOutputVars + pSes->nGateVars; */
    /* pSes->nDepthOffset  = pSes->nSimVars + pSes->nOutputVars + pSes->nGateVars + pSes->nSelectVars; */

    pSes->nDepthOffset  = 0;
    pSes->nSelectOffset = pSes->nDepthVars;
    pSes->nGateOffset   = pSes->nDepthVars + pSes->nSelectVars;
    pSes->nOutputOffset = pSes->nDepthVars + pSes->nSelectVars + pSes->nGateVars;
    pSes->nSimOffset    = pSes->nDepthVars + pSes->nSelectVars + pSes->nGateVars + pSes->nOutputVars;

    /* pSes->nDepthOffset  = 0; */
    /* pSes->nSelectOffset = pSes->nDepthVars; */
    /* pSes->nOutputOffset = pSes->nDepthVars + pSes->nSelectVars; */
    /* pSes->nGateOffset   = pSes->nDepthVars + pSes->nSelectVars + pSes->nOutputVars; */
    /* pSes->nSimOffset    = pSes->nDepthVars + pSes->nSelectVars + pSes->nOutputVars + pSes->nGateVars; */
1104

1105
    /* if we already have a SAT solver, then restart it (this saves a lot of time) */
1106
    if ( pSes->pSat )
1107 1108 1109
        sat_solver_restart( pSes->pSat );
    else
        pSes->pSat = sat_solver_new();
1110
    sat_solver_setnvars( pSes->pSat, pSes->nSimVars + pSes->nOutputVars + pSes->nGateVars + pSes->nSelectVars + pSes->nDepthVars );
1111 1112 1113 1114 1115 1116 1117
}

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

  Synopsis    [Create clauses.]

***********************************************************************/
Mathias Soeken committed
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
static inline void Ses_ManGateCannotHaveChild( Ses_Man_t * pSes, int i, int j )
{
    int k;

    for ( k = 0; k < j; ++k )
        Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, k, j ), 1 ) );
    for ( k = j + 1; k < pSes->nSpecVars + i; ++k )
        Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 ) );
}

1128 1129
static inline void Ses_ManCreateMainClause( Ses_Man_t * pSes, int t, int i, int j, int k, int a, int b, int c )
{
1130
    int pLits[5], ctr = 0;
1131 1132 1133 1134 1135 1136

    pLits[ctr++] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
    pLits[ctr++] = Abc_Var2Lit( Ses_ManSimVar( pSes, i, t ), a );

    if ( j < pSes->nSpecVars )
    {
1137
        if ( ( ( ( t + 1 ) & ( 1 << j ) ) ? 1 : 0 ) != b )
1138 1139 1140 1141 1142 1143 1144
            return;
    }
    else
        pLits[ctr++] = Abc_Var2Lit( Ses_ManSimVar( pSes, j - pSes->nSpecVars, t ), b );

    if ( k < pSes->nSpecVars )
    {
1145
        if ( ( ( ( t + 1 ) & ( 1 << k ) ) ? 1 : 0 ) != c )
1146 1147 1148 1149 1150 1151 1152 1153
            return;
    }
    else
        pLits[ctr++] = Abc_Var2Lit( Ses_ManSimVar( pSes, k - pSes->nSpecVars, t ), c );

    if ( b > 0 || c > 0 )
        pLits[ctr++] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, b, c ), 1 - a );

1154
    sat_solver_addclause( pSes->pSat, pLits, pLits + ctr );
1155 1156
}

Mathias Soeken committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
static int inline Ses_ManCreateTruthTableClause( Ses_Man_t * pSes, int t )
{
    int i, j, k, h;
    int pLits[3];

    for ( i = 0; i < pSes->nGates; ++i )
    {
        /* main clauses */
        for ( j = 0; j < pSes->nSpecVars + i; ++j )
            for ( k = j + 1; k < pSes->nSpecVars + i; ++k )
            {
                Ses_ManCreateMainClause( pSes, t, i, j, k, 0, 0, 1 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 0, 1, 0 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 0, 1, 1 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 1, 0, 0 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 1, 0, 1 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 1, 1, 0 );
                Ses_ManCreateMainClause( pSes, t, i, j, k, 1, 1, 1 );
            }

        /* output clauses */
        if ( pSes->nSpecFunc != 1 )
            for ( h = 0; h < pSes->nSpecFunc; ++h )
            {
                pLits[0] = Abc_Var2Lit( Ses_ManOutputVar( pSes, h, i ), 1 );
                pLits[1] = Abc_Var2Lit( Ses_ManSimVar( pSes, i, t ), 1 - Abc_TtGetBit( &pSes->pSpec[h << 2], t + 1 ) );
                if ( !sat_solver_addclause( pSes->pSat, pLits, pLits + 2 ) )
                    return 0;
            }
    }

    if ( pSes->nSpecFunc == 1 )
Mathias Soeken committed
1189
        Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManSimVar( pSes, pSes->nGates - 1, t ), 1 - Abc_TtGetBit( pSes->pSpec, t + 1 ) ) );
Mathias Soeken committed
1190 1191 1192 1193

    return 1;
}

1194
static int Ses_ManCreateClauses( Ses_Man_t * pSes )
1195 1196 1197
{
    extern int Extra_TruthVarsSymm( unsigned * pTruth, int nVars, int iVar0, int iVar1 );

Mathias Soeken committed
1198
    int h, i, j, k, t, ii, jj, kk, iii, p, q;
1199
    int pLits[3];
Mathias Soeken committed
1200
    Vec_Int_t * vLits = NULL;
1201 1202

    for ( t = 0; t < pSes->nRows; ++t )
Mathias Soeken committed
1203
    {
Mathias Soeken committed
1204 1205
        if ( Abc_TtGetBit( pSes->pTtValues, t ) )
            if ( !Ses_ManCreateTruthTableClause( pSes, t ) )
Mathias Soeken committed
1206 1207 1208
                return 0;
    }

1209 1210
    /* if there is only one output, we know it must point to the last gate  */
    if ( pSes->nSpecFunc == 1 )
1211
    {
1212
        for ( i = 0; i < pSes->nGates - 1; ++i )
Mathias Soeken committed
1213 1214
            Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManOutputVar( pSes, 0, i ), 1 ) );
        Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManOutputVar( pSes, 0, pSes->nGates - 1 ), 0 ) );
Mathias Soeken committed
1215 1216

        vLits = Vec_IntAlloc( 0u );
1217 1218 1219
    }
    else
    {
Mathias Soeken committed
1220 1221
        vLits = Vec_IntAlloc( 0u );

1222 1223 1224 1225 1226 1227 1228 1229
        /* some output is selected */
        for ( h = 0; h < pSes->nSpecFunc; ++h )
        {
            Vec_IntGrowResize( vLits, pSes->nGates );
            for ( i = 0; i < pSes->nGates; ++i )
                Vec_IntSetEntry( vLits, i, Abc_Var2Lit( Ses_ManOutputVar( pSes, h, i ), 0 ) );
            sat_solver_addclause( pSes->pSat, Vec_IntArray( vLits ), Vec_IntArray( vLits ) + pSes->nGates );
        }
1230 1231 1232 1233 1234
    }

    /* each gate has two operands */
    for ( i = 0; i < pSes->nGates; ++i )
    {
1235 1236
        Vec_IntGrowResize( vLits, ( ( pSes->nSpecVars + i ) * ( pSes->nSpecVars + i - 1 ) ) / 2 );
        jj = 0;
1237 1238
        for ( j = 0; j < pSes->nSpecVars + i; ++j )
            for ( k = j + 1; k < pSes->nSpecVars + i; ++k )
1239 1240
                Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 0 ) );
        sat_solver_addclause( pSes->pSat, Vec_IntArray( vLits ), Vec_IntArray( vLits ) + jj );
1241 1242
    }

Mathias Soeken committed
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    /* gate decomposition (makes it worse) */
    /* if ( fDecVariable >= 0 && pSes->nGates >= 2 ) */
    /* { */
    /*     pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, pSes->nGates - 1, fDecVariable, pSes->nSpecVars + pSes->nGates - 2 ), 0 ); */
    /*     if ( !sat_solver_addclause( pSes->pSat, pLits, pLits + 1 ) ) */
    /*     { */
    /*         Vec_IntFree( vLits ); */
    /*         return 0; */
    /*     } */

    /*     for ( k = 1; k < pSes->nSpecVars + pSes->nGates - 1; ++k ) */
    /*         for ( j = 0; j < k; ++j ) */
    /*             if ( j != fDecVariable || k != pSes->nSpecVars + pSes->nGates - 2 ) */
    /*             { */
    /*                 pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, pSes->nGates - 1, j, k ), 1 ); */
    /*                 if ( !sat_solver_addclause( pSes->pSat, pLits, pLits + 1 ) ) */
    /*                 { */
    /*                     Vec_IntFree( vLits ); */
    /*                     return 0; */
    /*                 } */
    /*             } */
    /* } */

1266 1267 1268 1269 1270 1271 1272 1273 1274
    /* only AIG */
    if ( pSes->fMakeAIG )
    {
        for ( i = 0; i < pSes->nGates; ++i )
        {
            /* not 2 ones */
            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 1 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 1 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 0 );
1275
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
1276 1277 1278 1279

            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 1 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 0 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 1 );
1280
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
1281 1282 1283 1284

            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 0 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 1 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 1 );
1285
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
1286 1287 1288
        }
    }

Mathias Soeken committed
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 1314 1315 1316 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
    /* only binary clauses */
    if ( 1 ) /* TODO: add some meaningful parameter */
    {
        for ( i = 0; i < pSes->nGates; ++i )
        {
            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 0 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 0 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 0 );
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );

            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 1 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 0 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 1 );
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );

            pLits[0] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 0, 1 ), 0 );
            pLits[1] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 0 ), 1 );
            pLits[2] = Abc_Var2Lit( Ses_ManGateVar( pSes, i, 1, 1 ), 1 );
            sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
        }

        for ( i = 0; i < pSes->nGates; ++i )
            for ( k = 1; k < pSes->nSpecVars + i; ++k )
                for ( j = 0; j < k; ++j )
                {
                    pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );

                    for ( kk = 1; kk < pSes->nSpecVars + i; ++kk )
                        for ( jj = 0; jj < kk; ++jj )
                        {
                            if ( k == kk && j == jj ) continue;
                            pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, jj, kk ), 1 );

                            if ( pLits[0] < pLits[1] )
                                sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
                        }
                }

        /* Vec_IntGrowResize( vLits, pSes->nGates * ( pSes->nSpecVars + pSes->nGates - 2 ) ); */

        /* for ( j = 0; j < pSes->nSpecVars; ++j ) */
        /* { */
        /*     jj = 0; */
        /*     for ( i = 0; i < pSes->nGates; ++i ) */
        /*     { */
        /*         for ( k = 0; k < j; ++k ) */
        /*             Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, k, j ), 0 ) ); */
        /*         for ( k = j + 1; k < pSes->nSpecVars + i; ++k ) */
        /*             Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 0 ) ); */
        /*     } */
        /*     sat_solver_addclause( pSes->pSat, Vec_IntArray( vLits ), Vec_IntArray( vLits ) + jj ); */
        /* } */
    }

Mathias Soeken committed
1343
    /* EXTRA stair decomposition */
1344
    if (Vec_IntSize( pSes->vStairDecVars ) )
Mathias Soeken committed
1345 1346 1347
    {
        Vec_IntForEachEntry( pSes->vStairDecVars, j, i )
        {
1348
            if ( pSes->nGates - 2 - i < j )
Mathias Soeken committed
1349
            {
1350
                continue;
Mathias Soeken committed
1351
            }
Mathias Soeken committed
1352 1353
            Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManSelectVar( pSes, pSes->nGates - 1 - i, j, pSes->nSpecVars + pSes->nGates - 2 - i ), 0 ) );

Mathias Soeken committed
1354 1355
            //printf( "dec %d for var %d\n", pSes->pStairDecFunc[i], j );

Mathias Soeken committed
1356 1357 1358 1359
            switch ( pSes->pStairDecFunc[i] )
            {
            case 1: /* AND(x,g) */
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 0, 1 ), 1 ) );
Mathias Soeken committed
1360 1361
                //Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 0 ), 1 ) );
                //Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 1 ), 0 ) );
Mathias Soeken committed
1362 1363
                break;
            case 2: /* AND(!x,g) */
Mathias Soeken committed
1364
                //Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 0, 1 ), 0 ) );
Mathias Soeken committed
1365 1366 1367 1368
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 0 ), 1 ) );
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 1 ), 1 ) );
                break;
            case 3: /* OR(x,g) */
Mathias Soeken committed
1369
                //Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 0, 1 ), 0 ) );
Mathias Soeken committed
1370 1371 1372 1373
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 0 ), 0 ) );
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 1 ), 0 ) );
                break;
            case 4: /* OR(!x,g) */
Mathias Soeken committed
1374 1375 1376
                ////Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 0, 1 ), 0 ) );
                ////Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 0 ), 1 ) );
                ////Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 1 ), 0 ) );
Mathias Soeken committed
1377
                break;
Mathias Soeken committed
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
            case 5: /* XOR(x,g) */
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 0, 1 ), 0 ) );
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 0 ), 0 ) );
                Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManGateVar( pSes, pSes->nGates - 1 - i, 1, 1 ), 1 ) );
                break;
            default:
                printf( "func: %d\n", pSes->pStairDecFunc[i] );
                assert( 0 );
            }
        }
    }

1390
    /* EXTRA clauses: use gate i at least once */
1391
    Vec_IntGrowResize( vLits, pSes->nSpecFunc + pSes->nGates * ( pSes->nSpecVars + pSes->nGates - 2 ) );
1392 1393
    for ( i = 0; i < pSes->nGates; ++i )
    {
1394
        jj = 0;
1395
        for ( h = 0; h < pSes->nSpecFunc; ++h )
1396
            Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManOutputVar( pSes, h, i ), 0 ) );
1397 1398 1399
        for ( ii = i + 1; ii < pSes->nGates; ++ii )
        {
            for ( j = 0; j < pSes->nSpecVars + i; ++j )
1400
                Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, j, pSes->nSpecVars + i ), 0 ) );
1401
            for ( j = pSes->nSpecVars + i + 1; j < pSes->nSpecVars + ii; ++j )
1402
                Vec_IntSetEntry( vLits, jj++, Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, pSes->nSpecVars + i, j ), 0 ) );
1403
        }
1404
        sat_solver_addclause( pSes->pSat, Vec_IntArray( vLits ), Vec_IntArray( vLits ) + jj );
1405
    }
1406
    Vec_IntFree( vLits );
1407

Mathias Soeken committed
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    /* EXTRA clauses: no reapplying operand */
    if ( pSes->nGates > 1 )
        for ( i = 0; i < pSes->nGates - 1; ++i )
            for ( ii = i + 1; ii < pSes->nGates; ++ii )
                for ( k = 1; k < pSes->nSpecVars + i; ++k )
                    for ( j = 0; j < k; ++j )
                    {
                        pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
                        pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, j, pSes->nSpecVars + i ), 1 );
                        sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );

                        pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, k, pSes->nSpecVars + i ), 1 );
                        sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
                    }
Mathias Soeken committed
1422 1423 1424 1425 1426 1427 1428 1429 1430
    if ( pSes->nGates > 2 )
        for ( i = 0; i < pSes->nGates - 2; ++i )
            for ( ii = i + 1; ii < pSes->nGates - 1; ++ii )
                for ( iii = ii + 1; iii < pSes->nGates; ++iii )
                    for ( k = 1; k < pSes->nSpecVars + i; ++k )
                        for ( j = 0; j < k; ++j )
                            {
                                pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
                                pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, j, k ), 1 );
Mathias Soeken committed
1431
                                pLits[2] = Abc_Var2Lit( Ses_ManSelectVar( pSes, iii, i, ii ), 1 );
Mathias Soeken committed
1432 1433
                                sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
                            }
Mathias Soeken committed
1434

1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    /* EXTRA clauses: co-lexicographic order */
    for ( i = 0; i < pSes->nGates - 1; ++i )
    {
        for ( k = 2; k < pSes->nSpecVars + i; ++k )
        {
            for ( j = 1; j < k; ++j )
                for ( jj = 0; jj < j; ++jj )
                {
                    pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
                    pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i + 1, jj, k ), 1 );
Mathias Soeken committed
1445
                    sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
1446 1447 1448 1449 1450 1451 1452 1453
                }

            for ( j = 0; j < k; ++j )
                for ( kk = 1; kk < k; ++kk )
                    for ( jj = 0; jj < kk; ++jj )
                    {
                        pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
                        pLits[1] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i + 1, jj, kk ), 1 );
Mathias Soeken committed
1454
                        sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
1455 1456 1457 1458 1459
                    }
        }
    }

    /* EXTRA clauses: symmetric variables */
1460
    if ( /*pSes->nMaxDepth == -1 &&*/ pSes->nSpecFunc == 1 ) /* only check if there is one output function */
1461 1462
        for ( q = 1; q < pSes->nSpecVars; ++q )
            for ( p = 0; p < q; ++p )
1463
                if ( Extra_TruthVarsSymm( (unsigned*)( pSes->pSpec ), pSes->nSpecVars, p, q ) &&
Mathias Soeken committed
1464
                     ( !pSes->pArrTimeProfile || ( pSes->pArrTimeProfile[p] <= pSes->pArrTimeProfile[q] ) ) )
1465
                {
1466
                    if ( pSes->fSatVerbose )
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                        printf( "variables %d and %d are symmetric\n", p, q );
                    for ( i = 0; i < pSes->nGates; ++i )
                        for ( j = 0; j < q; ++j )
                        {
                            if ( j == p ) continue;

                            vLits = Vec_IntAlloc( 0 );
                            Vec_IntPush( vLits, Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, q ), 1 ) );
                            for ( ii = 0; ii < i; ++ii )
                                for ( kk = 1; kk < pSes->nSpecVars + ii; ++kk )
                                    for ( jj = 0; jj < kk; ++jj )
                                        if ( jj == p || kk == p )
                                            Vec_IntPush( vLits, Abc_Var2Lit( Ses_ManSelectVar( pSes, ii, jj, kk ), 0 ) );
1480
                            sat_solver_addclause( pSes->pSat, Vec_IntArray( vLits ), Vec_IntLimit( vLits ) );
1481 1482 1483
                            Vec_IntFree( vLits );
                        }
                }
1484

Mathias Soeken committed
1485 1486
    return 1;
}
1487

Mathias Soeken committed
1488 1489 1490 1491
static int Ses_ManCreateDepthClauses( Ses_Man_t * pSes )
{
    int i, j, k, jj, kk, d, h;
    int pLits[3];
1492

Mathias Soeken committed
1493 1494 1495 1496 1497
    for ( i = 0; i < pSes->nGates; ++i )
    {
        /* propagate depths from children */
        for ( k = 1; k < i; ++k )
            for ( j = 0; j < k; ++j )
1498
            {
Mathias Soeken committed
1499 1500 1501 1502 1503 1504 1505
                pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, pSes->nSpecVars + j, pSes->nSpecVars + k ), 1 );
                for ( jj = 0; jj <= pSes->nArrTimeMax + j; ++jj )
                {
                    pLits[1] = Abc_Var2Lit( Ses_ManDepthVar( pSes, j, jj ), 1 );
                    pLits[2] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, jj + 1 ), 0 );
                    sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
                }
1506
            }
1507

Mathias Soeken committed
1508 1509
        for ( k = 0; k < i; ++k )
            for ( j = 0; j < pSes->nSpecVars + k; ++j )
1510
            {
Mathias Soeken committed
1511 1512 1513 1514 1515 1516 1517
                pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, pSes->nSpecVars + k ), 1 );
                for ( kk = 0; kk <= pSes->nArrTimeMax + k; ++kk )
                {
                    pLits[1] = Abc_Var2Lit( Ses_ManDepthVar( pSes, k, kk ), 1 );
                    pLits[2] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, kk + 1 ), 0 );
                    sat_solver_addclause( pSes->pSat, pLits, pLits + 3 );
                }
1518 1519
            }

Mathias Soeken committed
1520 1521 1522 1523 1524
        /* propagate depths from arrival times at PIs */
        if ( pSes->pArrTimeProfile )
        {
            for ( k = 1; k < pSes->nSpecVars + i; ++k )
                for ( j = 0; j < ( ( k < pSes->nSpecVars ) ? k : pSes->nSpecVars ); ++j )
1525
                {
Mathias Soeken committed
1526 1527 1528 1529 1530 1531 1532
                    d = pSes->pArrTimeProfile[j];
                    if ( k < pSes->nSpecVars && pSes->pArrTimeProfile[k] > d )
                        d = pSes->pArrTimeProfile[k];

                    pLits[0] = Abc_Var2Lit( Ses_ManSelectVar( pSes, i, j, k ), 1 );
                    pLits[1] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, d ), 0 );
                    sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
1533 1534
                }
        }
Mathias Soeken committed
1535 1536
        else
            /* arrival times are 0 */
Mathias Soeken committed
1537
            Vec_IntPush( pSes->vAssump, Abc_Var2Lit( Ses_ManDepthVar( pSes, i, 0 ), 0 ) );
Mathias Soeken committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

        /* reverse order encoding of depth variables */
        for ( j = 1; j <= pSes->nArrTimeMax + i; ++j )
        {
            pLits[0] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, j ), 1 );
            pLits[1] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, j - 1 ), 0 );
            sat_solver_addclause( pSes->pSat, pLits, pLits + 2 );
        }

        /* constrain maximum depth */
        if ( pSes->nMaxDepth < pSes->nArrTimeMax + i )
            for ( h = 0; h < pSes->nSpecFunc; ++h )
            {
                pLits[0] = Abc_Var2Lit( Ses_ManOutputVar( pSes, h, i ), 1 );
                pLits[1] = Abc_Var2Lit( Ses_ManDepthVar( pSes, i, pSes->nMaxDepth ), 1 );
                if ( !sat_solver_addclause( pSes->pSat, pLits, pLits + 2 ) )
                    return 0;
            }
1556
    }
1557 1558

    return 1;
1559 1560 1561 1562 1563 1564 1565
}

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

  Synopsis    [Solve.]

***********************************************************************/
Mathias Soeken committed
1566 1567
static inline double Sat_Wrd2Dbl( word w )  { return (double)(unsigned)(w&0x3FFFFFFF) + (double)(1<<30)*(unsigned)(w>>30); }

1568 1569 1570 1571 1572
static inline int Ses_ManSolve( Ses_Man_t * pSes )
{
    int status;
    abctime timeStart, timeDelta;

1573
    if ( pSes->fSatVerbose )
1574
    {
Mathias Soeken committed
1575 1576
        printf( "SAT   CL: %7d   VA: %5d", sat_solver_nclauses( pSes->pSat ), sat_solver_nvars( pSes->pSat ) );
        fflush( stdout );
1577
    }
1578 1579

    timeStart = Abc_Clock();
Mathias Soeken committed
1580
    status = sat_solver_solve( pSes->pSat, Vec_IntArray( pSes->vAssump ), Vec_IntLimit( pSes->vAssump ), pSes->nBTLimit, 0, 0, 0 );
1581 1582
    timeDelta = Abc_Clock() - timeStart;

Mathias Soeken committed
1583
    if ( pSes->fSatVerbose )
Mathias Soeken committed
1584 1585 1586 1587 1588
        printf( "   RE:   %2d   ST: %4.f   CO: %7.0f   DE: %6.0f    PR: %6.0f\n",
                status,
                Sat_Wrd2Dbl( pSes->pSat->stats.starts ), Sat_Wrd2Dbl( pSes->pSat->stats.conflicts ),
                Sat_Wrd2Dbl( pSes->pSat->stats.decisions ), Sat_Wrd2Dbl( pSes->pSat->stats.propagations ) );
        //Sat_SolverPrintStats( stdout, pSes->pSat );
Mathias Soeken committed
1589

1590 1591 1592 1593
    pSes->timeSat += timeDelta;

    if ( status == l_True )
    {
1594
        pSes->nSatCalls++;
1595 1596 1597 1598 1599
        pSes->timeSatSat += timeDelta;
        return 1;
    }
    else if ( status == l_False )
    {
1600
        pSes->nUnsatCalls++;
1601 1602 1603 1604 1605
        pSes->timeSatUnsat += timeDelta;
        return 0;
    }
    else
    {
1606 1607
        pSes->nUndefCalls++;
        pSes->timeSatUndef += timeDelta;
1608
        if ( pSes->fSatVerbose )
1609
        {
Mathias Soeken committed
1610 1611 1612
            //Sat_SolverWriteDimacs( pSes->pSat, "/tmp/test.cnf", Vec_IntArray( pSes->vAssump ), Vec_IntLimit( pSes->vAssump ), 1 );
            //exit( 42 );

1613
            printf( "resource limit reached\n" );
1614
        }
1615
        return 2;
1616 1617 1618 1619 1620 1621 1622 1623
    }
}

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

  Synopsis    [Extract solution.]

***********************************************************************/
1624 1625
// char is an array of short integers that stores the synthesized network
// using the following format
1626 1627 1628 1629 1630 1631
// | nvars | nfunc | ngates | gate[1] | ... | gate[ngates] | func[1] | .. | func[nfunc] |
// nvars:       integer with number of variables
// nfunc:       integer with number of functions
// ngates:      integer with number of gates
// gate[i]:     | op | nfanin | fanin[1] | ... | fanin[nfanin] |
//   op:        integer of gate's truth table (divided by 2, because gate is normal)
Mathias Soeken committed
1632 1633
//   nfanin:    integer with number of fanins
//   fanin[i]:  integer to primary input or other gate
1634 1635 1636 1637 1638
// func[i]:     | fanin | delay | pin[1] | ... | pin[nvars] |
//   fanin:     integer as literal to some gate (not primary input), can be complemented
//   delay:     maximum delay to output (taking arrival times into account, not normalized) or 0 if not specified
//   pin[i]:    pin to pin delay to input i or 0 if not specified or if there is no connection to input i
// NOTE: since outputs can only point to gates, delay and pin-to-pin times cannot be 0
1639
static char * Ses_ManExtractSolution( Ses_Man_t * pSes )
1640
{
1641
    int nSol, h, i, j, k, l, aj, ak, d, nOp;
1642
    char * pSol, * p;
Alan Mishchenko committed
1643
    int * pPerm = NULL; /* will be a 2d array [i][l] where is is gate id and l is PI id */
1644 1645

    /* compute length of solution, for now all gates have 2 inputs */
1646
    nSol = 3 + pSes->nGates * 4 + pSes->nSpecFunc * ( 2 + pSes->nSpecVars );
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

    p = pSol = ABC_CALLOC( char, nSol );

    /* header */
    *p++ = pSes->nSpecVars;
    *p++ = pSes->nSpecFunc;
    *p++ = pSes->nGates;

    /* gates */
    for ( i = 0; i < pSes->nGates; ++i )
    {
        nOp  = sat_solver_var_value( pSes->pSat, Ses_ManGateVar( pSes, i, 0, 1 ) );
        nOp |= sat_solver_var_value( pSes->pSat, Ses_ManGateVar( pSes, i, 1, 0 ) ) << 1;
        nOp |= sat_solver_var_value( pSes->pSat, Ses_ManGateVar( pSes, i, 1, 1 ) ) << 2;

        *p++ = nOp;
        *p++ = 2;

1665
        if ( pSes->fExtractVerbose )
1666 1667
            printf( "add gate %d with operation %d", pSes->nSpecVars + i, nOp );

1668 1669 1670 1671
        for ( k = 0; k < pSes->nSpecVars + i; ++k )
            for ( j = 0; j < k; ++j )
                if ( sat_solver_var_value( pSes->pSat, Ses_ManSelectVar( pSes, i, j, k ) ) )
                {
1672
                    if ( pSes->fExtractVerbose )
1673
                        printf( " and operands %d and %d", j, k );
1674 1675
                    *p++ = j;
                    *p++ = k;
Mathias Soeken committed
1676
                    k = pSes->nSpecVars + i;
1677 1678 1679
                    break;
                }

1680
        if ( pSes->fExtractVerbose )
1681 1682 1683 1684 1685 1686 1687 1688 1689
        {
            if ( pSes->nMaxDepth > 0 )
            {
                printf( " and depth vector " );
                for ( j = 0; j <= pSes->nArrTimeMax + i; ++j )
                    printf( "%d", sat_solver_var_value( pSes->pSat, Ses_ManDepthVar( pSes, i, j ) ) );
            }
            printf( "\n" );
        }
1690 1691
    }

1692 1693 1694 1695 1696 1697 1698 1699
    /* pin-to-pin delay */
    if ( pSes->nMaxDepth != -1 )
    {
        pPerm = ABC_CALLOC( int, pSes->nGates * pSes->nSpecVars );
        for ( i = 0; i < pSes->nGates; ++i )
        {
            /* since all gates are binary for now */
            j = pSol[3 + i * 4 + 2];
1700
            k = pSol[3 + i * 4 + 3];
1701 1702 1703 1704

            for ( l = 0; l < pSes->nSpecVars; ++l )
            {
                /* pin-to-pin delay to input l of child nodes */
1705 1706
                aj = j < pSes->nSpecVars ? 0 : pPerm[(j - pSes->nSpecVars) * pSes->nSpecVars + l];
                ak = k < pSes->nSpecVars ? 0 : pPerm[(k - pSes->nSpecVars) * pSes->nSpecVars + l];
1707 1708

                if ( aj == 0 && ak == 0 )
1709
                    pPerm[i * pSes->nSpecVars + l] = ( l == j || l == k ) ? 1 : 0;
1710
                else
1711
                    pPerm[i * pSes->nSpecVars + l] = Abc_MaxInt( aj, ak ) + 1;
1712 1713 1714 1715
            }
        }
    }

1716 1717 1718 1719
    /* outputs */
    for ( h = 0; h < pSes->nSpecFunc; ++h )
        for ( i = 0; i < pSes->nGates; ++i )
            if ( sat_solver_var_value( pSes->pSat, Ses_ManOutputVar( pSes, h, i ) ) )
1720
            {
1721
                *p++ = Abc_Var2Lit( i, ( pSes->bSpecInv >> h ) & 1 );
1722 1723
                d = 0;
                if ( pSes->nMaxDepth != -1 )
1724
                    for ( l = 0; l < pSes->nSpecVars; ++l )
1725 1726 1727 1728 1729 1730
                    {
                        if ( pSes->pArrTimeProfile )
                            d = Abc_MaxInt( d, pSes->pArrTimeProfile[l] + pPerm[i * pSes->nSpecVars + l] );
                        else
                            d = Abc_MaxInt( d, pPerm[i * pSes->nSpecVars + l] );
                    }
1731
                *p++ = d;
1732
                if ( pSes->pArrTimeProfile && pSes->fExtractVerbose )
Mathias Soeken committed
1733
                    printf( "output %d points to gate %d and has normalized delay %d (nArrTimeDelta = %d)\n", h, pSes->nSpecVars + i, d, pSes->nArrTimeDelta );
1734 1735 1736
                for ( l = 0; l < pSes->nSpecVars; ++l )
                {
                    d = ( pSes->nMaxDepth != -1 ) ? pPerm[i * pSes->nSpecVars + l] : 0;
1737
                    if ( pSes->pArrTimeProfile && pSes->fExtractVerbose )
1738
                        printf( "  pin-to-pin arrival time from input %d is %d (pArrTimeProfile = %d)\n", l, d, pSes->pArrTimeProfile[l] );
1739 1740
                    *p++ = d;
                }
1741 1742 1743 1744 1745
            }

    /* pin-to-pin delays */
    if ( pSes->nMaxDepth != -1 )
        ABC_FREE( pPerm );
1746 1747 1748 1749

    /* have we used all the fields? */
    assert( ( p - pSol ) == nSol );

Mathias Soeken committed
1750 1751 1752 1753
    /* printf( "found network: " ); */
    /* Abc_TtPrintHexRev( stdout, Ses_ManDeriveTruth( pSes, pSol, 1 ), pSes->nSpecVars ); */
    /* printf( "\n" ); */

1754 1755 1756 1757 1758 1759 1760
    return pSol;
}

static Abc_Ntk_t * Ses_ManExtractNtk( char const * pSol )
{
    int h, i;
    char const * p;
1761 1762 1763 1764 1765 1766 1767 1768
    Abc_Ntk_t * pNtk;
    Abc_Obj_t * pObj;
    Vec_Ptr_t * pGates, * vNames;
    char pGateTruth[5];
    char * pSopCover;

    pNtk = Abc_NtkAlloc( ABC_NTK_LOGIC, ABC_FUNC_SOP, 1 );
    pNtk->pName = Extra_UtilStrsav( "exact" );
1769
    pGates = Vec_PtrAlloc( pSol[ABC_EXACT_SOL_NVARS] + pSol[ABC_EXACT_SOL_NGATES] );
1770 1771
    pGateTruth[3] = '0';
    pGateTruth[4] = '\0';
1772
    vNames = Abc_NodeGetFakeNames( pSol[ABC_EXACT_SOL_NVARS] + pSol[ABC_EXACT_SOL_NFUNC] );
1773 1774 1775

    /* primary inputs */
    Vec_PtrPush( pNtk->vObjs, NULL );
1776
    for ( i = 0; i < pSol[ABC_EXACT_SOL_NVARS]; ++i )
1777 1778 1779 1780 1781 1782 1783
    {
        pObj = Abc_NtkCreatePi( pNtk );
        Abc_ObjAssignName( pObj, (char*)Vec_PtrEntry( vNames, i ), NULL );
        Vec_PtrPush( pGates, pObj );
    }

    /* gates */
1784 1785
    p = pSol + 3;
    for ( i = 0; i < pSol[ABC_EXACT_SOL_NGATES]; ++i )
1786
    {
1787 1788 1789 1790
        pGateTruth[2] = '0' + ( *p & 1 );
        pGateTruth[1] = '0' + ( ( *p >> 1 ) & 1 );
        pGateTruth[0] = '0' + ( ( *p >> 2 ) & 1 );
        ++p;
1791

1792 1793
        assert( *p == 2 ); /* binary gate */
        ++p;
1794 1795 1796 1797 1798 1799 1800

        pSopCover = Abc_SopFromTruthBin( pGateTruth );
        pObj = Abc_NtkCreateNode( pNtk );
        pObj->pData = Abc_SopRegister( (Mem_Flex_t*)pNtk->pManFunc, pSopCover );
        Vec_PtrPush( pGates, pObj );
        ABC_FREE( pSopCover );

1801 1802
        Abc_ObjAddFanin( pObj, (Abc_Obj_t *)Vec_PtrEntry( pGates, *p++ ) );
        Abc_ObjAddFanin( pObj, (Abc_Obj_t *)Vec_PtrEntry( pGates, *p++ ) );
1803 1804 1805
    }

    /* outputs */
1806
    for ( h = 0; h < pSol[ABC_EXACT_SOL_NFUNC]; ++h )
1807 1808
    {
        pObj = Abc_NtkCreatePo( pNtk );
1809 1810 1811 1812 1813
        Abc_ObjAssignName( pObj, (char*)Vec_PtrEntry( vNames, pSol[ABC_EXACT_SOL_NVARS] + h ), NULL );
        if ( Abc_LitIsCompl( *p ) )
            Abc_ObjAddFanin( pObj, Abc_NtkCreateNodeInv( pNtk, (Abc_Obj_t *)Vec_PtrEntry( pGates, pSol[ABC_EXACT_SOL_NVARS] + Abc_Lit2Var( *p ) ) ) );
        else
            Abc_ObjAddFanin( pObj, (Abc_Obj_t *)Vec_PtrEntry( pGates, pSol[ABC_EXACT_SOL_NVARS] + Abc_Lit2Var( *p ) ) );
1814
        p += ( 2 + pSol[ABC_EXACT_SOL_NVARS] );
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
    }
    Abc_NodeFreeNames( vNames );

    Vec_PtrFree( pGates );

    if ( !Abc_NtkCheck( pNtk ) )
        printf( "Ses_ManExtractSolution(): Network check has failed.\n" );

    return pNtk;
}

1826
static Gia_Man_t * Ses_ManExtractGia( char const * pSol )
1827
{
1828 1829
    int h, i;
    char const * p;
1830 1831 1832 1833 1834
    Gia_Man_t * pGia;
    Vec_Int_t * pGates;
    Vec_Ptr_t * vNames;
    int nObj, nChild1, nChild2, fChild1Comp, fChild2Comp;

1835
    pGia = Gia_ManStart( pSol[ABC_EXACT_SOL_NVARS] + pSol[ABC_EXACT_SOL_NGATES] + pSol[ABC_EXACT_SOL_NFUNC] + 1 );
1836 1837 1838
    pGia->nConstrs = 0;
    pGia->pName = Extra_UtilStrsav( "exact" );

1839 1840
    pGates = Vec_IntAlloc( pSol[ABC_EXACT_SOL_NVARS] + pSol[ABC_EXACT_SOL_NGATES] );
    vNames = Abc_NodeGetFakeNames( pSol[ABC_EXACT_SOL_NVARS] + pSol[ABC_EXACT_SOL_NFUNC] );
1841 1842

    /* primary inputs */
1843 1844
    pGia->vNamesIn = Vec_PtrStart( pSol[ABC_EXACT_SOL_NVARS] );
    for ( i = 0; i < pSol[ABC_EXACT_SOL_NVARS]; ++i )
1845 1846 1847
    {
        nObj = Gia_ManAppendCi( pGia );
        Vec_IntPush( pGates, nObj );
1848
        Vec_PtrSetEntry( pGia->vNamesIn, i, Extra_UtilStrsav( (const char*)Vec_PtrEntry( vNames, i ) ) );
1849 1850 1851
    }

    /* gates */
1852 1853
    p = pSol + 3;
    for ( i = 0; i < pSol[ABC_EXACT_SOL_NGATES]; ++i )
1854
    {
1855 1856 1857 1858
        assert( p[1] == 2 );
        nChild1 = Vec_IntEntry( pGates, p[2] );
        nChild2 = Vec_IntEntry( pGates, p[3] );
        fChild1Comp = fChild2Comp = 0;
1859

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
        if ( *p & 1 )
        {
            nChild1 = Abc_LitNot( nChild1 );
            fChild1Comp = 1;
        }
        if ( ( *p >> 1 ) & 1 )
        {
            nChild2 = Abc_LitNot( nChild2 );
            fChild2Comp = 1;
        }
        nObj = Gia_ManAppendAnd( pGia, nChild1, nChild2 );
        if ( fChild1Comp && fChild2Comp )
        {
            assert( ( *p >> 2 ) & 1 );
            nObj = Abc_LitNot( nObj );
        }
1876

1877
        Vec_IntPush( pGates, nObj );
1878

1879
        p += 4;
1880 1881 1882
    }

    /* outputs */
1883
    pGia->vNamesOut = Vec_PtrStart( pSol[ABC_EXACT_SOL_NFUNC] );
1884
    for ( h = 0; h < pSol[ABC_EXACT_SOL_NFUNC]; ++h )
1885
    {
1886 1887 1888 1889
        nObj = Vec_IntEntry( pGates, pSol[ABC_EXACT_SOL_NVARS] + Abc_Lit2Var( *p ) );
        if ( Abc_LitIsCompl( *p ) )
            nObj = Abc_LitNot( nObj );
        Gia_ManAppendCo( pGia, nObj );
1890
        Vec_PtrSetEntry( pGia->vNamesOut, h, Extra_UtilStrsav( (const char*)Vec_PtrEntry( vNames, pSol[ABC_EXACT_SOL_NVARS] + h ) ) );
1891
        p += ( 2 + pSol[ABC_EXACT_SOL_NVARS] );
1892 1893 1894 1895 1896 1897 1898 1899
    }
    Abc_NodeFreeNames( vNames );

    Vec_IntFree( pGates );

    return pGia;
}

1900 1901 1902 1903 1904 1905 1906 1907
/**Function*************************************************************

  Synopsis    [Debug.]

***********************************************************************/
static void Ses_ManPrintRuntime( Ses_Man_t * pSes )
{
    printf( "Runtime breakdown:\n" );
1908 1909 1910 1911 1912 1913
    ABC_PRTP( "Sat     ",  pSes->timeSat,      pSes->timeTotal );
    ABC_PRTP( " Sat    ",  pSes->timeSatSat,   pSes->timeTotal );
    ABC_PRTP( " Unsat  ",  pSes->timeSatUnsat, pSes->timeTotal );
    ABC_PRTP( " Undef  ",  pSes->timeSatUndef, pSes->timeTotal );
    ABC_PRTP( "Instance", pSes->timeInstance,  pSes->timeTotal );
    ABC_PRTP( "ALL     ",  pSes->timeTotal,    pSes->timeTotal );
1914 1915
}

1916 1917 1918 1919 1920 1921 1922 1923
static inline void Ses_ManPrintFuncs( Ses_Man_t * pSes )
{
    int h;

    printf( "find optimum circuit for %d %d-variable functions:\n", pSes->nSpecFunc, pSes->nSpecVars );
    for ( h = 0; h < pSes->nSpecFunc; ++h )
    {
        printf( "  func %d: ", h + 1 );
1924
        Abc_TtPrintHexRev( stdout, &pSes->pSpec[h << 2], pSes->nSpecVars );
1925 1926
        printf( "\n" );
    }
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938

    if ( pSes->nMaxDepth != -1 )
    {
        printf( "  max depth = %d\n", pSes->nMaxDepth );
        if ( pSes->pArrTimeProfile )
        {
            printf( "  arrival times =" );
            for ( h = 0; h < pSes->nSpecVars; ++h )
                printf( " %d", pSes->pArrTimeProfile[h] );
            printf( "\n" );
        }
    }
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
static inline void Ses_ManPrintVars( Ses_Man_t * pSes )
{
    int h, i, j, k, p, q, t;

    for ( i = 0; i < pSes->nGates; ++i )
        for ( t = 0; t < pSes->nRows; ++t )
            printf( "x(%d, %d) : %d\n", i, t, Ses_ManSimVar( pSes, i, t ) );

    for ( h = 0; h < pSes->nSpecFunc; ++h )
        for ( i = 0; i < pSes->nGates; ++i )
            printf( "h(%d, %d) : %d\n", h, i, Ses_ManOutputVar( pSes, h, i ) );

    for ( i = 0; i < pSes->nGates; ++i )
        for ( p = 0; p <= 1; ++p )
            for ( q = 0; q <= 1; ++ q)
            {
                if ( p == 0 && q == 0 ) { continue; }
                printf( "f(%d, %d, %d) : %d\n", i, p, q, Ses_ManGateVar( pSes, i, p, q ) );
            }

    for ( i = 0; i < pSes->nGates; ++i )
        for ( j = 0; j < pSes->nSpecVars + i; ++j )
            for ( k = j + 1; k < pSes->nSpecVars + i; ++k )
                printf( "s(%d, %d, %d) : %d\n", i, j, k, Ses_ManSelectVar( pSes, i, j, k ) );

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    if ( pSes->nMaxDepth > 0 )
        for ( i = 0; i < pSes->nGates; ++i )
            for ( j = 0; j <= i; ++j )
                printf( "d(%d, %d) : %d\n", i, j, Ses_ManDepthVar( pSes, i, j ) );

}

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

  Synopsis    [Synthesis algorithm.]

***********************************************************************/
Mathias Soeken committed
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
static void Ses_ManComputeMaxGates( Ses_Man_t * pSes )
{
    int s = 1, lvl = pSes->nMaxDepth, avail = pSes->nSpecVars, l;

    pSes->nMaxGates = 0;

    /* s is the number of gates we have in the current level */
    while ( s && /* while there are nodes to branch from */
            lvl && /* while we are at some level */
            avail * 2 > s /* while there are still enough available nodes (heuristic) */ )
    {
        /* erase from s if we have arriving nodes */
        for ( l = 0; l < pSes->nSpecVars; ++l )
            if ( pSes->pArrTimeProfile[l] == lvl )
            {
                --s;
                --avail;
            }

        --lvl;
        pSes->nMaxGates += s;
        s *= 2;
    }
}

Mathias Soeken committed
2003 2004
// returns 0, if current max depth and arrival times are not consistent
static int Ses_CheckDepthConsistency( Ses_Man_t * pSes )
2005
{
Mathias Soeken committed
2006
    int l, i, fAdded, nLevel;
2007
    int fMaxGatesLevel2 = 1;
2008

Mathias Soeken committed
2009
    Vec_IntClear( pSes->vStairDecVars );
Mathias Soeken committed
2010 2011 2012
    pSes->fDecStructure = 0;

    for ( l = 0; l < pSes->nSpecVars; ++l )
2013
    {
Mathias Soeken committed
2014
        if ( pSes->pArrTimeProfile[l] >= pSes->nMaxDepth )
2015
        {
Mathias Soeken committed
2016
            if ( pSes->fReasonVerbose )
Mathias Soeken committed
2017 2018 2019
                printf( "give up due to impossible arrival time (depth = %d, input = %d, arrival time = %d)", pSes->nMaxDepth, l, pSes->pArrTimeProfile[l] );
            return 0;
        }
Mathias Soeken committed
2020
        else if ( pSes->nSpecFunc == 1 && pSes->pArrTimeProfile[l] + 1 == pSes->nMaxDepth )
Mathias Soeken committed
2021 2022
        {
            if ( ( pSes->fDecStructure == 1 && pSes->nSpecVars > 2 ) || pSes->fDecStructure == 2 )
2023
            {
Mathias Soeken committed
2024
                if ( pSes->fReasonVerbose )
Mathias Soeken committed
2025
                    printf( "give up due to impossible decomposition (depth = %d, input = %d, arrival time = %d)", pSes->nMaxDepth, l, pSes->pArrTimeProfile[l] );
2026 2027
                return 0;
            }
Mathias Soeken committed
2028 2029 2030 2031

            pSes->fDecStructure++;

            /* A subset B <=> A and B = A */
Mathias Soeken committed
2032 2033 2034 2035 2036 2037
            if ( !( ( pSes->pDecVars >> l ) & 1 ) )
            {
                if ( pSes->fReasonVerbose )
                    printf( "give up due to impossible decomposition (depth = %d, input = %d, arrival time = %d)", pSes->nMaxDepth, l, pSes->pArrTimeProfile[l] );
                return 0;
            }
Mathias Soeken committed
2038 2039
        }
    }
2040

Mathias Soeken committed
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    /* more complicated decomposition */
    if ( pSes->fDecStructure )
    {
        nLevel = 1;
        while ( 1 )
        {
            fAdded = 0;

            for ( l = 0; l < pSes->nSpecVars; ++l )
                if ( pSes->pArrTimeProfile[l] + nLevel == pSes->nMaxDepth )
                {
                    if ( fAdded )
                    {
Mathias Soeken committed
2054
                        assert( nLevel == Vec_IntSize( pSes->vStairDecVars ) );
Mathias Soeken committed
2055 2056 2057 2058 2059 2060 2061
                        if ( fAdded > 1 || ( nLevel + 1 < pSes->nSpecVars ) )
                        {
                            if ( pSes->fReasonVerbose )
                                printf( "give up due to impossible decomposition at level %d", nLevel );
                            return 0;
                        }
                    }
Mathias Soeken committed
2062 2063 2064 2065
                    else
                    {
                        Vec_IntPush( pSes->vStairDecVars, l );
                    }
Mathias Soeken committed
2066 2067 2068 2069 2070 2071 2072
                    fAdded++;
                }

            if ( !fAdded ) break;
            ++nLevel;
        }

Mathias Soeken committed
2073
        if ( Vec_IntSize( pSes->vStairDecVars ) && !Abc_TtIsStairDecomposable( pSes->pSpec, pSes->nSpecWords, Vec_IntArray( pSes->vStairDecVars ), Vec_IntSize( pSes->vStairDecVars ), pSes->pStairDecFunc ) )
Mathias Soeken committed
2074 2075 2076 2077
        {
            if ( pSes->fReasonVerbose )
            {
                printf( "give up due to impossible stair decomposition at level %d: ", nLevel );
Mathias Soeken committed
2078
                Vec_IntPrint( pSes->vStairDecVars );
Mathias Soeken committed
2079 2080 2081 2082 2083
            }
            return 0;
        }
    }

Mathias Soeken committed
2084 2085 2086 2087 2088
    /* check if depth's match with structure at second level from top */
    if ( pSes->fDecStructure )
        fMaxGatesLevel2 = ( pSes->nSpecVars == 3 ) ? 2 : 1;
    else
        fMaxGatesLevel2 = ( pSes->nSpecVars == 4 ) ? 4 : 3;
2089

Mathias Soeken committed
2090 2091 2092 2093 2094
    i = 0;
    for ( l = 0; l < pSes->nSpecVars; ++l )
        if ( pSes->pArrTimeProfile[l] + 2 == pSes->nMaxDepth )
            if ( ++i > fMaxGatesLevel2 )
            {
Mathias Soeken committed
2095
                if ( pSes->fReasonVerbose )
Mathias Soeken committed
2096 2097
                    printf( "give up due to impossible decomposition at second level (depth = %d, input = %d, arrival time = %d)", pSes->nMaxDepth, l, pSes->pArrTimeProfile[l] );
                return 0;
2098 2099
            }

Mathias Soeken committed
2100 2101 2102
    /* check if depth's match with structure at third level from top */
    if ( pSes->nSpecVars > 4 && pSes->fDecStructure && i == 1 ) /* we have f = AND(x_i, AND(x_j, g)) (x_i and x_j may be complemented) */
    {
2103 2104
        i = 0;
        for ( l = 0; l < pSes->nSpecVars; ++l )
Mathias Soeken committed
2105 2106
            if ( pSes->pArrTimeProfile[l] + 3 == pSes->nMaxDepth )
                if ( ++i > 1 )
2107
                {
Mathias Soeken committed
2108
                    if ( pSes->fReasonVerbose )
Mathias Soeken committed
2109
                        printf( "give up due to impossible decomposition at third level (depth = %d, input = %d, arrival time = %d)", pSes->nMaxDepth, l, pSes->pArrTimeProfile[l] );
2110 2111 2112 2113
                    return 0;
                }
    }

Mathias Soeken committed
2114 2115 2116 2117 2118 2119 2120
    return 1;
}

// returns 0, if current max depth and #gates are not consistent
static int Ses_CheckGatesConsistency( Ses_Man_t * pSes, int nGates )
{
    /* give up if number of gates is impossible for given depth */
Mathias Soeken committed
2121
    if ( pSes->nMaxDepth != -1 && nGates >= ( 1 << pSes->nMaxDepth ) )
Mathias Soeken committed
2122
    {
Mathias Soeken committed
2123
        if ( pSes->fReasonVerbose )
Mathias Soeken committed
2124 2125 2126 2127
            printf( "give up due to impossible depth (depth = %d, gates = %d)", pSes->nMaxDepth, nGates );
        return 0;
    }

Mathias Soeken committed
2128 2129 2130 2131 2132 2133 2134 2135
    /* give up if number of gates is impossible for given depth and arrival times */
    if ( pSes->nMaxDepth != -1 && pSes->pArrTimeProfile && nGates > pSes->nMaxGates )
    {
        if ( pSes->fReasonVerbose )
            printf( "give up due to impossible depth and arrival times (depth = %d, gates = %d)", pSes->nMaxDepth, nGates );
        return 0;
    }

Mathias Soeken committed
2136 2137
    if ( pSes->fDecStructure && nGates >= ( 1 << ( pSes->nMaxDepth - 1 ) ) + 1 )
    {
Mathias Soeken committed
2138
        if ( pSes->fReasonVerbose )
Mathias Soeken committed
2139 2140 2141 2142 2143 2144 2145
            printf( "give up due to impossible depth in AND-dec structure (depth = %d, gates = %d)", pSes->nMaxDepth, nGates );
        return 0;
    }

    /* give up if number of gates gets practically too large */
    if ( nGates >= ( 1 << pSes->nSpecVars ) )
    {
Mathias Soeken committed
2146
        if ( pSes->fReasonVerbose )
Mathias Soeken committed
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
            printf( "give up due to impossible number of gates" );
        return 0;
    }

    return 1;
}

static void Abc_ExactCopyDepthAndArrivalTimes( int nVars, int nDepthFrom, int * nDepthTo, int * pTimesFrom, int * pTimesTo )
{
    int l;

    *nDepthTo = nDepthFrom;
    for ( l = 0; l < nVars; ++l )
        pTimesTo[l] = pTimesFrom[l];
}

static void Ses_ManStoreDepthAndArrivalTimes( Ses_Man_t * pSes )
{
    if ( pSes->nMaxDepth == -1 ) return;
    Abc_ExactCopyDepthAndArrivalTimes( pSes->nSpecVars, pSes->nMaxDepth, &pSes->nMaxDepthTmp, pSes->pArrTimeProfile, pSes->pArrTimeProfileTmp );
}

static void Ses_ManRestoreDepthAndArrivalTimes( Ses_Man_t * pSes )
{
    if ( pSes->nMaxDepth == -1 ) return;
    Abc_ExactCopyDepthAndArrivalTimes( pSes->nSpecVars, pSes->nMaxDepthTmp, &pSes->nMaxDepth, pSes->pArrTimeProfileTmp, pSes->pArrTimeProfile );
}

static void Abc_ExactAdjustDepthAndArrivalTimes( int nVars, int nGates, int nDepthFrom, int * nDepthTo, int * pTimesFrom, int * pTimesTo, int nTimesMax )
{
    int l;

    *nDepthTo = Abc_MinInt( nDepthFrom, nGates );
    for ( l = 0; l < nVars; ++l )
        pTimesTo[l] = Abc_MinInt( pTimesFrom[l], Abc_MaxInt( 0, nGates - 1 - nTimesMax + pTimesFrom[l] ) );
}

static void Ses_AdjustDepthAndArrivalTimes( Ses_Man_t * pSes, int nGates )
{
    Abc_ExactAdjustDepthAndArrivalTimes( pSes->nSpecVars, nGates, pSes->nMaxDepthTmp, &pSes->nMaxDepth, pSes->pArrTimeProfileTmp, pSes->pArrTimeProfile, pSes->nArrTimeMax - 1 );
}

Mathias Soeken committed
2189 2190
/* return: (2: continue, 1: found, 0: gave up) */
static int Ses_ManFindNetworkExact( Ses_Man_t * pSes, int nGates )
Mathias Soeken committed
2191
{
Mathias Soeken committed
2192
    int f, fSat;
Mathias Soeken committed
2193 2194
    abctime timeStart;

Mathias Soeken committed
2195 2196
    /* solve */
    timeStart = Abc_Clock();
Mathias Soeken committed
2197 2198
    Vec_IntClear( pSes->vPolar );
    Vec_IntClear( pSes->vAssump );
Mathias Soeken committed
2199
    Ses_ManCreateVars( pSes, nGates );
Mathias Soeken committed
2200 2201 2202 2203 2204 2205 2206 2207 2208

    if ( pSes->nMaxDepth != -1 )
    {
        f = Ses_ManCreateDepthClauses( pSes );
        pSes->timeInstance += ( Abc_Clock() - timeStart );
        if ( !f ) return 2; /* proven UNSAT while creating clauses */
    }

    sat_solver_set_polarity( pSes->pSat, Vec_IntArray( pSes->vPolar ), Vec_IntSize( pSes->vPolar ) );
Mathias Soeken committed
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236

    /* first solve */
    fSat = Ses_ManSolve( pSes );
    if ( fSat == 0 )
        return 2; /* UNSAT, continue with next # of gates */
    else if ( fSat == 2 )
    {
        pSes->fHitResLimit = 1;
        return 0;
    }

    timeStart = Abc_Clock();
    f = Ses_ManCreateClauses( pSes );
    pSes->timeInstance += ( Abc_Clock() - timeStart );
    if ( !f ) return 2; /* proven UNSAT while creating clauses */

    fSat = Ses_ManSolve( pSes );
    if ( fSat == 1 )
        return 1;
    else if ( fSat == 2 )
    {
        pSes->fHitResLimit = 1;
        return 0;
    }

    return 2; /* UNSAT continue */
}

2237
// is there a network for a given number of gates
Mathias Soeken committed
2238
/* return: (3: impossible, 2: continue, 1: found, 0: gave up) */
2239
static int Ses_ManFindNetworkExactCEGAR( Ses_Man_t * pSes, int nGates, char ** pSol )
Mathias Soeken committed
2240
{
Mathias Soeken committed
2241
    int fRes, iMint, fSat, i;
Mathias Soeken committed
2242 2243
    word pTruth[4];

2244
    /* debug */
Mathias Soeken committed
2245
    Abc_DebugErase( pSes->nDebugOffset + ( nGates > 10 ? 5 : 4 ), pSes->fVeryVerbose );
2246
    Abc_DebugPrintIntInt( " (%d/%d)", nGates, pSes->nMaxGates, pSes->fVeryVerbose );
Mathias Soeken committed
2247

2248 2249
    /* do #gates and max depth allow for a network? */
    if ( !Ses_CheckGatesConsistency( pSes, nGates ) )
Mathias Soeken committed
2250
        return 3;
2251

Mathias Soeken committed
2252 2253 2254
    for ( i = 0; i < pSes->nRandRowAssigns; ++i )
        Abc_TtSetBit( pSes->pTtValues, rand() % pSes->nRows );

2255 2256 2257 2258
    fRes = Ses_ManFindNetworkExact( pSes, nGates );
    if ( fRes != 1 ) return fRes;

    while ( true )
Mathias Soeken committed
2259
    {
2260 2261 2262 2263
        *pSol = Ses_ManExtractSolution( pSes );
        Abc_TtXor( pTruth, Ses_ManDeriveTruth( pSes, *pSol, 0 ), pSes->pSpec, pSes->nSpecWords, 0 );
        iMint = Abc_TtFindFirstBit( pTruth, pSes->nSpecVars );

Mathias Soeken committed
2264
        if ( iMint == -1 || (pSes->nSpecVars < 6 && iMint > pSes->nRows) )
2265 2266 2267 2268 2269 2270
        {
            assert( fRes == 1 );
            return 1;
        }
        ABC_FREE( *pSol );

Mathias Soeken committed
2271 2272
        if ( pSes->fKeepRowAssigns )
            Abc_TtSetBit( pSes->pTtValues, iMint - 1 );
2273 2274 2275 2276 2277 2278
        if ( !Ses_ManCreateTruthTableClause( pSes, iMint - 1 ) ) /* UNSAT, continue */
            return 2;

        if ( ( fSat = Ses_ManSolve( pSes ) ) == 1 ) continue;

        return ( fSat == 2 ) ? 0 : 2;
Mathias Soeken committed
2279
    }
2280 2281 2282 2283 2284 2285 2286
}

// find minimum size by increasing the number of gates
static char * Ses_ManFindMinimumSizeBottomUp( Ses_Man_t * pSes )
{
    int nGates = pSes->nStartGates, fRes;
    char * pSol = NULL;
Mathias Soeken committed
2287

2288 2289 2290 2291 2292 2293
    /* store whether call was unsuccessful due to resource limit and not due to impossible constraint */
    pSes->fHitResLimit = 0;

    pSes->nDebugOffset = pSes->nMaxGates >= 10 ? 3 : 2;

    /* adjust number of gates if there is a stair decomposition */
Mathias Soeken committed
2294 2295 2296
    if ( Vec_IntSize( pSes->vStairDecVars ) )
        nGates = Abc_MaxInt( nGates, Vec_IntSize( pSes->vStairDecVars ) - 1 );

Mathias Soeken committed
2297 2298
    //Ses_ManStoreDepthAndArrivalTimes( pSes );

Mathias Soeken committed
2299 2300
    memset( pSes->pTtValues, 0, 4 * sizeof( word ) );

Mathias Soeken committed
2301 2302
    Abc_DebugPrintIntInt( " (%d/%d)", nGates, pSes->nMaxGates, pSes->fVeryVerbose );

2303 2304 2305
    while ( true )
    {
        ++nGates;
2306

2307
        fRes = Ses_ManFindNetworkExactCEGAR( pSes, nGates, &pSol );
Mathias Soeken committed
2308

2309
        if ( fRes == 0 )
2310
        {
2311
            pSes->fHitResLimit = 1;
Mathias Soeken committed
2312
            break;
2313
        }
Mathias Soeken committed
2314
        else if ( fRes == 1 || fRes == 3 )
2315 2316
            break;
    }
2317

2318
    Abc_DebugErase( pSes->nDebugOffset + ( nGates >= 10 ? 5 : 4 ), pSes->fVeryVerbose );
2319

Mathias Soeken committed
2320
    return pSol;
2321
}
Mathias Soeken committed
2322

2323 2324 2325 2326
static char * Ses_ManFindMinimumSizeTopDown( Ses_Man_t * pSes, int nMinGates )
{
    int nGates = pSes->nMaxGates, fRes;
    char * pSol = NULL, * pSol2 = NULL;
Mathias Soeken committed
2327

2328
    pSes->fHitResLimit = 0;
Mathias Soeken committed
2329

Mathias Soeken committed
2330 2331
    Abc_DebugPrintIntInt( " (%d/%d)", nGates, pSes->nMaxGates, pSes->fVeryVerbose );

2332 2333 2334
    while ( true )
    {
        fRes = Ses_ManFindNetworkExactCEGAR( pSes, nGates, &pSol2 );
2335

2336 2337 2338
        if ( fRes == 0 )
        {
            pSes->fHitResLimit = 1;
Mathias Soeken committed
2339 2340
            break;
        }
Mathias Soeken committed
2341
        else if ( fRes == 2 || fRes == 3 )
2342 2343 2344
            break;

        pSol = pSol2;
Mathias Soeken committed
2345

2346
        if ( nGates == nMinGates )
Mathias Soeken committed
2347
            break;
Mathias Soeken committed
2348

2349 2350
        --nGates;
    }
Mathias Soeken committed
2351

Mathias Soeken committed
2352 2353
    Abc_DebugErase( pSes->nDebugOffset + ( nGates >= 10 ? 5 : 4 ), pSes->fVeryVerbose );

2354 2355
    return pSol;
}
Mathias Soeken committed
2356

2357 2358
static char * Ses_ManFindMinimumSize( Ses_Man_t * pSes )
{
Mathias Soeken committed
2359
    char * pSol = NULL;
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    int i = pSes->nStartGates + 1, fRes;

    /* if more than one function, no CEGAR */
    if ( pSes->nSpecFunc > 1 )
    {
      while ( true )
      {
        if ( pSes->fVerbose )
        {
          printf( "try with %d gates\n", i );
        }

        memset( pSes->pTtValues, ~0, 4 * sizeof( word ) );
        fRes = Ses_ManFindNetworkExact( pSes, i++ );
        if ( fRes == 2 ) continue;
        if ( fRes == 0 ) break;

        pSol = Ses_ManExtractSolution( pSes );
        break;
      }

      return pSol;
    }
Mathias Soeken committed
2383

2384 2385 2386 2387 2388 2389
    /* do the arrival times allow for a network? */
    if ( pSes->nMaxDepth != -1 && pSes->pArrTimeProfile )
    {
        if ( !Ses_CheckDepthConsistency( pSes ) )
            return 0;
        Ses_ManComputeMaxGates( pSes );
2390
    }
2391

2392
    pSol = Ses_ManFindMinimumSizeBottomUp( pSes );
Mathias Soeken committed
2393

Mathias Soeken committed
2394
    if ( !pSol && pSes->nMaxDepth != -1 && pSes->fHitResLimit && pSes->nGates != pSes->nMaxGates )
2395 2396 2397
        return Ses_ManFindMinimumSizeTopDown( pSes, pSes->nGates + 1 );
    else
        return pSol;
2398 2399
}

2400

2401 2402 2403 2404
/**Function*************************************************************

  Synopsis    [Find minimum size networks with a SAT solver.]

2405
  Description [If nMaxDepth is -1, then depth constraints are ignored.
2406 2407
               If nMaxDepth is not -1, one can set pArrTimeProfile which should have the length of nVars.
               One can ignore pArrTimeProfile by setting it to NULL.]
2408 2409 2410 2411 2412 2413

  SideEffects []

  SeeAlso     []

***********************************************************************/
2414
Abc_Ntk_t * Abc_NtkFindExact( word * pTruth, int nVars, int nFunc, int nMaxDepth, int * pArrTimeProfile, int nBTLimit, int nStartGates, int fVerbose )
2415 2416
{
    Ses_Man_t * pSes;
2417
    char * pSol;
2418 2419
    Abc_Ntk_t * pNtk = NULL;
    abctime timeStart;
2420 2421

    /* some checks */
2422 2423 2424
    assert( nVars >= 2 && nVars <= 8 );

    timeStart = Abc_Clock();
2425

2426
    pSes = Ses_ManAlloc( pTruth, nVars, nFunc, nMaxDepth, pArrTimeProfile, 0, nBTLimit, fVerbose );
2427
    pSes->nStartGates = nStartGates;
Mathias Soeken committed
2428 2429
    pSes->fReasonVerbose = 0;
    pSes->fSatVerbose = 0;
2430
    if ( fVerbose )
2431 2432
        Ses_ManPrintFuncs( pSes );

2433
    if ( ( pSol = Ses_ManFindMinimumSize( pSes ) ) != NULL )
2434 2435 2436 2437
    {
        pNtk = Ses_ManExtractNtk( pSol );
        ABC_FREE( pSol );
    }
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449

    pSes->timeTotal = Abc_Clock() - timeStart;

    if ( fVerbose )
        Ses_ManPrintRuntime( pSes );

    /* cleanup */
    Ses_ManClean( pSes );

    return pNtk;
}

2450
Gia_Man_t * Gia_ManFindExact( word * pTruth, int nVars, int nFunc, int nMaxDepth, int * pArrTimeProfile, int nBTLimit, int nStartGates, int fVerbose )
2451 2452
{
    Ses_Man_t * pSes;
2453
    char * pSol;
2454 2455 2456 2457 2458 2459 2460
    Gia_Man_t * pGia = NULL;
    abctime timeStart;

    /* some checks */
    assert( nVars >= 2 && nVars <= 8 );

    timeStart = Abc_Clock();
2461

2462
    pSes = Ses_ManAlloc( pTruth, nVars, nFunc, nMaxDepth, pArrTimeProfile, 1, nBTLimit, fVerbose );
2463
    pSes->nStartGates = nStartGates;
2464
    pSes->fVeryVerbose = 1;
2465
    pSes->fExtractVerbose = 0;
Mathias Soeken committed
2466 2467
    pSes->fSatVerbose = 0;
    pSes->fReasonVerbose = 1;
2468 2469 2470
    if ( fVerbose )
        Ses_ManPrintFuncs( pSes );

2471
    if ( ( pSol = Ses_ManFindMinimumSize( pSes ) ) != NULL )
2472 2473 2474 2475
    {
        pGia = Ses_ManExtractGia( pSol );
        ABC_FREE( pSol );
    }
2476 2477

    pSes->timeTotal = Abc_Clock() - timeStart;
2478 2479 2480 2481 2482 2483 2484

    if ( fVerbose )
        Ses_ManPrintRuntime( pSes );

    /* cleanup */
    Ses_ManClean( pSes );

2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
    return pGia;
}

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

  Synopsis    [Some test cases.]

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

Abc_Ntk_t * Abc_NtkFromTruthTable( word * pTruth, int nVars )
{
    Abc_Ntk_t * pNtk;
    Mem_Flex_t * pMan;
    char * pSopCover;

    pMan = Mem_FlexStart();
    pSopCover = Abc_SopCreateFromTruth( pMan, nVars, (unsigned*)pTruth );
    pNtk = Abc_NtkCreateWithNode( pSopCover );
    Abc_NtkShortNames( pNtk );
    Mem_FlexStop( pMan, 0 );

2506 2507 2508
    return pNtk;
}

2509 2510 2511 2512 2513 2514
void Abc_ExactTestSingleOutput( int fVerbose )
{
    extern void Abc_NtkCecSat( Abc_Ntk_t * pNtk1, Abc_Ntk_t * pNtk2, int nConfLimit, int nInsLimit );

    word pTruth[4] = {0xcafe, 0, 0, 0};
    Abc_Ntk_t * pNtk, * pNtk2, * pNtk3, * pNtk4;
2515
    int pArrTimeProfile[4] = {6, 2, 8, 5};
2516 2517 2518

    pNtk = Abc_NtkFromTruthTable( pTruth, 4 );

2519
    pNtk2 = Abc_NtkFindExact( pTruth, 4, 1, -1, NULL, 0, 0, fVerbose );
2520 2521 2522 2523 2524 2525
    Abc_NtkShortNames( pNtk2 );
    Abc_NtkCecSat( pNtk, pNtk2, 10000, 0 );
    assert( pNtk2 );
    assert( Abc_NtkNodeNum( pNtk2 ) == 6 );
    Abc_NtkDelete( pNtk2 );

2526
    pNtk3 = Abc_NtkFindExact( pTruth, 4, 1, 3, NULL, 0, 0, fVerbose );
2527 2528 2529 2530 2531 2532
    Abc_NtkShortNames( pNtk3 );
    Abc_NtkCecSat( pNtk, pNtk3, 10000, 0 );
    assert( pNtk3 );
    assert( Abc_NtkLevel( pNtk3 ) <= 3 );
    Abc_NtkDelete( pNtk3 );

2533
    pNtk4 = Abc_NtkFindExact( pTruth, 4, 1, 9, pArrTimeProfile, 50000, 0, fVerbose );
2534 2535 2536 2537 2538 2539
    Abc_NtkShortNames( pNtk4 );
    Abc_NtkCecSat( pNtk, pNtk4, 10000, 0 );
    assert( pNtk4 );
    assert( Abc_NtkLevel( pNtk4 ) <= 9 );
    Abc_NtkDelete( pNtk4 );

2540
    assert( !Abc_NtkFindExact( pTruth, 4, 1, 2, NULL, 50000, 0, fVerbose ) );
2541

2542
    assert( !Abc_NtkFindExact( pTruth, 4, 1, 8, pArrTimeProfile, 50000, 0, fVerbose ) );
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552

    Abc_NtkDelete( pNtk );
}

void Abc_ExactTestSingleOutputAIG( int fVerbose )
{
    word pTruth[4] = {0xcafe, 0, 0, 0};
    Abc_Ntk_t * pNtk;
    Gia_Man_t * pGia, * pGia2, * pGia3, * pGia4, * pMiter;
    Cec_ParCec_t ParsCec, * pPars = &ParsCec;
2553
    int pArrTimeProfile[4] = {6, 2, 8, 5};
2554 2555 2556 2557 2558 2559 2560

    Cec_ManCecSetDefaultParams( pPars );

    pNtk = Abc_NtkFromTruthTable( pTruth, 4 );
    Abc_NtkToAig( pNtk );
    pGia = Abc_NtkAigToGia( pNtk, 1 );

2561
    pGia2 = Gia_ManFindExact( pTruth, 4, 1, -1, NULL, 0, 0, fVerbose );
2562 2563 2564 2565 2566
    pMiter = Gia_ManMiter( pGia, pGia2, 0, 1, 0, 0, 1 );
    assert( pMiter );
    Cec_ManVerify( pMiter, pPars );
    Gia_ManStop( pMiter );

2567
    pGia3 = Gia_ManFindExact( pTruth, 4, 1, 3, NULL, 0, 0, fVerbose );
2568 2569 2570 2571 2572
    pMiter = Gia_ManMiter( pGia, pGia3, 0, 1, 0, 0, 1 );
    assert( pMiter );
    Cec_ManVerify( pMiter, pPars );
    Gia_ManStop( pMiter );

2573
    pGia4 = Gia_ManFindExact( pTruth, 4, 1, 9, pArrTimeProfile, 50000, 0, fVerbose );
2574 2575 2576 2577 2578
    pMiter = Gia_ManMiter( pGia, pGia4, 0, 1, 0, 0, 1 );
    assert( pMiter );
    Cec_ManVerify( pMiter, pPars );
    Gia_ManStop( pMiter );

2579
    assert( !Gia_ManFindExact( pTruth, 4, 1, 2, NULL, 50000, 0, fVerbose ) );
2580

2581
    assert( !Gia_ManFindExact( pTruth, 4, 1, 8, pArrTimeProfile, 50000, 0, fVerbose ) );
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596

    Gia_ManStop( pGia );
    Gia_ManStop( pGia2 );
    Gia_ManStop( pGia3 );
    Gia_ManStop( pGia4 );
}

void Abc_ExactTest( int fVerbose )
{
    Abc_ExactTestSingleOutput( fVerbose );
    Abc_ExactTestSingleOutputAIG( fVerbose );

    printf( "\n" );
}

2597

2598 2599 2600 2601 2602 2603 2604 2605 2606
/**Function*************************************************************

  Synopsis    [APIs for integraging with the mapper.]

***********************************************************************/
// may need to have a static pointer to the SAT-based synthesis engine and/or loaded library
// this procedure should return 1, if the engine/library are available, and 0 otherwise
int Abc_ExactIsRunning()
{
2607
    return s_pSesStore != NULL;
2608 2609 2610 2611 2612
}
// this procedure returns the number of inputs of the library
// for example, somebody may try to map into 10-cuts while the library only contains 8-functions
int Abc_ExactInputNum()
{
2613 2614 2615
    return 8;
}
// start exact store manager
2616
void Abc_ExactStart( int nBTLimit, int fMakeAIG, int fVerbose, int fVeryVerbose, const char * pFilename )
2617 2618
{
    if ( !s_pSesStore )
2619 2620
    {
        s_pSesStore = Ses_StoreAlloc( nBTLimit, fMakeAIG, fVerbose );
2621
        s_pSesStore->fVeryVerbose = fVeryVerbose;
2622
        if ( pFilename )
Mathias Soeken committed
2623
        {
2624
            Ses_StoreRead( s_pSesStore, pFilename, 1, 0, 0, 0 );
Mathias Soeken committed
2625 2626 2627 2628

            s_pSesStore->szDBName = ABC_CALLOC( char, strlen( pFilename ) + 1 );
            strcpy( s_pSesStore->szDBName, pFilename );
        }
2629 2630 2631 2632
        if ( s_pSesStore->fVeryVerbose )
        {
            s_pSesStore->pDebugEntries = fopen( "bms.debug", "w" );
        }
2633
    }
2634
    else
2635
        printf( "BMS manager already started\n" );
2636 2637
}
// stop exact store manager
2638
void Abc_ExactStop( const char * pFilename )
2639 2640
{
    if ( s_pSesStore )
2641 2642
    {
        if ( pFilename )
2643 2644 2645
            Ses_StoreWrite( s_pSesStore, pFilename, 1, 0, 0, 0 );
        if ( s_pSesStore->pDebugEntries )
            fclose( s_pSesStore->pDebugEntries );
2646
        Ses_StoreClean( s_pSesStore );
2647
    }
2648
    else
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
        printf( "BMS manager has not been started\n" );
}
// show statistics about store manager
void Abc_ExactStats()
{
    int i;

    if ( !s_pSesStore )
    {
        printf( "BMS manager has not been started\n" );
        return;
    }

Mathias Soeken committed
2662 2663 2664
    printf( "-------------------------------------------------------------------------------------------------------------------------------\n" );
    printf( "                                    0         1         2         3         4         5         6         7         8     total\n" );
    printf( "-------------------------------------------------------------------------------------------------------------------------------\n" );
2665
    printf( "number of considered cuts :" );
Mathias Soeken committed
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pCutCount[i] );
    printf( "%10lu\n", s_pSesStore->nCutCount );
    printf( " - trivial                :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pSynthesizedTrivial[i] );
    printf( "%10lu\n", s_pSesStore->nSynthesizedTrivial );
    printf( " - synth (imp)            :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pSynthesizedImp[i] );
    printf( "%10lu\n", s_pSesStore->nSynthesizedImp );
    printf( " - synth (res)            :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pSynthesizedRL[i] );
    printf( "%10lu\n", s_pSesStore->nSynthesizedRL );
    printf( " - not synth (imp)        :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pUnsynthesizedImp[i] );
    printf( "%10lu\n", s_pSesStore->nUnsynthesizedImp );
    printf( " - not synth (res)        :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pUnsynthesizedRL[i] );
    printf( "%10lu\n", s_pSesStore->nUnsynthesizedRL );
    printf( " - cache hits             :" );
    for ( i = 0; i < 9; ++i )
        printf( "%10lu", s_pSesStore->pCacheHits[i] );
    printf( "%10lu\n", s_pSesStore->nCacheHits );
    printf( "-------------------------------------------------------------------------------------------------------------------------------\n" );
2694
    printf( "number of entries         : %d\n", s_pSesStore->nEntriesCount );
2695
    printf( "number of valid entries   : %d\n", s_pSesStore->nValidEntriesCount );
Mathias Soeken committed
2696
    printf( "number of invalid entries : %d\n", s_pSesStore->nEntriesCount - s_pSesStore->nValidEntriesCount );
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
    printf( "-------------------------------------------------------------------------------------------------------------------------------\n" );
    printf( "number of SAT calls       : %lu\n", s_pSesStore->nSatCalls );
    printf( "number of UNSAT calls     : %lu\n", s_pSesStore->nUnsatCalls );
    printf( "number of UNDEF calls     : %lu\n", s_pSesStore->nUndefCalls );

    printf( "-------------------------------------------------------------------------------------------------------------------------------\n" );
    printf( "Runtime breakdown:\n" );
    ABC_PRTP( "Exact    ", s_pSesStore->timeExact,                          s_pSesStore->timeTotal );
    ABC_PRTP( " Sat     ", s_pSesStore->timeSat,                            s_pSesStore->timeTotal );
    ABC_PRTP( "  Sat    ", s_pSesStore->timeSatSat,                         s_pSesStore->timeTotal );
    ABC_PRTP( "  Unsat  ", s_pSesStore->timeSatUnsat,                       s_pSesStore->timeTotal );
    ABC_PRTP( "  Undef  ", s_pSesStore->timeSatUndef,                       s_pSesStore->timeTotal );
    ABC_PRTP( " Instance", s_pSesStore->timeInstance,                       s_pSesStore->timeTotal );
    ABC_PRTP( "Other    ", s_pSesStore->timeTotal - s_pSesStore->timeExact, s_pSesStore->timeTotal );
    ABC_PRTP( "ALL      ", s_pSesStore->timeTotal,                          s_pSesStore->timeTotal );
2712
}
2713 2714 2715
// this procedure takes TT and input arrival times (pArrTimeProfile) and return the smallest output arrival time;
// it also returns the pin-to-pin delays (pPerm) between each cut leaf and the cut output and the cut area cost (Cost)
// the area cost should not exceed 2048, if the cut is implementable; otherwise, it should be ABC_INFINITY
2716
int Abc_ExactDelayCost( word * pTruth, int nVars, int * pArrTimeProfile, char * pPerm, int * Cost, int AigLevel )
2717
{
Mathias Soeken committed
2718
    int i, nMaxArrival, nDelta, l;
2719
    Ses_Man_t * pSes = NULL;
2720
    char * pSol = NULL, * pSol2 = NULL, * p;
2721
    int pNormalArrTime[8];
2722
    int Delay = ABC_INFINITY, nMaxDepth, fResLimit;
2723
    abctime timeStart = Abc_Clock(), timeStartExact;
2724 2725

    /* some checks */
2726
    if ( nVars < 0 || nVars > 8 )
2727 2728 2729 2730
    {
        printf( "invalid truth table size %d\n", nVars );
        assert( 0 );
    }
2731

Mathias Soeken committed
2732 2733 2734 2735
    /* statistics */
    s_pSesStore->nCutCount++;
    s_pSesStore->pCutCount[nVars]++;

2736 2737
    if ( nVars == 0 )
    {
Mathias Soeken committed
2738 2739 2740
        s_pSesStore->nSynthesizedTrivial++;
        s_pSesStore->pSynthesizedTrivial[0]++;

2741
        *Cost = 0;
2742
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2743 2744 2745 2746 2747
        return 0;
    }

    if ( nVars == 1 )
    {
Mathias Soeken committed
2748 2749 2750
        s_pSesStore->nSynthesizedTrivial++;
        s_pSesStore->pSynthesizedTrivial[1]++;

2751 2752
        *Cost = 0;
        pPerm[0] = (char)0;
2753
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2754 2755 2756
        return pArrTimeProfile[0];
    }

2757 2758 2759
    for ( l = 0; l < nVars; ++l )
        pNormalArrTime[l] = pArrTimeProfile[l];

Mathias Soeken committed
2760
    nDelta = Abc_NormalizeArrivalTimes( pNormalArrTime, nVars, &nMaxArrival );
2761

2762 2763
    *Cost = ABC_INFINITY;

2764
    if ( Ses_StoreGetEntry( s_pSesStore, pTruth, nVars, pNormalArrTime, &pSol ) )
2765
    {
Mathias Soeken committed
2766 2767
        s_pSesStore->nCacheHits++;
        s_pSesStore->pCacheHits[nVars]++;
2768 2769 2770
    }
    else
    {
Mathias Soeken committed
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
        if ( s_pSesStore->fVeryVerbose )
        {
            printf( ANSI_COLOR_CYAN );
            Abc_TtPrintHexRev( stdout, pTruth, nVars );
            printf( ANSI_COLOR_RESET );
            printf( " [%d", pNormalArrTime[0] );
            for ( l = 1; l < nVars; ++l )
                printf( " %d", pNormalArrTime[l] );
            printf( "]@%d:", AigLevel );
            fflush( stdout );
        }

2783
        nMaxDepth = pNormalArrTime[0];
2784
        for ( i = 1; i < nVars; ++i )
2785
            nMaxDepth = Abc_MaxInt( nMaxDepth, pNormalArrTime[i] );
2786
        nMaxDepth += nVars + 1;
2787
        if ( AigLevel != -1 )
Mathias Soeken committed
2788
            nMaxDepth = Abc_MinInt( AigLevel - nDelta, nMaxDepth + nVars + 1 );
2789

2790
        timeStartExact = Abc_Clock();
2791

2792
        pSes = Ses_ManAlloc( pTruth, nVars, 1 /* nSpecFunc */, nMaxDepth, pNormalArrTime, s_pSesStore->fMakeAIG, s_pSesStore->nBTLimit, s_pSesStore->fVerbose );
2793
        pSes->fVeryVerbose = s_pSesStore->fVeryVerbose;
2794
        pSes->pSat = s_pSesStore->pSat;
Mathias Soeken committed
2795
        pSes->nStartGates = nVars - 2;
2796

2797
        while ( pSes->nMaxDepth ) /* there is improvement */
2798
        {
2799 2800
            if ( s_pSesStore->fVeryVerbose )
            {
Mathias Soeken committed
2801
                printf( " %d", pSes->nMaxDepth );
2802 2803 2804
                fflush( stdout );
            }

2805
            if ( ( pSol2 = Ses_ManFindMinimumSize( pSes ) ) != NULL )
2806
            {
2807
                if ( s_pSesStore->fVeryVerbose )
Mathias Soeken committed
2808 2809 2810 2811
                {
                    if ( pSes->nMaxDepth >= 10 ) printf( "\b" );
                    printf( "\b" ANSI_COLOR_GREEN "%d" ANSI_COLOR_RESET, pSes->nMaxDepth );
                }
2812 2813
                if ( pSol )
                    ABC_FREE( pSol );
2814
                pSol = pSol2;
2815 2816 2817
                pSes->nMaxDepth--;
            }
            else
2818 2819
            {
                if ( s_pSesStore->fVeryVerbose )
Mathias Soeken committed
2820 2821 2822 2823
                {
                    if ( pSes->nMaxDepth >= 10 ) printf( "\b" );
                    printf( "\b%s%d" ANSI_COLOR_RESET, pSes->fHitResLimit ? ANSI_COLOR_RED : ANSI_COLOR_YELLOW, pSes->nMaxDepth );
                }
2824
                break;
2825
            }
2826
        }
2827

Mathias Soeken committed
2828
        if ( s_pSesStore->fVeryVerbose )
Mathias Soeken committed
2829
            printf( "        \n" );
Mathias Soeken committed
2830

2831 2832
        /* log unsuccessful case for debugging */
        if ( s_pSesStore->pDebugEntries && pSes->fHitResLimit )
Mathias Soeken committed
2833
            Ses_StorePrintDebugEntry( s_pSesStore, pTruth, nVars, pNormalArrTime, pSes->nMaxDepth, pSol, nVars - 2 );
2834

2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
        pSes->timeTotal = Abc_Clock() - timeStartExact;

        /* statistics */
        s_pSesStore->nSatCalls += pSes->nSatCalls;
        s_pSesStore->nUnsatCalls += pSes->nUnsatCalls;
        s_pSesStore->nUndefCalls += pSes->nUndefCalls;

        s_pSesStore->timeSat += pSes->timeSat;
        s_pSesStore->timeSatSat += pSes->timeSatSat;
        s_pSesStore->timeSatUnsat += pSes->timeSatUnsat;
        s_pSesStore->timeSatUndef += pSes->timeSatUndef;
        s_pSesStore->timeInstance += pSes->timeInstance;
        s_pSesStore->timeExact += pSes->timeTotal;
2848

2849 2850
        /* cleanup (we need to clean before adding since pTruth may have been modified by pSes) */
        fResLimit = pSes->fHitResLimit;
2851
        Ses_ManCleanLight( pSes );
2852 2853

        /* store solution */
2854
        Ses_StoreAddEntry( s_pSesStore, pTruth, nVars, pNormalArrTime, pSol, fResLimit );
2855
    }
2856

2857 2858
    if ( pSol )
    {
2859
        *Cost = pSol[ABC_EXACT_SOL_NGATES];
2860
        p = pSol + 3 + 4 * pSol[ABC_EXACT_SOL_NGATES] + 1;
2861 2862 2863 2864 2865
        Delay = *p++;
        for ( l = 0; l < nVars; ++l )
            pPerm[l] = *p++;
    }

2866 2867 2868 2869 2870 2871 2872 2873 2874
    if ( pSol )
    {
        int Delay2 = 0;
        for ( l = 0; l < nVars; ++l )
        {
            //printf( "%d ", pPerm[l] );
            Delay2 = Abc_MaxInt( Delay2, pArrTimeProfile[l] + pPerm[l] );
        }
        //printf( "  output arrival = %d    recomputed = %d\n", Delay, Delay2 );
2875 2876 2877 2878 2879 2880 2881 2882
        //if ( Delay != Delay2 )
        //{
        //    printf( "^--- BUG!\n" );
        //    assert( 0 );
        //}

        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
        return Delay2;
2883
    }
2884
    else
2885 2886 2887
    {
        assert( *Cost == ABC_INFINITY );

2888 2889 2890
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
        return ABC_INFINITY;
    }
2891
}
2892
// this procedure returns a new node whose output in terms of the given fanins
2893
// has the smallest possible arrival time (in agreement with the above Abc_ExactDelayCost)
2894
Abc_Obj_t * Abc_ExactBuildNode( word * pTruth, int nVars, int * pArrTimeProfile, Abc_Obj_t ** pFanins, Abc_Ntk_t * pNtk )
2895
{
2896
    char * pSol = NULL;
2897 2898
    int i, j, nMaxArrival;
    int pNormalArrTime[8];
2899 2900 2901 2902 2903
    char const * p;
    Abc_Obj_t * pObj;
    Vec_Ptr_t * pGates;
    char pGateTruth[5];
    char * pSopCover;
2904
    abctime timeStart = Abc_Clock();
2905

2906
    if ( nVars == 0 )
2907 2908
    {
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2909
        return (pTruth[0] & 1) ? Abc_NtkCreateNodeConst1(pNtk) : Abc_NtkCreateNodeConst0(pNtk);
2910
    }
2911
    if ( nVars == 1 )
2912 2913
    {
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2914
        return (pTruth[0] & 1) ? Abc_NtkCreateNodeInv(pNtk, pFanins[0]) : Abc_NtkCreateNodeBuf(pNtk, pFanins[0]);
2915
    }
2916

2917 2918 2919
    for ( i = 0; i < nVars; ++i )
        pNormalArrTime[i] = pArrTimeProfile[i];
    Abc_NormalizeArrivalTimes( pNormalArrTime, nVars, &nMaxArrival );
Mathias Soeken committed
2920
    assert( Ses_StoreGetEntry( s_pSesStore, pTruth, nVars, pNormalArrTime, &pSol ) );
2921
    if ( !pSol )
2922 2923
    {
        s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2924
        return NULL;
2925
    }
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936

    assert( pSol[ABC_EXACT_SOL_NVARS] == nVars );
    assert( pSol[ABC_EXACT_SOL_NFUNC] == 1 );

    pGates = Vec_PtrAlloc( nVars + pSol[ABC_EXACT_SOL_NGATES] );
    pGateTruth[3] = '0';
    pGateTruth[4] = '\0';

    /* primary inputs */
    for ( i = 0; i < nVars; ++i )
    {
Mathias Soeken committed
2937
        assert( pFanins[i] );
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
        Vec_PtrPush( pGates, pFanins[i] );
    }

    /* gates */
    p = pSol + 3;
    for ( i = 0; i < pSol[ABC_EXACT_SOL_NGATES]; ++i )
    {
        pGateTruth[2] = '0' + ( *p & 1 );
        pGateTruth[1] = '0' + ( ( *p >> 1 ) & 1 );
        pGateTruth[0] = '0' + ( ( *p >> 2 ) & 1 );
        ++p;

        assert( *p == 2 ); /* binary gate */
        ++p;

2953 2954 2955 2956 2957
        /* invert truth table if we are last gate and inverted */
        if ( i + 1 == pSol[ABC_EXACT_SOL_NGATES] && Abc_LitIsCompl( *( p + 2 ) ) )
            for ( j = 0; j < 4; ++j )
                pGateTruth[j] = ( pGateTruth[j] == '0' ) ? '1' : '0';

2958 2959
        pSopCover = Abc_SopFromTruthBin( pGateTruth );
        pObj = Abc_NtkCreateNode( pNtk );
Mathias Soeken committed
2960
        assert( pObj );
2961 2962 2963 2964 2965 2966 2967 2968 2969
        pObj->pData = Abc_SopRegister( (Mem_Flex_t*)pNtk->pManFunc, pSopCover );
        Vec_PtrPush( pGates, pObj );
        ABC_FREE( pSopCover );

        Abc_ObjAddFanin( pObj, (Abc_Obj_t *)Vec_PtrEntry( pGates, *p++ ) );
        Abc_ObjAddFanin( pObj, (Abc_Obj_t *)Vec_PtrEntry( pGates, *p++ ) );
    }

    /* output */
2970
    pObj = (Abc_Obj_t *)Vec_PtrEntry( pGates, nVars + Abc_Lit2Var( *p ) );
2971 2972 2973

    Vec_PtrFree( pGates );

2974
    s_pSesStore->timeTotal += ( Abc_Clock() - timeStart );
2975
    return pObj;
2976 2977
}

2978 2979 2980 2981 2982 2983 2984 2985
void Abc_ExactStoreTest( int fVerbose )
{
    int i;
    word pTruth[4] = {0xcafe, 0, 0, 0};
    int pArrTimeProfile[4] = {6, 2, 8, 5};
    Abc_Ntk_t * pNtk;
    Abc_Obj_t * pFanins[4];
    Vec_Ptr_t * vNames;
2986 2987
    char pPerm[4] = {0};
    int Cost = 0;
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001

    pNtk = Abc_NtkAlloc( ABC_NTK_LOGIC, ABC_FUNC_SOP, 1 );
    pNtk->pName = Extra_UtilStrsav( "exact" );
    vNames = Abc_NodeGetFakeNames( 4u );

    /* primary inputs */
    Vec_PtrPush( pNtk->vObjs, NULL );
    for ( i = 0; i < 4; ++i )
    {
        pFanins[i] = Abc_NtkCreatePi( pNtk );
        Abc_ObjAssignName( pFanins[i], (char*)Vec_PtrEntry( vNames, i ), NULL );
    }
    Abc_NodeFreeNames( vNames );

3002
    Abc_ExactStart( 10000, 1, fVerbose, 0, NULL );
3003

3004
    assert( !Abc_ExactBuildNode( pTruth, 4, pArrTimeProfile, pFanins, pNtk ) );
3005

3006 3007
    assert( Abc_ExactDelayCost( pTruth, 4, pArrTimeProfile, pPerm, &Cost, 12 ) == 1 );

3008
    assert( Abc_ExactBuildNode( pTruth, 4, pArrTimeProfile, pFanins, pNtk ) );
3009 3010

    (*pArrTimeProfile)++;
3011
    assert( !Abc_ExactBuildNode( pTruth, 4, pArrTimeProfile, pFanins, pNtk ) );
3012
    (*pArrTimeProfile)--;
3013

3014
    Abc_ExactStop( NULL );
Mathias Soeken committed
3015 3016

    Abc_NtkDelete( pNtk );
3017 3018
}

3019 3020 3021 3022 3023 3024
////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


ABC_NAMESPACE_IMPL_END