ifTune.c 50.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/**CFile****************************************************************

  FileName    [ifTune.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [FPGA mapping based on priority cuts.]

  Synopsis    [Library tuning.]

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

  Date        [Ver. 1.0. Started - November 21, 2006.]

  Revision    [$Id: ifTune.c,v 1.00 2006/11/21 00:00:00 alanmi Exp $]

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

#include "if.h"
22 23 24 25
#include "aig/gia/giaAig.h"
#include "sat/bsat/satStore.h"
#include "sat/cnf/cnf.h"
#include "misc/extra/extra.h"
26
#include "bool/kit/kit.h"
27 28 29 30 31 32

ABC_NAMESPACE_IMPL_START

////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////
33 34 35 36
 
#define IFN_INS    11
#define IFN_WRD  (IFN_INS > 6 ? 1 << (IFN_INS-6) : 1)
#define IFN_PAR  1024
37

38 39
// network types
typedef enum { 
40 41 42 43 44 45 46
    IFN_DSD_NONE = 0,              // 0:  unknown
    IFN_DSD_CONST0,                // 1:  constant
    IFN_DSD_VAR,                   // 2:  variable
    IFN_DSD_AND,                   // 3:  AND
    IFN_DSD_XOR,                   // 4:  XOR
    IFN_DSD_MUX,                   // 5:  MUX
    IFN_DSD_PRIME                  // 6:  PRIME
47
} Ifn_DsdType_t;
48

49 50 51 52 53 54 55 56 57 58 59
// object types
static char * Ifn_Symbs[16] = { 
    NULL,                          // 0:  unknown
    "const",                       // 1:  constant
    "var",                         // 2:  variable
    "()",                          // 3:  AND
    "[]",                          // 4:  XOR
    "<>",                          // 5:  MUX
    "{}"                           // 6:  PRIME
};

60 61
typedef struct Ifn_Obj_t_  Ifn_Obj_t;
struct Ifn_Obj_t_
62 63 64 65 66 67 68
{
    unsigned               Type    :  3;      // node type
    unsigned               nFanins :  5;      // fanin counter
    unsigned               iFirst  :  8;      // first parameter
    unsigned               Var     : 16;      // current variable
    int                    Fanins[IFN_INS];   // fanin IDs
};
69
struct Ifn_Ntk_t_ 
70 71 72 73
{
    // cell structure
    int                    nInps;             // inputs
    int                    nObjs;             // objects
74
    Ifn_Obj_t              Nodes[2*IFN_INS];  // nodes
75
    // constraints
76
    int                    pConstr[IFN_INS*IFN_INS];  // constraint pairs
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    int                    nConstr;           // number of pairs
    // user data
    int                    nVars;             // variables
    int                    nWords;            // truth table words
    int                    nParsVNum;         // selection parameters per variable
    int                    nParsVIni;         // first selection parameter
    int                    nPars;             // total parameters
    word *                 pTruth;            // user truth table
    // matching procedures
    int                    Values[IFN_PAR];            // variable values
    word                   pTtElems[IFN_INS*IFN_WRD];  // elementary truth tables
    word                   pTtObjs[2*IFN_INS*IFN_WRD]; // object truth tables
};

91 92
static inline word *       Ifn_ElemTruth( Ifn_Ntk_t * p, int i ) { return p->pTtElems + i * Abc_TtWordNum(p->nInps); }
static inline word *       Ifn_ObjTruth( Ifn_Ntk_t * p, int i )  { return p->pTtObjs + i * p->nWords;                }
93 94 95 96 97
 
// variable ordering
// - primary inputs            [0;            p->nInps)
// - internal nodes            [p->nInps;     p->nObjs)
// - configuration params      [p->nObjs;     p->nParsVIni)
98
// - variable selection params [p->nParsVIni; p->nPars)
99

100 101 102
////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////
103 104 105 106 107 108 109 110 111 112 113 114

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

  Synopsis    [Prepare network to check the given function.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
115
int Ifn_Prepare( Ifn_Ntk_t * p, word * pTruth, int nVars )
116 117 118 119 120 121 122 123 124
{
    int i, fVerbose = 0;
    assert( nVars <= p->nInps );
    p->pTruth = pTruth;
    p->nVars  = nVars;
    p->nWords = Abc_TtWordNum(nVars);
    p->nPars  = p->nObjs;
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
125
        if ( p->Nodes[i].Type != IFN_DSD_PRIME )
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
            continue;
        p->Nodes[i].iFirst = p->nPars;
        p->nPars += (1 << p->Nodes[i].nFanins);
        if ( fVerbose )
            printf( "Node %d  Start %d  Vars %d\n", i, p->Nodes[i].iFirst, (1 << p->Nodes[i].nFanins) );
    }
    if ( fVerbose )
        printf( "Groups start %d\n", p->nPars );
    p->nParsVIni = p->nPars;
    p->nParsVNum = Abc_Base2Log(nVars);
    p->nPars    += p->nParsVNum * p->nInps;
    assert( p->nPars <= IFN_PAR );
    memset( p->Values, 0xFF, sizeof(int) * p->nPars );
    return p->nPars;
}
141
void Ifn_NtkPrint( Ifn_Ntk_t * p )
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
{
    int i, k; 
    if ( p == NULL )
        printf( "String is empty.\n" );
    if ( p == NULL )
        return;
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        printf( "%c=", 'a'+i );
        printf( "%c", Ifn_Symbs[p->Nodes[i].Type][0] );
        for ( k = 0; k < (int)p->Nodes[i].nFanins; k++ )
            printf( "%c", 'a'+p->Nodes[i].Fanins[k] );
        printf( "%c", Ifn_Symbs[p->Nodes[i].Type][1] );
        printf( ";" );
    }
    printf( "\n" );
}
159 160 161 162
int Ifn_NtkLutSizeMax( Ifn_Ntk_t * p )
{
    int i, LutSize = 0;
    for ( i = p->nInps; i < p->nObjs; i++ )
163
        if ( p->Nodes[i].Type == IFN_DSD_PRIME )
164 165 166
            LutSize = Abc_MaxInt( LutSize, (int)p->Nodes[i].nFanins );
    return LutSize;
}
167 168 169 170
int Ifn_NtkInputNum( Ifn_Ntk_t * p )
{
    return p->nInps;
}
171

172 173 174 175 176 177 178 179 180 181 182
/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
int Ifn_ErrorMessage( const char * format, ...  )
{
    char * pMessage;
    va_list args;
    va_start( args, format );
    pMessage = vnsprintf( format, args );
    va_end( args );
    printf( "%s", pMessage );
    ABC_FREE( pMessage );
    return 0;
}
int Inf_ManOpenSymb( char * pStr )
{
    if ( pStr[0] == '(' )
        return 3;
    if ( pStr[0] == '[' )
        return 4;
    if ( pStr[0] == '<' )
        return 5;
    if ( pStr[0] == '{' )
        return 6;
    return 0;
}
206
int Ifn_ManStrCheck( char * pStr, int * pnInps, int * pnObjs )
207
{
208
    int i, nNodes = 0, Marks[32] = {0}, MaxVar = -1;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    for ( i = 0; pStr[i]; i++ )
    {
        if ( Inf_ManOpenSymb(pStr+i) )
            nNodes++;
        if ( pStr[i] == ';' || 
             pStr[i] == '(' || pStr[i] == ')' || 
             pStr[i] == '[' || pStr[i] == ']' || 
             pStr[i] == '<' || pStr[i] == '>' || 
             pStr[i] == '{' || pStr[i] == '}' )
            continue;
        if ( pStr[i] >= 'A' && pStr[i] <= 'Z' )
            continue;
        if ( pStr[i] >= 'a' && pStr[i] <= 'z' )
        {
            MaxVar = Abc_MaxInt( MaxVar, (int)(pStr[i] - 'a') );
            Marks[pStr[i] - 'a'] = 1;
            continue;
        }
        return Ifn_ErrorMessage( "String \"%s\" contains unrecognized symbol \'%c\'.\n", pStr, pStr[i] );
    }
    for ( i = 0; i <= MaxVar; i++ )
        if ( Marks[i] == 0 )
            return Ifn_ErrorMessage( "String \"%s\" has no symbol \'%c\'.\n", pStr, 'a' + i );
    *pnInps = MaxVar + 1;
    *pnObjs = MaxVar + 1 + nNodes;
    return 1;
}
236
static inline char * Ifn_NtkParseFindClosingParenthesis( char * pStr, char Open, char Close )
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
{
    int Counter = 0;
    assert( *pStr == Open );
    for ( ; *pStr; pStr++ )
    {
        if ( *pStr == Open )
            Counter++;
        if ( *pStr == Close )
            Counter--;
        if ( Counter == 0 )
            return pStr;
    }
    return NULL;
}
int Ifn_NtkParseInt_rec( char * pStr, Ifn_Ntk_t * p, char ** ppFinal, int * piNode )
{
    Ifn_Obj_t * pObj;
    int nFanins = 0, pFanins[IFN_INS];
    int Type = Inf_ManOpenSymb( pStr );
256
    char * pLim = Ifn_NtkParseFindClosingParenthesis( pStr++, Ifn_Symbs[Type][0], Ifn_Symbs[Type][1] );
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    *ppFinal = NULL;
    if ( pLim == NULL )
        return Ifn_ErrorMessage( "For symbol \'%c\' cannot find matching symbol \'%c\'.\n", Ifn_Symbs[Type][0], Ifn_Symbs[Type][1] );
    while ( pStr < pLim )
    {
        assert( nFanins < IFN_INS );
        if ( pStr[0] >= 'a' && pStr[0] <= 'z' )
            pFanins[nFanins++] = pStr[0] - 'a', pStr++; 
        else if ( Inf_ManOpenSymb(pStr) )
        {
            if ( !Ifn_NtkParseInt_rec( pStr, p, &pStr, piNode ) )
                return 0;
            pFanins[nFanins++] = *piNode - 1;
        }
        else
            return Ifn_ErrorMessage( "Substring \"%s\" contans unrecognized symbol \'%c\'.\n", pStr, pStr[0] );
    }
    assert( pStr == pLim );
    pObj = p->Nodes + (*piNode)++;
    pObj->Type = Type;
    assert( pObj->nFanins == 0 );
    pObj->nFanins = nFanins;
    memcpy( pObj->Fanins, pFanins, sizeof(int) * nFanins );
    *ppFinal = pLim + 1;
    if ( Type == IFN_DSD_MUX && nFanins != 3 )
        return Ifn_ErrorMessage( "MUX should have exactly three fanins.\n" );
    return 1;
}
int Ifn_NtkParseInt( char * pStr, Ifn_Ntk_t * p )
{
    char * pFinal; int iNode;
    if ( !Ifn_ManStrCheck(pStr, &p->nInps, &p->nObjs) )
        return 0;
    if ( p->nInps > IFN_INS )
        return Ifn_ErrorMessage( "The number of variables (%d) exceeds predefined limit (%d). Recompile with different value of IFN_INS.\n", p->nInps, IFN_INS );
    assert( p->nInps > 1 && p->nInps < p->nObjs && p->nInps <= IFN_INS && p->nObjs < 2*IFN_INS );
    if ( !Inf_ManOpenSymb(pStr) )
        return Ifn_ErrorMessage( "The first symbol should be one of the symbols: (, [, <, {.\n" );
    iNode = p->nInps;
    if ( !Ifn_NtkParseInt_rec( pStr, p, &pFinal, &iNode ) )
        return 0;
    if ( pFinal[0] && pFinal[0] != ';' )
        return Ifn_ErrorMessage( "The last symbol should be \';\'.\n" );
    if ( iNode != p->nObjs )
        return Ifn_ErrorMessage( "Mismatch in the number of nodes.\n" );
    return 1;
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int Ifn_ManStrType2( char * pStr )
{
    int i;
    for ( i = 0; pStr[i]; i++ )
        if ( pStr[i] == '=' )
            return 1;
    return 0;
}
int Ifn_ManStrCheck2( char * pStr, int * pnInps, int * pnObjs )
{
    int i, Marks[32] = {0}, MaxVar = 0, MaxDef = 0;
327 328 329 330 331 332 333 334
    for ( i = 0; pStr[i]; i++ )
    {
        if ( pStr[i] == '=' || pStr[i] == ';' || 
             pStr[i] == '(' || pStr[i] == ')' || 
             pStr[i] == '[' || pStr[i] == ']' || 
             pStr[i] == '<' || pStr[i] == '>' || 
             pStr[i] == '{' || pStr[i] == '}' )
            continue;
335 336
        if ( pStr[i] >= 'A' && pStr[i] <= 'Z' )
            continue;
337 338 339
        if ( pStr[i] >= 'a' && pStr[i] <= 'z' )
        {
            if ( pStr[i+1] == '=' )
340
                Marks[pStr[i] - 'a'] = 2, MaxDef = Abc_MaxInt(MaxDef, pStr[i] - 'a');
341 342
            continue;
        }
343
        return Ifn_ErrorMessage( "String \"%s\" contains unrecognized symbol \'%c\'.\n", pStr, pStr[i] );
344
    }
345 346 347 348 349 350 351 352
    for ( i = 0; pStr[i]; i++ )
    {
        if ( pStr[i] == '=' || pStr[i] == ';' || 
             pStr[i] == '(' || pStr[i] == ')' || 
             pStr[i] == '[' || pStr[i] == ']' || 
             pStr[i] == '<' || pStr[i] == '>' || 
             pStr[i] == '{' || pStr[i] == '}' )
            continue;
353 354
        if ( pStr[i] >= 'A' && pStr[i] <= 'Z' )
            continue;
355 356 357 358 359 360
        if ( pStr[i] >= 'a' && pStr[i] <= 'z' )
        {
            if ( pStr[i+1] != '=' && Marks[pStr[i] - 'a'] != 2 )
                Marks[pStr[i] - 'a'] = 1, MaxVar = Abc_MaxInt(MaxVar, pStr[i] - 'a');
            continue;
        }
361
        return Ifn_ErrorMessage( "String \"%s\" contains unrecognized symbol \'%c\'.\n", pStr, pStr[i] );
362 363 364
    }
    MaxVar++;
    MaxDef++;
365 366
    for ( i = 0; i < MaxDef; i++ )
        if ( Marks[i] == 0 )
367
            return Ifn_ErrorMessage( "String \"%s\" has no symbol \'%c\'.\n", pStr, 'a' + i );
368 369
    for ( i = 0; i < MaxVar; i++ )
        if ( Marks[i] == 2 )
370
            return Ifn_ErrorMessage( "String \"%s\" has definition of input variable \'%c\'.\n", pStr, 'a' + i );
371 372
    for ( i = MaxVar; i < MaxDef; i++ )
        if ( Marks[i] == 1 )
373
            return Ifn_ErrorMessage( "String \"%s\" has no definition for internal variable \'%c\'.\n", pStr, 'a' + i );
374
    *pnInps = MaxVar;
375 376
    *pnObjs = MaxDef;
    return 1;
377
}
378
int Ifn_NtkParseInt2( char * pStr, Ifn_Ntk_t * p )
379
{
380
    int i, k, n, f, nFans, iFan;
381
    if ( !Ifn_ManStrCheck2(pStr, &p->nInps, &p->nObjs) )
382
        return 0;
383
    if ( p->nInps > IFN_INS )
384
        return Ifn_ErrorMessage( "The number of variables (%d) exceeds predefined limit (%d). Recompile with different value of IFN_INS.\n", p->nInps, IFN_INS );
385 386 387 388
    assert( p->nInps > 1 && p->nInps < p->nObjs && p->nInps <= IFN_INS && p->nObjs < 2*IFN_INS );
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        char Next = 0;
389 390 391
        for ( k = 0; pStr[k]; k++ )
            if ( pStr[k] == 'a' + i && pStr[k+1] == '=' )
                break;
392
        if ( pStr[k] == 0 )
393
            return Ifn_ErrorMessage( "Cannot find definition of signal \'%c\'.\n", 'a' + i );
394
        if ( pStr[k+2] == '(' )
395
            p->Nodes[i].Type = IFN_DSD_AND, Next = ')';
396
        else if ( pStr[k+2] == '[' )
397
            p->Nodes[i].Type = IFN_DSD_XOR, Next = ']';
398
        else if ( pStr[k+2] == '<' )
399
            p->Nodes[i].Type = IFN_DSD_MUX, Next = '>';
400
        else if ( pStr[k+2] == '{' )
401
            p->Nodes[i].Type = IFN_DSD_PRIME, Next = '}';
402
        else 
403
            return Ifn_ErrorMessage( "Cannot find openning operation symbol in the definition of signal \'%c\'.\n", 'a' + i );
404 405 406
        for ( n = k + 3; pStr[n]; n++ )
            if ( pStr[n] == Next )
                break;
407
        if ( pStr[n] == 0 )
408
            return Ifn_ErrorMessage( "Cannot find closing operation symbol in the definition of signal \'%c\'.\n", 'a' + i );
409
        nFans = n - k - 3;
410 411
        if ( nFans > 8 )
            return Ifn_ErrorMessage( "Cannot find matching operation symbol in the definition of signal \'%c\'.\n", 'a' + i );
412 413 414 415
        for ( f = 0; f < nFans; f++ )
        {
            iFan = pStr[k + 3 + f] - 'a';
            if ( iFan < 0 || iFan >= i )
416
                return Ifn_ErrorMessage( "Fanin number %d is signal %d is out of range.\n", f, 'a' + i );
417 418 419
            p->Nodes[i].Fanins[f] = iFan;
        }
        p->Nodes[i].nFanins = nFans;
420
    }
421 422 423 424 425
    return 1;
}
void Ifn_NtkParseConstraints( char * pStr, Ifn_Ntk_t * p )
{
    int i, k;
426 427 428 429 430 431
    // parse constraints
    p->nConstr = 0;
    for ( i = 0; i < p->nInps; i++ )
        for ( k = 0; pStr[k]; k++ )
            if ( pStr[k] == 'A' + i && pStr[k-1] == ';' )
            {
432
                assert( p->nConstr < IFN_INS*IFN_INS );
433 434 435 436 437
                p->pConstr[p->nConstr++] = ((int)(pStr[k] - 'A') << 16) | (int)(pStr[k+1] - 'A');
//                printf( "Added constraint (%c < %c)\n", pStr[k], pStr[k+1] );
            }
//    if ( p->nConstr )
//        printf( "Total constraints = %d\n", p->nConstr );
438
}
439

440 441 442
Ifn_Ntk_t * Ifn_NtkParse( char * pStr )
{
    Ifn_Ntk_t * p = ABC_CALLOC( Ifn_Ntk_t, 1 );
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    if ( Ifn_ManStrType2(pStr) )
    {
        if ( !Ifn_NtkParseInt2( pStr, p ) )
        {
            ABC_FREE( p );
            return NULL;
        }
    }
    else
    {
        if ( !Ifn_NtkParseInt( pStr, p ) )
        {
            ABC_FREE( p );
            return NULL;
        }
    }
    Ifn_NtkParseConstraints( pStr, p );
    Abc_TtElemInit2( p->pTtElems, p->nInps );
461
//    printf( "Finished parsing: " ); Ifn_NtkPrint(p);
462
    return p;
463
}
464 465 466 467 468 469 470 471 472 473
int Ifn_NtkTtBits( char * pStr )
{
    int i, Counter = 0;
    Ifn_Ntk_t * pNtk = Ifn_NtkParse( pStr );
    for ( i = pNtk->nInps; i < pNtk->nObjs; i++ )
        if ( pNtk->Nodes[i].Type == IFN_DSD_PRIME )
            Counter += (1 << pNtk->Nodes[i].nFanins);
    ABC_FREE( pNtk );
    return Counter;
}
474

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527


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

  Synopsis    [Derive AIG.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
Gia_Man_t * Ifn_ManStrFindModel( Ifn_Ntk_t * p )
{
    Gia_Man_t * pNew, * pTemp;
    int i, k, iLit, * pVarMap = ABC_FALLOC( int, p->nParsVIni );
    pNew = Gia_ManStart( 1000 );
    pNew->pName = Abc_UtilStrsav( "model" );
    Gia_ManHashStart( pNew );
    for ( i = 0; i < p->nInps; i++ )
        pVarMap[i] = Gia_ManAppendCi(pNew);
    for ( i = p->nObjs; i < p->nParsVIni; i++ )
        pVarMap[i] = Gia_ManAppendCi(pNew);
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        int Type = p->Nodes[i].Type;
        int nFans = p->Nodes[i].nFanins;
        int * pFans = p->Nodes[i].Fanins;
        int iFanin = p->Nodes[i].iFirst;
        if ( Type == IFN_DSD_AND )
        {
            iLit = 1;
            for ( k = 0; k < nFans; k++ )
                iLit = Gia_ManHashAnd( pNew, iLit, pVarMap[pFans[k]] );
            pVarMap[i] = iLit;
        }
        else if ( Type == IFN_DSD_XOR )
        {
            iLit = 0;
            for ( k = 0; k < nFans; k++ )
                iLit = Gia_ManHashXor( pNew, iLit, pVarMap[pFans[k]] );
            pVarMap[i] = iLit;
        }
        else if ( Type == IFN_DSD_MUX )
        {
            assert( nFans == 3 );
            pVarMap[i] = Gia_ManHashMux( pNew, pVarMap[pFans[0]], pVarMap[pFans[1]], pVarMap[pFans[2]] );
        }
        else if ( Type == IFN_DSD_PRIME )
        {
            int n, Step, pVarsData[256];
            int nMints = (1 << nFans);
528
            assert( nFans >= 0 && nFans <= 8 );
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
            for ( k = 0; k < nMints; k++ )
                pVarsData[k] = pVarMap[iFanin + k];
            for ( Step = 1, k = 0; k < nFans; k++, Step <<= 1 )
                for ( n = 0; n < nMints; n += Step << 1 )
                    pVarsData[n] = Gia_ManHashMux( pNew, pVarMap[pFans[k]], pVarsData[n+Step], pVarsData[n] );
            assert( Step == nMints );
            pVarMap[i] = pVarsData[0];
        }
        else assert( 0 );
    }
    Gia_ManAppendCo( pNew, pVarMap[p->nObjs-1] );
    ABC_FREE( pVarMap );
    pNew = Gia_ManCleanup( pTemp = pNew );
    Gia_ManStop( pTemp );
    assert( Gia_ManPiNum(pNew) == p->nParsVIni - (p->nObjs - p->nInps) );
    assert( Gia_ManPoNum(pNew) == 1 );
    return pNew;
}
// compute cofactors w.r.t. the first nIns variables
Gia_Man_t * Ifn_ManStrFindCofactors( int nIns, Gia_Man_t * p )
{
    Gia_Man_t * pNew, * pTemp; 
    Gia_Obj_t * pObj;
552
    int i, m, nMints = 1 << nIns;
553 554 555 556 557 558 559 560 561 562 563 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 627 628 629 630 631 632
    pNew = Gia_ManStart( Gia_ManObjNum(p) );
    pNew->pName = Abc_UtilStrsav( p->pName );
    Gia_ManHashAlloc( pNew );
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachCi( p, pObj, i )
        if ( i >= nIns )
            pObj->Value = Gia_ManAppendCi( pNew );
    for ( m = 0; m < nMints; m++ )
    {
        Gia_ManForEachCi( p, pObj, i )
            if ( i < nIns )
                pObj->Value = ((m >> i) & 1);
        Gia_ManForEachAnd( p, pObj, i )
            pObj->Value = Gia_ManHashAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
        Gia_ManForEachPo( p, pObj, i )
            pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
    }
    pNew = Gia_ManCleanup( pTemp = pNew );
    Gia_ManStop( pTemp );
    return pNew;
}

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

  Synopsis    [Derive SAT solver.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
static inline Cnf_Dat_t * Cnf_DeriveGiaRemapped( Gia_Man_t * p )
{
    Cnf_Dat_t * pCnf;
    Aig_Man_t * pAig = Gia_ManToAigSimple( p );
    pAig->nRegs = 0;
    pCnf = Cnf_Derive( pAig, Aig_ManCoNum(pAig) );
    Aig_ManStop( pAig );
    return pCnf;
}
sat_solver * Ifn_ManStrFindSolver( Gia_Man_t * p, Vec_Int_t ** pvPiVars, Vec_Int_t ** pvPoVars )
{
    sat_solver * pSat;
    Gia_Obj_t * pObj;
    Cnf_Dat_t * pCnf;
    int i;    
    pCnf = Cnf_DeriveGiaRemapped( p );
    // start the SAT solver
    pSat = sat_solver_new();
    sat_solver_setnvars( pSat, pCnf->nVars );
    // add timeframe clauses
    for ( i = 0; i < pCnf->nClauses; i++ )
        if ( !sat_solver_addclause( pSat, pCnf->pClauses[i], pCnf->pClauses[i+1] ) )
            assert( 0 );
    // inputs/outputs
    *pvPiVars = Vec_IntAlloc( Gia_ManPiNum(p) );
    Gia_ManForEachCi( p, pObj, i )
        Vec_IntPush( *pvPiVars, pCnf->pVarNums[Gia_ObjId(p, pObj)] );
    *pvPoVars = Vec_IntAlloc( Gia_ManPoNum(p) );
    Gia_ManForEachCo( p, pObj, i )
        Vec_IntPush( *pvPoVars, pCnf->pVarNums[Gia_ObjId(p, pObj)] );
    Cnf_DataFree( pCnf );
    return pSat;
}
sat_solver * Ifn_ManSatBuild( Ifn_Ntk_t * p, Vec_Int_t ** pvPiVars, Vec_Int_t ** pvPoVars )
{
    Gia_Man_t * p1, * p2;
    sat_solver * pSat = NULL;
    *pvPiVars = *pvPoVars = NULL;
    p1 = Ifn_ManStrFindModel( p );
//    Gia_AigerWrite( p1, "satbuild.aig", 0, 0 );
    p2 = Ifn_ManStrFindCofactors( p->nInps, p1 );
    Gia_ManStop( p1 );
//    Gia_AigerWrite( p2, "satbuild2.aig", 0, 0 );
    pSat = Ifn_ManStrFindSolver( p2, pvPiVars, pvPoVars );
    Gia_ManStop( p2 );
    return pSat;
}
633
void * If_ManSatBuildFromCell( char * pStr, Vec_Int_t ** pvPiVars, Vec_Int_t ** pvPoVars, Ifn_Ntk_t ** ppNtk )
634 635
{
    Ifn_Ntk_t * p = Ifn_NtkParse( pStr );
636
    Ifn_Prepare( p, NULL, p->nInps );
637 638 639 640 641 642
    *ppNtk = p;
    if ( p == NULL )
        return NULL;
//    Ifn_NtkPrint( p );
    return Ifn_ManSatBuild( p, pvPiVars, pvPoVars );
}
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Ifn_ManSatPrintPerm( char * pPerms, int nVars )
{
    int i;
    for ( i = 0; i < nVars; i++ )
        printf( "%c", 'a' + pPerms[i] );
    printf( "\n" );
}
662
int Ifn_ManSatCheckOne( sat_solver * pSat, Vec_Int_t * vPoVars, word * pTruth, int nVars, int * pPerm, int nInps, Vec_Int_t * vLits )
663
{
664
    int v, Value, m, mNew, nMints = (1 << nVars); // (1 << nInps);
665 666
    assert( (1 << nInps) == Vec_IntSize(vPoVars) );
    assert( nVars <= nInps );
667 668 669 670 671
    // remap minterms
    Vec_IntFill( vLits, Vec_IntSize(vPoVars), -1 );
    for ( m = 0; m < nMints; m++ )
    {
        mNew = 0;
672
        for ( v = 0; v < nInps; v++ )
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        {
            assert( pPerm[v] < nVars );
            if ( ((m >> pPerm[v]) & 1) )
                mNew |= (1 << v);
        }
        assert( Vec_IntEntry(vLits, mNew) == -1 );
        Vec_IntWriteEntry( vLits, mNew, Abc_TtGetBit(pTruth, m) );
    }
    // find assumptions
    v = 0;
    Vec_IntForEachEntry( vLits, Value, m )
        if ( Value >= 0 )
            Vec_IntWriteEntry( vLits, v++, Abc_Var2Lit(Vec_IntEntry(vPoVars, m), !Value) );
    Vec_IntShrink( vLits, v );
    // run SAT solver
    Value = sat_solver_solve( pSat, Vec_IntArray(vLits), Vec_IntArray(vLits) + Vec_IntSize(vLits), 0, 0, 0, 0 );
    return (int)(Value == l_True);
}
void Ifn_ManSatDeriveOne( sat_solver * pSat, Vec_Int_t * vPiVars, Vec_Int_t * vValues )
{
    int i, iVar;
    Vec_IntClear( vValues );
    Vec_IntForEachEntry( vPiVars, iVar, i )
        Vec_IntPush( vValues, sat_solver_var_value(pSat, iVar) );
}
698
int If_ManSatFindCofigBits( void * pSat, Vec_Int_t * vPiVars, Vec_Int_t * vPoVars, word * pTruth, int nVars, word Perm, int nInps, Vec_Int_t * vValues )
699 700 701
{
    // extract permutation
    int RetValue, i, pPerm[IF_MAX_FUNC_LUTSIZE];
702 703
    assert( nInps <= IF_MAX_FUNC_LUTSIZE );
    for ( i = 0; i < nInps; i++ )
704 705 706 707 708
    {
        pPerm[i] = Abc_TtGetHex( &Perm, i );
        assert( pPerm[i] < nVars );
    }
    // perform SAT check 
709
    RetValue = Ifn_ManSatCheckOne( (sat_solver *)pSat, vPoVars, pTruth, nVars, pPerm, nInps, vValues );
710 711 712
    Vec_IntClear( vValues );
    if ( RetValue == 0 )
        return 0;
713
    Ifn_ManSatDeriveOne( (sat_solver*)pSat, vPiVars, vValues );
714 715
    return 1;
}
716 717 718 719 720
int Ifn_ManSatFindCofigBitsTest( Ifn_Ntk_t * p, word * pTruth, int nVars, word Perm )
{
    Vec_Int_t * vValues = Vec_IntAlloc( 100 );
    Vec_Int_t * vPiVars, * vPoVars;
    sat_solver * pSat = Ifn_ManSatBuild( p, &vPiVars, &vPoVars );
721
    int RetValue = If_ManSatFindCofigBits( pSat, vPiVars, vPoVars, pTruth, nVars, Perm, p->nInps, vValues );
722 723 724 725 726 727 728 729
    Vec_IntPrint( vValues );
    // cleanup
    sat_solver_delete( pSat );
    Vec_IntFreeP( &vPiVars );
    Vec_IntFreeP( &vPoVars );
    Vec_IntFreeP( &vValues );
    return RetValue;
}
730

731 732 733 734 735 736 737 738 739 740 741
/**Function*************************************************************

  Synopsis    [Derive GIA using programmable bits.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
742
int If_ManSatDeriveGiaFromBits( void * pGia, Ifn_Ntk_t * p, word * pConfigData, Vec_Int_t * vLeaves, Vec_Int_t * vCover )
743
{
744
    Gia_Man_t * pNew = (Gia_Man_t *)pGia;
745 746 747 748 749 750 751 752 753 754 755 756 757
    int i, k, iLit, iVar = 0, nVarsNew, pVarMap[1000];
    int nTtBits = p->nParsVIni - p->nObjs;
    int nPermBits = Abc_Base2Log(p->nInps + 1) + 1;
    int fCompl = Abc_TtGetBit( pConfigData, nTtBits + nPermBits * p->nInps );
    assert( Vec_IntSize(vLeaves) <= p->nInps && p->nParsVIni < 1000 );
    for ( i = 0; i < p->nInps; i++ )
    {
        for ( iLit = k = 0; k < nPermBits; k++ )
            if ( Abc_TtGetBit(pConfigData, nTtBits + i * nPermBits + k) )
                iLit |= (1 << k);
        assert( Abc_Lit2Var(iLit) < Vec_IntSize(vLeaves) );
        pVarMap[i] = Abc_Lit2LitL( Vec_IntArray(vLeaves), iLit );
    }
758 759 760 761 762
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        int Type = p->Nodes[i].Type;
        int nFans = p->Nodes[i].nFanins;
        int * pFans = p->Nodes[i].Fanins;
Alan Mishchenko committed
763
        //int iFanin = p->Nodes[i].iFirst;
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
        assert( nFans <= 6 );
        if ( Type == IFN_DSD_AND )
        {
            iLit = 1;
            for ( k = 0; k < nFans; k++ )
                iLit = Gia_ManHashAnd( pNew, iLit, pVarMap[pFans[k]] );
            pVarMap[i] = iLit;
        }
        else if ( Type == IFN_DSD_XOR )
        {
            iLit = 0;
            for ( k = 0; k < nFans; k++ )
                iLit = Gia_ManHashXor( pNew, iLit, pVarMap[pFans[k]] );
            pVarMap[i] = iLit;
        }
        else if ( Type == IFN_DSD_MUX )
        {
            assert( nFans == 3 );
            pVarMap[i] = Gia_ManHashMux( pNew, pVarMap[pFans[0]], pVarMap[pFans[1]], pVarMap[pFans[2]] );
        }
        else if ( Type == IFN_DSD_PRIME )
        {
            int pFaninLits[16];
            // collect truth table
            word uTruth = 0;
            int nMints = (1 << nFans);
            for ( k = 0; k < nMints; k++ )
791
                if ( Abc_TtGetBit(pConfigData, iVar++) )
792
                    uTruth |= ((word)1 << k);
793
            uTruth = Abc_Tt6Stretch( uTruth, nFans );
794 795 796 797 798 799 800 801 802 803 804
            // collect function
            for ( k = 0; k < nFans; k++ )
                pFaninLits[k] = pVarMap[pFans[k]];
            // implement the function
            nVarsNew = Abc_TtMinBase( &uTruth, pFaninLits, nFans, 6 );
            if ( nVarsNew == 0 )
                pVarMap[i] = (int)(uTruth & 1);
            else
            {
                extern int Kit_TruthToGia( Gia_Man_t * pMan, unsigned * pTruth, int nVars, Vec_Int_t * vMemory, Vec_Int_t * vLeaves, int fHash );
                Vec_Int_t Leaves = { nVarsNew, nVarsNew, pFaninLits };
805
                pVarMap[i] = Kit_TruthToGia( pNew, (unsigned *)&uTruth, nVarsNew, vCover, &Leaves, 1 ); // hashing enabled!!!
806 807 808 809
            }
        }
        else assert( 0 );
    }
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    assert( iVar == nTtBits );
    return Abc_LitNotCond( pVarMap[p->nObjs - 1], fCompl );
}

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

  Synopsis    [Derive GIA using programmable bits.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void * If_ManDeriveGiaFromCells( void * pGia )
{
    Gia_Man_t * p = (Gia_Man_t *)pGia;
    Gia_Man_t * pNew, * pTemp;
    Vec_Int_t * vCover, * vLeaves;
    Ifn_Ntk_t * pNtkCell;
    Gia_Obj_t * pObj; 
    word * pConfigData;
    //word * pTruth;
    int k, i, iLut, iVar;
    int nConfigInts, Count = 0;
    assert( p->vConfigs != NULL );
    assert( p->pCellStr != NULL );
    assert( Gia_ManHasMapping(p) );
    // derive cell network
    pNtkCell = Ifn_NtkParse( p->pCellStr );
    Ifn_Prepare( pNtkCell, NULL, pNtkCell->nInps );
    nConfigInts = Vec_IntEntry( p->vConfigs, 1 );
    // create new manager
    pNew = Gia_ManStart( 6*Gia_ManObjNum(p)/5 + 100 );
    pNew->pName = Abc_UtilStrsav( p->pName );
    pNew->pSpec = Abc_UtilStrsav( p->pSpec );
    // map primary inputs
    Gia_ManFillValue(p);
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachCi( p, pObj, i )
        pObj->Value = Gia_ManAppendCi(pNew);
    // iterate through nodes used in the mapping
    vLeaves = Vec_IntAlloc( 16 );
    vCover  = Vec_IntAlloc( 1 << 16 );
    Gia_ManHashStart( pNew );
    //Gia_ObjComputeTruthTableStart( p, Gia_ManLutSizeMax(p) );
    Gia_ManForEachAnd( p, pObj, iLut )
    {
        if ( Gia_ObjIsBuf(pObj) )
        {
            pObj->Value = Gia_ManAppendBuf( pNew, Gia_ObjFanin0Copy(pObj) );
            continue;
        }
        if ( !Gia_ObjIsLut(p, iLut) )
            continue;
        // collect leaves
        //Vec_IntClear( vLeaves );
        //Gia_LutForEachFanin( p, iLut, iVar, k )
        //    Vec_IntPush( vLeaves, iVar );
        //pTruth = Gia_ObjComputeTruthTableCut( p, Gia_ManObj(p, iLut), vLeaves );
        // collect incoming literals
        Vec_IntClear( vLeaves );
        Gia_LutForEachFanin( p, iLut, iVar, k )
            Vec_IntPush( vLeaves, Gia_ManObj(p, iVar)->Value );
        pConfigData = (word *)Vec_IntEntryP( p->vConfigs, 2 + nConfigInts * Count++ );
        Gia_ManObj(p, iLut)->Value = If_ManSatDeriveGiaFromBits( pNew, pNtkCell, pConfigData, vLeaves, vCover );
    }
    assert( Vec_IntEntry(p->vConfigs, 0) == Count );
    assert( Vec_IntSize(p->vConfigs) == 2 + nConfigInts * Count );
    //Gia_ObjComputeTruthTableStop( p );
    Gia_ManForEachCo( p, pObj, i )
        pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
    Gia_ManHashStop( pNew );
    Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
    Vec_IntFree( vLeaves );
    Vec_IntFree( vCover );
    ABC_FREE( pNtkCell );
    // perform cleanup
    pNew = Gia_ManCleanup( pTemp = pNew );
    Gia_ManStop( pTemp );
    return pNew;

893
}
894

895 896 897 898 899 900 901 902 903 904 905
/**Function*************************************************************

  Synopsis    [Derive truth table given the configulation values.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
906
word * Ifn_NtkDeriveTruth( Ifn_Ntk_t * p, int * pValues )
907
{
908 909 910
    int i, v, f, iVar, iStart;
    // elementary variables
    for ( i = 0; i < p->nInps; i++ )
911
    {
912 913 914 915 916 917
        // find variable
        iStart = p->nParsVIni + i * p->nParsVNum;
        for ( v = iVar = 0; v < p->nParsVNum; v++ )
            if ( p->Values[iStart+v] )
                iVar += (1 << v);
        // assign variable
918
        Abc_TtCopy( Ifn_ObjTruth(p, i), Ifn_ElemTruth(p, iVar), p->nWords, 0 );
919 920 921 922 923 924
    }
    // internal variables
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        int nFans = p->Nodes[i].nFanins;
        int * pFans = p->Nodes[i].Fanins;
925
        word * pTruth = Ifn_ObjTruth( p, i );
926
        if ( p->Nodes[i].Type == IFN_DSD_AND )
927
        {
928 929
            Abc_TtFill( pTruth, p->nWords );
            for ( f = 0; f < nFans; f++ )
930
                Abc_TtAnd( pTruth, pTruth, Ifn_ObjTruth(p, pFans[f]), p->nWords, 0 );
931
        }
932
        else if ( p->Nodes[i].Type == IFN_DSD_XOR )
933
        {
934 935
            Abc_TtClear( pTruth, p->nWords );
            for ( f = 0; f < nFans; f++ )
936
                Abc_TtXor( pTruth, pTruth, Ifn_ObjTruth(p, pFans[f]), p->nWords, 0 );
937
        }
938
        else if ( p->Nodes[i].Type == IFN_DSD_MUX )
939
        {
940
            assert( nFans == 3 );
941
            Abc_TtMux( pTruth, Ifn_ObjTruth(p, pFans[0]), Ifn_ObjTruth(p, pFans[1]), Ifn_ObjTruth(p, pFans[2]), p->nWords );
942
        }
943
        else if ( p->Nodes[i].Type == IFN_DSD_PRIME )
944
        {
945
            int nValues = (1 << nFans);
946
            word * pTemp = Ifn_ObjTruth(p, p->nObjs);
947 948 949 950 951 952 953 954
            Abc_TtClear( pTruth, p->nWords );
            for ( v = 0; v < nValues; v++ )
            {
                if ( pValues[p->Nodes[i].iFirst + v] == 0 )
                    continue;
                Abc_TtFill( pTemp, p->nWords );
                for ( f = 0; f < nFans; f++ )
                    if ( (v >> f) & 1 )
955
                        Abc_TtAnd( pTemp, pTemp, Ifn_ObjTruth(p, pFans[f]), p->nWords, 0 );
956
                    else
957
                        Abc_TtSharp( pTemp, pTemp, Ifn_ObjTruth(p, pFans[f]), p->nWords );
958 959
                Abc_TtOr( pTruth, pTruth, pTemp, p->nWords );
            }
960 961
        }
        else assert( 0 );
962
//Dau_DsdPrintFromTruth( pTruth, p->nVars );
963
    }
964
    return Ifn_ObjTruth(p, p->nObjs-1);
965
}
966 967 968 969 970 971 972 973 974 975 976 977

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

  Synopsis    [Compute more or equal]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
978
void Ifn_TtComparisonConstr( word * pTruth, int nVars, int fMore, int fEqual )
979
{
980 981
    word Cond[4], Equa[4], Temp[4];
    word s_TtElems[8][4] = {
982 983 984 985 986 987 988 989
        { 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) }
990 991 992 993 994 995
    };
    int i, nWords = Abc_TtWordNum(2*nVars);
    assert( nVars > 0 && nVars <= 4 );
    Abc_TtClear( pTruth, nWords );
    Abc_TtFill( Equa, nWords );
    for ( i = nVars - 1; i >= 0; i-- )
996
    {
997 998 999 1000 1001 1002 1003 1004
        if ( fMore )
            Abc_TtSharp( Cond, s_TtElems[2*i+1], s_TtElems[2*i+0], nWords );
        else
            Abc_TtSharp( Cond, s_TtElems[2*i+0], s_TtElems[2*i+1], nWords );
        Abc_TtAnd( Temp, Equa, Cond, nWords, 0 );
        Abc_TtOr( pTruth, pTruth, Temp, nWords );
        Abc_TtXor( Temp, s_TtElems[2*i+0], s_TtElems[2*i+1], nWords, 1 );
        Abc_TtAnd( Equa, Equa, Temp, nWords, 0 );
1005
    }
1006 1007
    if ( fEqual )
        Abc_TtNot( pTruth, nWords );
1008
}
1009 1010 1011

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

1012
  Synopsis    [Adds parameter constraints.]
1013 1014 1015 1016 1017 1018 1019 1020

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1021
int Ifn_AddClause( sat_solver * pSat, int * pBeg, int * pEnd )
1022
{
1023 1024 1025 1026 1027 1028 1029 1030
    int fVerbose = 0;
    int RetValue = sat_solver_addclause( pSat, pBeg, pEnd );
    if ( fVerbose )
    {
        for ( ; pBeg < pEnd; pBeg++ )
            printf( "%c%d ", Abc_LitIsCompl(*pBeg) ? '-':'+', Abc_Lit2Var(*pBeg) );
        printf( "\n" );
    }
1031
    return RetValue;
1032
}
1033
void Ifn_NtkAddConstrOne( sat_solver * pSat, Vec_Int_t * vCover, int * pVars, int nVars )
1034
{
1035
    int RetValue, k, c, Cube, Literal, nLits, pLits[IFN_INS];
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    Vec_IntForEachEntry( vCover, Cube, c )
    {
        nLits = 0;
        for ( k = 0; k < nVars; k++ )
        {
            Literal = 3 & (Cube >> (k << 1));
            if ( Literal == 1 )      // '0'  -> pos lit
                pLits[nLits++] = Abc_Var2Lit(pVars[k], 0);
            else if ( Literal == 2 ) // '1'  -> neg lit
                pLits[nLits++] = Abc_Var2Lit(pVars[k], 1);
            else if ( Literal != 0 )
                assert( 0 );
        }
1049 1050
        RetValue = Ifn_AddClause( pSat, pLits, pLits + nLits );
        assert( RetValue );
1051
    }
1052
}
1053
void Ifn_NtkAddConstraints( Ifn_Ntk_t * p, sat_solver * pSat )
1054
{
1055
    int fAddConstr = 1;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    Vec_Int_t * vCover = Vec_IntAlloc( 0 );
    word uTruth = Abc_Tt6Stretch( ~Abc_Tt6Mask(p->nVars), p->nParsVNum );
    assert( p->nParsVNum <= 4 );
    if ( uTruth )
    {
        int i, k, pVars[IFN_INS];
        int RetValue = Kit_TruthIsop( (unsigned *)&uTruth, p->nParsVNum, vCover, 0 );
        assert( RetValue == 0 );
//        Dau_DsdPrintFromTruth( &uTruth, p->nParsVNum );
        // add capacity constraints
        for ( i = 0; i < p->nInps; i++ )
        {
            for ( k = 0; k < p->nParsVNum; k++ )
                pVars[k] = p->nParsVIni + i * p->nParsVNum + k;
1070
            Ifn_NtkAddConstrOne( pSat, vCover, pVars, p->nParsVNum );
1071 1072 1073 1074 1075 1076 1077 1078
        }
    }
    // ordering constraints
    if ( fAddConstr && p->nConstr )
    {
        word pTruth[4];
        int i, k, RetValue, pVars[2*IFN_INS];
        int fForceDiff = (p->nVars == p->nInps);
1079
        Ifn_TtComparisonConstr( pTruth, p->nParsVNum, fForceDiff, fForceDiff );
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
        RetValue = Kit_TruthIsop( (unsigned *)pTruth, 2*p->nParsVNum, vCover, 0 );
        assert( RetValue == 0 );
//        Kit_TruthIsopPrintCover( vCover, 2*p->nParsVNum, 0 );
        for ( i = 0; i < p->nConstr; i++ )
        {
            int iVar1 = p->pConstr[i] >> 16;
            int iVar2 = p->pConstr[i] & 0xFFFF;
            for ( k = 0; k < p->nParsVNum; k++ )
            {
                pVars[2*k+0] = p->nParsVIni + iVar1 * p->nParsVNum + k;
                pVars[2*k+1] = p->nParsVIni + iVar2 * p->nParsVNum + k;
            }
1092
            Ifn_NtkAddConstrOne( pSat, vCover, pVars, 2*p->nParsVNum );
1093 1094 1095 1096
//            printf( "added constraint with %d clauses for %d and %d\n", Vec_IntSize(vCover), iVar1, iVar2 );
        }
    }
    Vec_IntFree( vCover );
1097
}
1098

1099 1100
/**Function*************************************************************

1101
  Synopsis    [Derive clauses given variable assignment.]
1102 1103 1104 1105 1106 1107 1108 1109

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1110
int Ifn_NtkAddClauses( Ifn_Ntk_t * p, int * pValues, sat_solver * pSat )
1111
{
1112 1113 1114
    int i, f, v, nLits, pLits[IFN_INS+2], pLits2[IFN_INS+2];
    // assign new variables
    int nSatVars = sat_solver_nvars(pSat);
1115 1116
//    for ( i = 0; i < p->nObjs-1; i++ )
    for ( i = 0; i < p->nObjs; i++ )
1117
        p->Nodes[i].Var = nSatVars++;
1118
    //p->Nodes[p->nObjs-1].Var = 0xFFFF;
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    sat_solver_setnvars( pSat, nSatVars );
    // verify variable values
    for ( i = 0; i < p->nVars; i++ )
        assert( pValues[i] != -1 );
    for ( i = p->nVars; i < p->nObjs-1; i++ )
        assert( pValues[i] == -1 );
    assert( pValues[p->nObjs-1] != -1 );
    // internal variables
//printf( "\n" );
    for ( i = 0; i < p->nInps; i++ )
1129
    {
1130 1131
        int iParStart = p->nParsVIni + i * p->nParsVNum;
        for ( v = 0; v < p->nVars; v++ )
1132
        {
1133 1134 1135 1136 1137
            // add output literal
            pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, pValues[v]==0 );
            // add clause literals
            for ( f = 0; f < p->nParsVNum; f++ )
                pLits[f+1] = Abc_Var2Lit( iParStart + f, (v >> f) & 1 ); 
1138 1139
            if ( !Ifn_AddClause( pSat, pLits, pLits+p->nParsVNum+1 ) )
                return 0;
1140 1141
        }
    }
1142 1143 1144 1145 1146
//printf( "\n" );
    for ( i = p->nInps; i < p->nObjs; i++ )
    {
        int nFans = p->Nodes[i].nFanins;
        int * pFans = p->Nodes[i].Fanins;
1147
        if ( p->Nodes[i].Type == IFN_DSD_AND )
1148 1149 1150 1151 1152 1153 1154 1155 1156
        {
            nLits = 0;
            pLits[nLits++] = Abc_Var2Lit( p->Nodes[i].Var, 0 );
            for ( f = 0; f < nFans; f++ )
            {
                pLits[nLits++] = Abc_Var2Lit( p->Nodes[pFans[f]].Var, 1 );
                // add small clause
                pLits2[0] = Abc_Var2Lit( p->Nodes[i].Var, 1 );
                pLits2[1] = Abc_Var2Lit( p->Nodes[pFans[f]].Var, 0 );
1157 1158
                if ( !Ifn_AddClause( pSat, pLits2, pLits2 + 2 ) )
                    return 0;
1159 1160
            }
            // add big clause
1161 1162
            if ( !Ifn_AddClause( pSat, pLits, pLits + nLits ) )
                return 0;
1163
        }
1164
        else if ( p->Nodes[i].Type == IFN_DSD_XOR )
1165
        {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
            int m, nMints = (1 << (nFans+1));
            for ( m = 0; m < nMints; m++ )
            {
                // skip even 
                int Count = 0;
                for ( v = 0; v <= nFans; v++ )
                    Count += ((m >> v) & 1);
                if ( (Count & 1) == 0 )
                    continue;
                // generate minterm
                pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, (m >> nFans) & 1 );
                for ( v = 0; v < nFans; v++ )
                    pLits[v+1] = Abc_Var2Lit( p->Nodes[pFans[v]].Var, (m >> v) & 1 );
1179 1180
                if ( !Ifn_AddClause( pSat, pLits, pLits + nFans + 1 ) )
                    return 0;
1181
            }
1182
        }
1183
        else if ( p->Nodes[i].Type == IFN_DSD_MUX )
1184
        {
1185 1186 1187
            pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, 0 );
            pLits[1] = Abc_Var2Lit( p->Nodes[pFans[0]].Var, 1 ); // ctrl
            pLits[2] = Abc_Var2Lit( p->Nodes[pFans[1]].Var, 1 );
1188 1189
            if ( !Ifn_AddClause( pSat, pLits, pLits + 3 ) )
                return 0;
1190 1191 1192 1193

            pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, 1 );
            pLits[1] = Abc_Var2Lit( p->Nodes[pFans[0]].Var, 1 ); // ctrl
            pLits[2] = Abc_Var2Lit( p->Nodes[pFans[1]].Var, 0 );
1194 1195
            if ( !Ifn_AddClause( pSat, pLits, pLits + 3 ) )
                return 0;
1196 1197 1198 1199

            pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, 0 );
            pLits[1] = Abc_Var2Lit( p->Nodes[pFans[0]].Var, 0 ); // ctrl
            pLits[2] = Abc_Var2Lit( p->Nodes[pFans[2]].Var, 1 );
1200 1201
            if ( !Ifn_AddClause( pSat, pLits, pLits + 3 ) )
                return 0;
1202 1203 1204 1205

            pLits[0] = Abc_Var2Lit( p->Nodes[i].Var, 1 );
            pLits[1] = Abc_Var2Lit( p->Nodes[pFans[0]].Var, 0 ); // ctrl
            pLits[2] = Abc_Var2Lit( p->Nodes[pFans[2]].Var, 0 );
1206 1207
            if ( !Ifn_AddClause( pSat, pLits, pLits + 3 ) )
                return 0;
1208
        }
1209
        else if ( p->Nodes[i].Type == IFN_DSD_PRIME )
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        {
            int nValues = (1 << nFans);
            int iParStart = p->Nodes[i].iFirst;
            for ( v = 0; v < nValues; v++ )
            {
                nLits = 0;
                if ( pValues[i] == -1 )
                {
                    pLits[nLits]  = Abc_Var2Lit( p->Nodes[i].Var, 0 );
                    pLits2[nLits] = Abc_Var2Lit( p->Nodes[i].Var, 1 );
                    nLits++;
                }
                for ( f = 0; f < nFans; f++, nLits++ )
                    pLits[nLits] = pLits2[nLits] = Abc_Var2Lit( p->Nodes[pFans[f]].Var, (v >> f) & 1 ); 
                pLits[nLits]  = Abc_Var2Lit( iParStart + v, 1 ); 
                pLits2[nLits] = Abc_Var2Lit( iParStart + v, 0 ); 
                nLits++;
                if ( pValues[i] != 0 )
1228 1229 1230 1231
                {
                    if ( !Ifn_AddClause( pSat, pLits2, pLits2 + nLits ) )
                        return 0;
                }
1232
                if ( pValues[i] != 1 )
1233 1234 1235 1236
                {
                    if ( !Ifn_AddClause( pSat, pLits,  pLits + nLits ) )
                        return 0;
                }
1237 1238 1239 1240 1241
            }
        }
        else assert( 0 );
//printf( "\n" );
    }
1242 1243 1244 1245
    // add last clause (not needed if the root node is IFN_DSD_PRIME)
    pLits[0] = Abc_Var2Lit( p->Nodes[p->nObjs-1].Var, pValues[p->nObjs-1]==0 );
    if ( !Ifn_AddClause( pSat, pLits,  pLits + 1 ) )
        return 0;
1246
    return 1;
1247
}
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259

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

  Synopsis    [Returns the minterm number for which there is a mismatch.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1260
void Ifn_NtkMatchPrintStatus( sat_solver * p, int Iter, int status, int iMint, int Value, abctime clk )
1261
{
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
    printf( "Iter = %5d  ",  Iter );
    printf( "Mint = %5d  ",  iMint );
    printf( "Value = %2d  ", Value );
    printf( "Var = %6d  ",   sat_solver_nvars(p) );
    printf( "Cla = %6d  ",   sat_solver_nclauses(p) );
    printf( "Conf = %6d  ",  sat_solver_nconflicts(p) );
    if ( status == l_False )
        printf( "status = unsat" );
    else if ( status == l_True )
        printf( "status = sat  " );
    else 
        printf( "status = undec" );
1274
    Abc_PrintTime( 1, "Time", clk );
1275
}
1276
void Ifn_NtkMatchPrintConfig( Ifn_Ntk_t * p, sat_solver * pSat )
1277
{
1278
    int v, i;
1279
    for ( v = p->nObjs; v < p->nPars; v++ )
1280
    {
1281
        for ( i = p->nInps; i < p->nObjs; i++ )
1282
            if ( p->Nodes[i].Type == IFN_DSD_PRIME && (int)p->Nodes[i].iFirst == v )
1283 1284 1285 1286
                break;
        if ( i < p->nObjs )
            printf( " " );
        else if ( v >= p->nParsVIni && (v - p->nParsVIni) % p->nParsVNum == 0 )
1287 1288
            printf( " %d=", (v - p->nParsVIni) / p->nParsVNum );
        printf( "%d", sat_solver_var_value(pSat, v) );
1289 1290
    }
}
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
word Ifn_NtkMatchCollectPerm( Ifn_Ntk_t * p, sat_solver * pSat )
{
    word Perm = 0;
    int i, v, Mint;
    assert( p->nParsVNum <= 4 );
    for ( i = 0; i < p->nInps; i++ )
    {
        for ( Mint = v = 0; v < p->nParsVNum; v++ )
            if ( sat_solver_var_value(pSat, p->nParsVIni + i * p->nParsVNum + v) )
                Mint |= (1 << v);
        Abc_TtSetHex( &Perm, i, Mint );
    }
    return Perm;
}
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
void Ifn_NtkMatchCollectConfig( Ifn_Ntk_t * p, sat_solver * pSat, word * pConfig )
{
    int i, v, Mint;
    assert( p->nParsVNum <= 4 );
    for ( i = 0; i < p->nInps; i++ )
    {
        for ( Mint = v = 0; v < p->nParsVNum; v++ )
            if ( sat_solver_var_value(pSat, p->nParsVIni + i * p->nParsVNum + v) )
                Mint |= (1 << v);
        Abc_TtSetHex( pConfig, i, Mint );
    }
    for ( v = p->nObjs; v < p->nParsVIni; v++ )
        if ( sat_solver_var_value(pSat, v) )
            Abc_TtSetBit( pConfig + 1, v - p->nObjs );
}
1320 1321 1322 1323 1324 1325 1326 1327
void Ifn_NtkMatchPrintPerm( word Perm, int nInps )
{
    int i;
    assert( nInps <= 16 );
    for ( i = 0; i < nInps; i++ )
        printf( "%c", 'a' + Abc_TtGetHex(&Perm, i) );
    printf( "\n" );
}
1328
int Ifn_NtkMatch( Ifn_Ntk_t * p, word * pTruth, int nVars, int nConfls, int fVerbose, int fVeryVerbose, word * pConfig )
1329
{
1330 1331 1332 1333
    word * pTruth1;
    int RetValue = 0;
    int nIterMax = (1<<nVars);
    int i, v, status, iMint = 0;
1334
    abctime clk = Abc_Clock();
1335
//    abctime clkTru = 0, clkSat = 0, clk2;
1336 1337 1338 1339
    sat_solver * pSat;
    if ( nVars == 0 )
        return 1;
    pSat = sat_solver_new();
1340 1341
    Ifn_Prepare( p, pTruth, nVars );
    sat_solver_setnvars( pSat, p->nPars );
1342 1343
    Ifn_NtkAddConstraints( p, pSat );
    if ( fVeryVerbose )
1344
        Ifn_NtkMatchPrintStatus( pSat, 0, l_True, -1, -1, Abc_Clock() - clk );
1345
    if ( pConfig ) assert( *pConfig == 0 );
1346 1347 1348 1349 1350 1351 1352
    for ( i = 0; i < nIterMax; i++ )
    {
        // get variable assignment
        for ( v = 0; v < p->nObjs; v++ )
            p->Values[v] = v < p->nVars ? (iMint >> v) & 1 :  -1;
        p->Values[p->nObjs-1] = Abc_TtGetBit( pTruth, iMint );
        // derive clauses
1353
        if ( !Ifn_NtkAddClauses( p, p->Values, pSat ) )
1354 1355 1356
            break;
        // find assignment of parameters
//        clk2 = Abc_Clock();
1357
        status = sat_solver_solve( pSat, NULL, NULL, nConfls, 0, 0, 0 );
1358
//        clkSat += Abc_Clock() - clk2;
1359
        if ( fVeryVerbose )
1360
            Ifn_NtkMatchPrintStatus( pSat, i+1, status, iMint, p->Values[p->nObjs-1], Abc_Clock() - clk );
1361
        if ( status != l_True )
1362 1363 1364 1365 1366 1367
            break;
        // collect assignment
        for ( v = p->nObjs; v < p->nPars; v++ )
            p->Values[v] = sat_solver_var_value(pSat, v);
        // find truth table
//        clk2 = Abc_Clock();
1368
        pTruth1 = Ifn_NtkDeriveTruth( p, p->Values );
1369 1370 1371 1372 1373 1374
//        clkTru += Abc_Clock() - clk2;
        Abc_TtXor( pTruth1, pTruth1, p->pTruth, p->nWords, 0 );
        // find mismatch if present
        iMint = Abc_TtFindFirstBit( pTruth1, p->nVars );
        if ( iMint == -1 )
        {
1375 1376
            if ( pConfig ) 
                Ifn_NtkMatchCollectConfig( p, pSat, pConfig );
1377 1378 1379 1380 1381 1382 1383 1384 1385
/*
            if ( pPerm )
            {
                int RetValue = Ifn_ManSatFindCofigBitsTest( p, pTruth, nVars, *pPerm );
                Ifn_NtkMatchPrintPerm( *pPerm, p->nInps );
                if ( RetValue == 0 )
                    printf( "Verification failed.\n" );
            }
*/
1386 1387 1388 1389 1390
            RetValue = 1;
            break;
        }
    }
    assert( i < nIterMax );
1391 1392 1393 1394
    if ( fVerbose )
    {
        printf( "%s  Iter =%4d. Confl = %6d.  ", RetValue ? "yes":"no ", i, sat_solver_nconflicts(pSat) );
        if ( RetValue )
1395
            Ifn_NtkMatchPrintConfig( p, pSat );
1396 1397
        printf( "\n" );
    }
1398 1399 1400 1401
    sat_solver_delete( pSat );
//    Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
//    Abc_PrintTime( 1, "Sat", clkSat );
//    Abc_PrintTime( 1, "Tru", clkTru );
1402
    return RetValue;
1403 1404
}

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Ifn_NtkRead()
{
    int RetValue;
1419
    int nVars = 8;
1420 1421 1422 1423 1424 1425
//    word * pTruth = Dau_DsdToTruth( "(abcdefghi)", nVars );
    word * pTruth = Dau_DsdToTruth( "1008{(1008{(ab)cde}f)ghi}", nVars );
//    word * pTruth = Dau_DsdToTruth( "18{(1008{(ab)cde}f)gh}", nVars );
//    word * pTruth = Dau_DsdToTruth( "1008{(1008{[ab]cde}f)ghi}", nVars );
//    word * pTruth = Dau_DsdToTruth( "(abcd)", nVars );
//    word * pTruth = Dau_DsdToTruth( "(abc)", nVars );
1426
//    word * pTruth = Dau_DsdToTruth( "18{(1008{(ab)cde}f)gh}", nVars );
1427 1428
//    char * pStr = "e={abc};f={ed};";
//    char * pStr = "d={ab};e={cd};";
1429
//    char * pStr = "j=(ab);k={jcde};l=(kf);m={lghi};";
1430 1431 1432
//    char * pStr = "i={abc};j={ide};k={ifg};l={jkh};";
//    char * pStr = "h={abcde};i={abcdf};j=<ghi>;";
//    char * pStr = "g=<abc>;h=<ade>;i={fgh};";
1433 1434
//    char * pStr = "i=<abc>;j=(def);k=[gh];l={ijk};";
    char * pStr = "{({(ab)cde}f)ghi};AB;CD;DE;GH;HI";
1435
    Ifn_Ntk_t * p = Ifn_NtkParse( pStr );
1436
    word Perm = 0;
1437 1438
    if ( p == NULL )
        return;
1439 1440 1441
    Ifn_NtkPrint( p );
    Dau_DsdPrintFromTruth( pTruth, nVars );
    // get the given function
1442
    RetValue = Ifn_NtkMatch( p, pTruth, nVars, 0, 1, 1, &Perm );
1443
    ABC_FREE( p );
1444 1445
}

1446 1447 1448 1449 1450 1451 1452
////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


ABC_NAMESPACE_IMPL_END