000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains routines used for analyzing expressions and
000013  ** for generating VDBE code that evaluates expressions in SQLite.
000014  */
000015  #include "sqliteInt.h"
000016  
000017  /* Forward declarations */
000018  static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
000019  static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
000020  
000021  /*
000022  ** Return the affinity character for a single column of a table.
000023  */
000024  char sqlite3TableColumnAffinity(Table *pTab, int iCol){
000025    assert( iCol<pTab->nCol );
000026    return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
000027  }
000028  
000029  /*
000030  ** Return the 'affinity' of the expression pExpr if any.
000031  **
000032  ** If pExpr is a column, a reference to a column via an 'AS' alias,
000033  ** or a sub-select with a column as the return value, then the 
000034  ** affinity of that column is returned. Otherwise, 0x00 is returned,
000035  ** indicating no affinity for the expression.
000036  **
000037  ** i.e. the WHERE clause expressions in the following statements all
000038  ** have an affinity:
000039  **
000040  ** CREATE TABLE t1(a);
000041  ** SELECT * FROM t1 WHERE a;
000042  ** SELECT a AS b FROM t1 WHERE b;
000043  ** SELECT * FROM t1 WHERE (select a from t1);
000044  */
000045  char sqlite3ExprAffinity(Expr *pExpr){
000046    int op;
000047    while( ExprHasProperty(pExpr, EP_Skip) ){
000048      assert( pExpr->op==TK_COLLATE );
000049      pExpr = pExpr->pLeft;
000050      assert( pExpr!=0 );
000051    }
000052    op = pExpr->op;
000053    if( op==TK_SELECT ){
000054      assert( pExpr->flags&EP_xIsSelect );
000055      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
000056    }
000057    if( op==TK_REGISTER ) op = pExpr->op2;
000058  #ifndef SQLITE_OMIT_CAST
000059    if( op==TK_CAST ){
000060      assert( !ExprHasProperty(pExpr, EP_IntValue) );
000061      return sqlite3AffinityType(pExpr->u.zToken, 0);
000062    }
000063  #endif
000064    if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
000065      return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
000066    }
000067    if( op==TK_SELECT_COLUMN ){
000068      assert( pExpr->pLeft->flags&EP_xIsSelect );
000069      return sqlite3ExprAffinity(
000070          pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
000071      );
000072    }
000073    if( op==TK_VECTOR ){
000074      return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
000075    }
000076    return pExpr->affExpr;
000077  }
000078  
000079  /*
000080  ** Set the collating sequence for expression pExpr to be the collating
000081  ** sequence named by pToken.   Return a pointer to a new Expr node that
000082  ** implements the COLLATE operator.
000083  **
000084  ** If a memory allocation error occurs, that fact is recorded in pParse->db
000085  ** and the pExpr parameter is returned unchanged.
000086  */
000087  Expr *sqlite3ExprAddCollateToken(
000088    Parse *pParse,           /* Parsing context */
000089    Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
000090    const Token *pCollName,  /* Name of collating sequence */
000091    int dequote              /* True to dequote pCollName */
000092  ){
000093    if( pCollName->n>0 ){
000094      Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
000095      if( pNew ){
000096        pNew->pLeft = pExpr;
000097        pNew->flags |= EP_Collate|EP_Skip;
000098        pExpr = pNew;
000099      }
000100    }
000101    return pExpr;
000102  }
000103  Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
000104    Token s;
000105    assert( zC!=0 );
000106    sqlite3TokenInit(&s, (char*)zC);
000107    return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
000108  }
000109  
000110  /*
000111  ** Skip over any TK_COLLATE operators.
000112  */
000113  Expr *sqlite3ExprSkipCollate(Expr *pExpr){
000114    while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
000115      assert( pExpr->op==TK_COLLATE );
000116      pExpr = pExpr->pLeft;
000117    }   
000118    return pExpr;
000119  }
000120  
000121  /*
000122  ** Skip over any TK_COLLATE operators and/or any unlikely()
000123  ** or likelihood() or likely() functions at the root of an
000124  ** expression.
000125  */
000126  Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
000127    while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
000128      if( ExprHasProperty(pExpr, EP_Unlikely) ){
000129        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
000130        assert( pExpr->x.pList->nExpr>0 );
000131        assert( pExpr->op==TK_FUNCTION );
000132        pExpr = pExpr->x.pList->a[0].pExpr;
000133      }else{
000134        assert( pExpr->op==TK_COLLATE );
000135        pExpr = pExpr->pLeft;
000136      }
000137    }   
000138    return pExpr;
000139  }
000140  
000141  /*
000142  ** Return the collation sequence for the expression pExpr. If
000143  ** there is no defined collating sequence, return NULL.
000144  **
000145  ** See also: sqlite3ExprNNCollSeq()
000146  **
000147  ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
000148  ** default collation if pExpr has no defined collation.
000149  **
000150  ** The collating sequence might be determined by a COLLATE operator
000151  ** or by the presence of a column with a defined collating sequence.
000152  ** COLLATE operators take first precedence.  Left operands take
000153  ** precedence over right operands.
000154  */
000155  CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
000156    sqlite3 *db = pParse->db;
000157    CollSeq *pColl = 0;
000158    Expr *p = pExpr;
000159    while( p ){
000160      int op = p->op;
000161      if( op==TK_REGISTER ) op = p->op2;
000162      if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
000163       && p->y.pTab!=0
000164      ){
000165        /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
000166        ** a TK_COLUMN but was previously evaluated and cached in a register */
000167        int j = p->iColumn;
000168        if( j>=0 ){
000169          const char *zColl = p->y.pTab->aCol[j].zColl;
000170          pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
000171        }
000172        break;
000173      }
000174      if( op==TK_CAST || op==TK_UPLUS ){
000175        p = p->pLeft;
000176        continue;
000177      }
000178      if( op==TK_VECTOR ){
000179        p = p->x.pList->a[0].pExpr;
000180        continue;
000181      }
000182      if( op==TK_COLLATE ){
000183        pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
000184        break;
000185      }
000186      if( p->flags & EP_Collate ){
000187        if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
000188          p = p->pLeft;
000189        }else{
000190          Expr *pNext  = p->pRight;
000191          /* The Expr.x union is never used at the same time as Expr.pRight */
000192          assert( p->x.pList==0 || p->pRight==0 );
000193          if( p->x.pList!=0 
000194           && !db->mallocFailed
000195           && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
000196          ){
000197            int i;
000198            for(i=0; i<p->x.pList->nExpr; i++){
000199              if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
000200                pNext = p->x.pList->a[i].pExpr;
000201                break;
000202              }
000203            }
000204          }
000205          p = pNext;
000206        }
000207      }else{
000208        break;
000209      }
000210    }
000211    if( sqlite3CheckCollSeq(pParse, pColl) ){ 
000212      pColl = 0;
000213    }
000214    return pColl;
000215  }
000216  
000217  /*
000218  ** Return the collation sequence for the expression pExpr. If
000219  ** there is no defined collating sequence, return a pointer to the
000220  ** defautl collation sequence.
000221  **
000222  ** See also: sqlite3ExprCollSeq()
000223  **
000224  ** The sqlite3ExprCollSeq() routine works the same except that it
000225  ** returns NULL if there is no defined collation.
000226  */
000227  CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
000228    CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
000229    if( p==0 ) p = pParse->db->pDfltColl;
000230    assert( p!=0 );
000231    return p;
000232  }
000233  
000234  /*
000235  ** Return TRUE if the two expressions have equivalent collating sequences.
000236  */
000237  int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
000238    CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
000239    CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
000240    return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
000241  }
000242  
000243  /*
000244  ** pExpr is an operand of a comparison operator.  aff2 is the
000245  ** type affinity of the other operand.  This routine returns the
000246  ** type affinity that should be used for the comparison operator.
000247  */
000248  char sqlite3CompareAffinity(Expr *pExpr, char aff2){
000249    char aff1 = sqlite3ExprAffinity(pExpr);
000250    if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
000251      /* Both sides of the comparison are columns. If one has numeric
000252      ** affinity, use that. Otherwise use no affinity.
000253      */
000254      if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
000255        return SQLITE_AFF_NUMERIC;
000256      }else{
000257        return SQLITE_AFF_BLOB;
000258      }
000259    }else{
000260      /* One side is a column, the other is not. Use the columns affinity. */
000261      assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
000262      return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
000263    }
000264  }
000265  
000266  /*
000267  ** pExpr is a comparison operator.  Return the type affinity that should
000268  ** be applied to both operands prior to doing the comparison.
000269  */
000270  static char comparisonAffinity(Expr *pExpr){
000271    char aff;
000272    assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
000273            pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
000274            pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
000275    assert( pExpr->pLeft );
000276    aff = sqlite3ExprAffinity(pExpr->pLeft);
000277    if( pExpr->pRight ){
000278      aff = sqlite3CompareAffinity(pExpr->pRight, aff);
000279    }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
000280      aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
000281    }else if( aff==0 ){
000282      aff = SQLITE_AFF_BLOB;
000283    }
000284    return aff;
000285  }
000286  
000287  /*
000288  ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
000289  ** idx_affinity is the affinity of an indexed column. Return true
000290  ** if the index with affinity idx_affinity may be used to implement
000291  ** the comparison in pExpr.
000292  */
000293  int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
000294    char aff = comparisonAffinity(pExpr);
000295    if( aff<SQLITE_AFF_TEXT ){
000296      return 1;
000297    }
000298    if( aff==SQLITE_AFF_TEXT ){
000299      return idx_affinity==SQLITE_AFF_TEXT;
000300    }
000301    return sqlite3IsNumericAffinity(idx_affinity);
000302  }
000303  
000304  /*
000305  ** Return the P5 value that should be used for a binary comparison
000306  ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
000307  */
000308  static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
000309    u8 aff = (char)sqlite3ExprAffinity(pExpr2);
000310    aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
000311    return aff;
000312  }
000313  
000314  /*
000315  ** Return a pointer to the collation sequence that should be used by
000316  ** a binary comparison operator comparing pLeft and pRight.
000317  **
000318  ** If the left hand expression has a collating sequence type, then it is
000319  ** used. Otherwise the collation sequence for the right hand expression
000320  ** is used, or the default (BINARY) if neither expression has a collating
000321  ** type.
000322  **
000323  ** Argument pRight (but not pLeft) may be a null pointer. In this case,
000324  ** it is not considered.
000325  */
000326  CollSeq *sqlite3BinaryCompareCollSeq(
000327    Parse *pParse, 
000328    Expr *pLeft, 
000329    Expr *pRight
000330  ){
000331    CollSeq *pColl;
000332    assert( pLeft );
000333    if( pLeft->flags & EP_Collate ){
000334      pColl = sqlite3ExprCollSeq(pParse, pLeft);
000335    }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
000336      pColl = sqlite3ExprCollSeq(pParse, pRight);
000337    }else{
000338      pColl = sqlite3ExprCollSeq(pParse, pLeft);
000339      if( !pColl ){
000340        pColl = sqlite3ExprCollSeq(pParse, pRight);
000341      }
000342    }
000343    return pColl;
000344  }
000345  
000346  /* Expresssion p is a comparison operator.  Return a collation sequence
000347  ** appropriate for the comparison operator.
000348  **
000349  ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
000350  ** However, if the OP_Commuted flag is set, then the order of the operands
000351  ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
000352  ** correct collating sequence is found.
000353  */
000354  CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){
000355    if( ExprHasProperty(p, EP_Commuted) ){
000356      return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
000357    }else{
000358      return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
000359    }
000360  }
000361  
000362  /*
000363  ** Generate code for a comparison operator.
000364  */
000365  static int codeCompare(
000366    Parse *pParse,    /* The parsing (and code generating) context */
000367    Expr *pLeft,      /* The left operand */
000368    Expr *pRight,     /* The right operand */
000369    int opcode,       /* The comparison opcode */
000370    int in1, int in2, /* Register holding operands */
000371    int dest,         /* Jump here if true.  */
000372    int jumpIfNull,   /* If true, jump if either operand is NULL */
000373    int isCommuted    /* The comparison has been commuted */
000374  ){
000375    int p5;
000376    int addr;
000377    CollSeq *p4;
000378  
000379    if( pParse->nErr ) return 0;
000380    if( isCommuted ){
000381      p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
000382    }else{
000383      p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
000384    }
000385    p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
000386    addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
000387                             (void*)p4, P4_COLLSEQ);
000388    sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
000389    return addr;
000390  }
000391  
000392  /*
000393  ** Return true if expression pExpr is a vector, or false otherwise.
000394  **
000395  ** A vector is defined as any expression that results in two or more
000396  ** columns of result.  Every TK_VECTOR node is an vector because the
000397  ** parser will not generate a TK_VECTOR with fewer than two entries.
000398  ** But a TK_SELECT might be either a vector or a scalar. It is only
000399  ** considered a vector if it has two or more result columns.
000400  */
000401  int sqlite3ExprIsVector(Expr *pExpr){
000402    return sqlite3ExprVectorSize(pExpr)>1;
000403  }
000404  
000405  /*
000406  ** If the expression passed as the only argument is of type TK_VECTOR 
000407  ** return the number of expressions in the vector. Or, if the expression
000408  ** is a sub-select, return the number of columns in the sub-select. For
000409  ** any other type of expression, return 1.
000410  */
000411  int sqlite3ExprVectorSize(Expr *pExpr){
000412    u8 op = pExpr->op;
000413    if( op==TK_REGISTER ) op = pExpr->op2;
000414    if( op==TK_VECTOR ){
000415      return pExpr->x.pList->nExpr;
000416    }else if( op==TK_SELECT ){
000417      return pExpr->x.pSelect->pEList->nExpr;
000418    }else{
000419      return 1;
000420    }
000421  }
000422  
000423  /*
000424  ** Return a pointer to a subexpression of pVector that is the i-th
000425  ** column of the vector (numbered starting with 0).  The caller must
000426  ** ensure that i is within range.
000427  **
000428  ** If pVector is really a scalar (and "scalar" here includes subqueries
000429  ** that return a single column!) then return pVector unmodified.
000430  **
000431  ** pVector retains ownership of the returned subexpression.
000432  **
000433  ** If the vector is a (SELECT ...) then the expression returned is
000434  ** just the expression for the i-th term of the result set, and may
000435  ** not be ready for evaluation because the table cursor has not yet
000436  ** been positioned.
000437  */
000438  Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
000439    assert( i<sqlite3ExprVectorSize(pVector) );
000440    if( sqlite3ExprIsVector(pVector) ){
000441      assert( pVector->op2==0 || pVector->op==TK_REGISTER );
000442      if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
000443        return pVector->x.pSelect->pEList->a[i].pExpr;
000444      }else{
000445        return pVector->x.pList->a[i].pExpr;
000446      }
000447    }
000448    return pVector;
000449  }
000450  
000451  /*
000452  ** Compute and return a new Expr object which when passed to
000453  ** sqlite3ExprCode() will generate all necessary code to compute
000454  ** the iField-th column of the vector expression pVector.
000455  **
000456  ** It is ok for pVector to be a scalar (as long as iField==0).  
000457  ** In that case, this routine works like sqlite3ExprDup().
000458  **
000459  ** The caller owns the returned Expr object and is responsible for
000460  ** ensuring that the returned value eventually gets freed.
000461  **
000462  ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
000463  ** then the returned object will reference pVector and so pVector must remain
000464  ** valid for the life of the returned object.  If pVector is a TK_VECTOR
000465  ** or a scalar expression, then it can be deleted as soon as this routine
000466  ** returns.
000467  **
000468  ** A trick to cause a TK_SELECT pVector to be deleted together with
000469  ** the returned Expr object is to attach the pVector to the pRight field
000470  ** of the returned TK_SELECT_COLUMN Expr object.
000471  */
000472  Expr *sqlite3ExprForVectorField(
000473    Parse *pParse,       /* Parsing context */
000474    Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
000475    int iField           /* Which column of the vector to return */
000476  ){
000477    Expr *pRet;
000478    if( pVector->op==TK_SELECT ){
000479      assert( pVector->flags & EP_xIsSelect );
000480      /* The TK_SELECT_COLUMN Expr node:
000481      **
000482      ** pLeft:           pVector containing TK_SELECT.  Not deleted.
000483      ** pRight:          not used.  But recursively deleted.
000484      ** iColumn:         Index of a column in pVector
000485      ** iTable:          0 or the number of columns on the LHS of an assignment
000486      ** pLeft->iTable:   First in an array of register holding result, or 0
000487      **                  if the result is not yet computed.
000488      **
000489      ** sqlite3ExprDelete() specifically skips the recursive delete of
000490      ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
000491      ** can be attached to pRight to cause this node to take ownership of
000492      ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
000493      ** with the same pLeft pointer to the pVector, but only one of them
000494      ** will own the pVector.
000495      */
000496      pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
000497      if( pRet ){
000498        pRet->iColumn = iField;
000499        pRet->pLeft = pVector;
000500      }
000501      assert( pRet==0 || pRet->iTable==0 );
000502    }else{
000503      if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
000504      pRet = sqlite3ExprDup(pParse->db, pVector, 0);
000505      sqlite3RenameTokenRemap(pParse, pRet, pVector);
000506    }
000507    return pRet;
000508  }
000509  
000510  /*
000511  ** If expression pExpr is of type TK_SELECT, generate code to evaluate
000512  ** it. Return the register in which the result is stored (or, if the 
000513  ** sub-select returns more than one column, the first in an array
000514  ** of registers in which the result is stored).
000515  **
000516  ** If pExpr is not a TK_SELECT expression, return 0.
000517  */
000518  static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
000519    int reg = 0;
000520  #ifndef SQLITE_OMIT_SUBQUERY
000521    if( pExpr->op==TK_SELECT ){
000522      reg = sqlite3CodeSubselect(pParse, pExpr);
000523    }
000524  #endif
000525    return reg;
000526  }
000527  
000528  /*
000529  ** Argument pVector points to a vector expression - either a TK_VECTOR
000530  ** or TK_SELECT that returns more than one column. This function returns
000531  ** the register number of a register that contains the value of
000532  ** element iField of the vector.
000533  **
000534  ** If pVector is a TK_SELECT expression, then code for it must have 
000535  ** already been generated using the exprCodeSubselect() routine. In this
000536  ** case parameter regSelect should be the first in an array of registers
000537  ** containing the results of the sub-select. 
000538  **
000539  ** If pVector is of type TK_VECTOR, then code for the requested field
000540  ** is generated. In this case (*pRegFree) may be set to the number of
000541  ** a temporary register to be freed by the caller before returning.
000542  **
000543  ** Before returning, output parameter (*ppExpr) is set to point to the
000544  ** Expr object corresponding to element iElem of the vector.
000545  */
000546  static int exprVectorRegister(
000547    Parse *pParse,                  /* Parse context */
000548    Expr *pVector,                  /* Vector to extract element from */
000549    int iField,                     /* Field to extract from pVector */
000550    int regSelect,                  /* First in array of registers */
000551    Expr **ppExpr,                  /* OUT: Expression element */
000552    int *pRegFree                   /* OUT: Temp register to free */
000553  ){
000554    u8 op = pVector->op;
000555    assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
000556    if( op==TK_REGISTER ){
000557      *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
000558      return pVector->iTable+iField;
000559    }
000560    if( op==TK_SELECT ){
000561      *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
000562       return regSelect+iField;
000563    }
000564    *ppExpr = pVector->x.pList->a[iField].pExpr;
000565    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
000566  }
000567  
000568  /*
000569  ** Expression pExpr is a comparison between two vector values. Compute
000570  ** the result of the comparison (1, 0, or NULL) and write that
000571  ** result into register dest.
000572  **
000573  ** The caller must satisfy the following preconditions:
000574  **
000575  **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
000576  **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
000577  **    otherwise:                op==pExpr->op and p5==0
000578  */
000579  static void codeVectorCompare(
000580    Parse *pParse,        /* Code generator context */
000581    Expr *pExpr,          /* The comparison operation */
000582    int dest,             /* Write results into this register */
000583    u8 op,                /* Comparison operator */
000584    u8 p5                 /* SQLITE_NULLEQ or zero */
000585  ){
000586    Vdbe *v = pParse->pVdbe;
000587    Expr *pLeft = pExpr->pLeft;
000588    Expr *pRight = pExpr->pRight;
000589    int nLeft = sqlite3ExprVectorSize(pLeft);
000590    int i;
000591    int regLeft = 0;
000592    int regRight = 0;
000593    u8 opx = op;
000594    int addrDone = sqlite3VdbeMakeLabel(pParse);
000595    int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
000596  
000597    if( pParse->nErr ) return;
000598    if( nLeft!=sqlite3ExprVectorSize(pRight) ){
000599      sqlite3ErrorMsg(pParse, "row value misused");
000600      return;
000601    }
000602    assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 
000603         || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 
000604         || pExpr->op==TK_LT || pExpr->op==TK_GT 
000605         || pExpr->op==TK_LE || pExpr->op==TK_GE 
000606    );
000607    assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
000608              || (pExpr->op==TK_ISNOT && op==TK_NE) );
000609    assert( p5==0 || pExpr->op!=op );
000610    assert( p5==SQLITE_NULLEQ || pExpr->op==op );
000611  
000612    p5 |= SQLITE_STOREP2;
000613    if( opx==TK_LE ) opx = TK_LT;
000614    if( opx==TK_GE ) opx = TK_GT;
000615  
000616    regLeft = exprCodeSubselect(pParse, pLeft);
000617    regRight = exprCodeSubselect(pParse, pRight);
000618  
000619    for(i=0; 1 /*Loop exits by "break"*/; i++){
000620      int regFree1 = 0, regFree2 = 0;
000621      Expr *pL, *pR; 
000622      int r1, r2;
000623      assert( i>=0 && i<nLeft );
000624      r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
000625      r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
000626      codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
000627      testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
000628      testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
000629      testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
000630      testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
000631      testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
000632      testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
000633      sqlite3ReleaseTempReg(pParse, regFree1);
000634      sqlite3ReleaseTempReg(pParse, regFree2);
000635      if( i==nLeft-1 ){
000636        break;
000637      }
000638      if( opx==TK_EQ ){
000639        sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
000640        p5 |= SQLITE_KEEPNULL;
000641      }else if( opx==TK_NE ){
000642        sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
000643        p5 |= SQLITE_KEEPNULL;
000644      }else{
000645        assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
000646        sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
000647        VdbeCoverageIf(v, op==TK_LT);
000648        VdbeCoverageIf(v, op==TK_GT);
000649        VdbeCoverageIf(v, op==TK_LE);
000650        VdbeCoverageIf(v, op==TK_GE);
000651        if( i==nLeft-2 ) opx = op;
000652      }
000653    }
000654    sqlite3VdbeResolveLabel(v, addrDone);
000655  }
000656  
000657  #if SQLITE_MAX_EXPR_DEPTH>0
000658  /*
000659  ** Check that argument nHeight is less than or equal to the maximum
000660  ** expression depth allowed. If it is not, leave an error message in
000661  ** pParse.
000662  */
000663  int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
000664    int rc = SQLITE_OK;
000665    int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
000666    if( nHeight>mxHeight ){
000667      sqlite3ErrorMsg(pParse, 
000668         "Expression tree is too large (maximum depth %d)", mxHeight
000669      );
000670      rc = SQLITE_ERROR;
000671    }
000672    return rc;
000673  }
000674  
000675  /* The following three functions, heightOfExpr(), heightOfExprList()
000676  ** and heightOfSelect(), are used to determine the maximum height
000677  ** of any expression tree referenced by the structure passed as the
000678  ** first argument.
000679  **
000680  ** If this maximum height is greater than the current value pointed
000681  ** to by pnHeight, the second parameter, then set *pnHeight to that
000682  ** value.
000683  */
000684  static void heightOfExpr(Expr *p, int *pnHeight){
000685    if( p ){
000686      if( p->nHeight>*pnHeight ){
000687        *pnHeight = p->nHeight;
000688      }
000689    }
000690  }
000691  static void heightOfExprList(ExprList *p, int *pnHeight){
000692    if( p ){
000693      int i;
000694      for(i=0; i<p->nExpr; i++){
000695        heightOfExpr(p->a[i].pExpr, pnHeight);
000696      }
000697    }
000698  }
000699  static void heightOfSelect(Select *pSelect, int *pnHeight){
000700    Select *p;
000701    for(p=pSelect; p; p=p->pPrior){
000702      heightOfExpr(p->pWhere, pnHeight);
000703      heightOfExpr(p->pHaving, pnHeight);
000704      heightOfExpr(p->pLimit, pnHeight);
000705      heightOfExprList(p->pEList, pnHeight);
000706      heightOfExprList(p->pGroupBy, pnHeight);
000707      heightOfExprList(p->pOrderBy, pnHeight);
000708    }
000709  }
000710  
000711  /*
000712  ** Set the Expr.nHeight variable in the structure passed as an 
000713  ** argument. An expression with no children, Expr.pList or 
000714  ** Expr.pSelect member has a height of 1. Any other expression
000715  ** has a height equal to the maximum height of any other 
000716  ** referenced Expr plus one.
000717  **
000718  ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
000719  ** if appropriate.
000720  */
000721  static void exprSetHeight(Expr *p){
000722    int nHeight = 0;
000723    heightOfExpr(p->pLeft, &nHeight);
000724    heightOfExpr(p->pRight, &nHeight);
000725    if( ExprHasProperty(p, EP_xIsSelect) ){
000726      heightOfSelect(p->x.pSelect, &nHeight);
000727    }else if( p->x.pList ){
000728      heightOfExprList(p->x.pList, &nHeight);
000729      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
000730    }
000731    p->nHeight = nHeight + 1;
000732  }
000733  
000734  /*
000735  ** Set the Expr.nHeight variable using the exprSetHeight() function. If
000736  ** the height is greater than the maximum allowed expression depth,
000737  ** leave an error in pParse.
000738  **
000739  ** Also propagate all EP_Propagate flags from the Expr.x.pList into
000740  ** Expr.flags. 
000741  */
000742  void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
000743    if( pParse->nErr ) return;
000744    exprSetHeight(p);
000745    sqlite3ExprCheckHeight(pParse, p->nHeight);
000746  }
000747  
000748  /*
000749  ** Return the maximum height of any expression tree referenced
000750  ** by the select statement passed as an argument.
000751  */
000752  int sqlite3SelectExprHeight(Select *p){
000753    int nHeight = 0;
000754    heightOfSelect(p, &nHeight);
000755    return nHeight;
000756  }
000757  #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
000758  /*
000759  ** Propagate all EP_Propagate flags from the Expr.x.pList into
000760  ** Expr.flags. 
000761  */
000762  void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
000763    if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
000764      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
000765    }
000766  }
000767  #define exprSetHeight(y)
000768  #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
000769  
000770  /*
000771  ** This routine is the core allocator for Expr nodes.
000772  **
000773  ** Construct a new expression node and return a pointer to it.  Memory
000774  ** for this node and for the pToken argument is a single allocation
000775  ** obtained from sqlite3DbMalloc().  The calling function
000776  ** is responsible for making sure the node eventually gets freed.
000777  **
000778  ** If dequote is true, then the token (if it exists) is dequoted.
000779  ** If dequote is false, no dequoting is performed.  The deQuote
000780  ** parameter is ignored if pToken is NULL or if the token does not
000781  ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
000782  ** then the EP_DblQuoted flag is set on the expression node.
000783  **
000784  ** Special case:  If op==TK_INTEGER and pToken points to a string that
000785  ** can be translated into a 32-bit integer, then the token is not
000786  ** stored in u.zToken.  Instead, the integer values is written
000787  ** into u.iValue and the EP_IntValue flag is set.  No extra storage
000788  ** is allocated to hold the integer text and the dequote flag is ignored.
000789  */
000790  Expr *sqlite3ExprAlloc(
000791    sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
000792    int op,                 /* Expression opcode */
000793    const Token *pToken,    /* Token argument.  Might be NULL */
000794    int dequote             /* True to dequote */
000795  ){
000796    Expr *pNew;
000797    int nExtra = 0;
000798    int iValue = 0;
000799  
000800    assert( db!=0 );
000801    if( pToken ){
000802      if( op!=TK_INTEGER || pToken->z==0
000803            || sqlite3GetInt32(pToken->z, &iValue)==0 ){
000804        nExtra = pToken->n+1;
000805        assert( iValue>=0 );
000806      }
000807    }
000808    pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
000809    if( pNew ){
000810      memset(pNew, 0, sizeof(Expr));
000811      pNew->op = (u8)op;
000812      pNew->iAgg = -1;
000813      if( pToken ){
000814        if( nExtra==0 ){
000815          pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
000816          pNew->u.iValue = iValue;
000817        }else{
000818          pNew->u.zToken = (char*)&pNew[1];
000819          assert( pToken->z!=0 || pToken->n==0 );
000820          if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
000821          pNew->u.zToken[pToken->n] = 0;
000822          if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
000823            sqlite3DequoteExpr(pNew);
000824          }
000825        }
000826      }
000827  #if SQLITE_MAX_EXPR_DEPTH>0
000828      pNew->nHeight = 1;
000829  #endif  
000830    }
000831    return pNew;
000832  }
000833  
000834  /*
000835  ** Allocate a new expression node from a zero-terminated token that has
000836  ** already been dequoted.
000837  */
000838  Expr *sqlite3Expr(
000839    sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
000840    int op,                 /* Expression opcode */
000841    const char *zToken      /* Token argument.  Might be NULL */
000842  ){
000843    Token x;
000844    x.z = zToken;
000845    x.n = sqlite3Strlen30(zToken);
000846    return sqlite3ExprAlloc(db, op, &x, 0);
000847  }
000848  
000849  /*
000850  ** Attach subtrees pLeft and pRight to the Expr node pRoot.
000851  **
000852  ** If pRoot==NULL that means that a memory allocation error has occurred.
000853  ** In that case, delete the subtrees pLeft and pRight.
000854  */
000855  void sqlite3ExprAttachSubtrees(
000856    sqlite3 *db,
000857    Expr *pRoot,
000858    Expr *pLeft,
000859    Expr *pRight
000860  ){
000861    if( pRoot==0 ){
000862      assert( db->mallocFailed );
000863      sqlite3ExprDelete(db, pLeft);
000864      sqlite3ExprDelete(db, pRight);
000865    }else{
000866      if( pRight ){
000867        pRoot->pRight = pRight;
000868        pRoot->flags |= EP_Propagate & pRight->flags;
000869      }
000870      if( pLeft ){
000871        pRoot->pLeft = pLeft;
000872        pRoot->flags |= EP_Propagate & pLeft->flags;
000873      }
000874      exprSetHeight(pRoot);
000875    }
000876  }
000877  
000878  /*
000879  ** Allocate an Expr node which joins as many as two subtrees.
000880  **
000881  ** One or both of the subtrees can be NULL.  Return a pointer to the new
000882  ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
000883  ** free the subtrees and return NULL.
000884  */
000885  Expr *sqlite3PExpr(
000886    Parse *pParse,          /* Parsing context */
000887    int op,                 /* Expression opcode */
000888    Expr *pLeft,            /* Left operand */
000889    Expr *pRight            /* Right operand */
000890  ){
000891    Expr *p;
000892    p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
000893    if( p ){
000894      memset(p, 0, sizeof(Expr));
000895      p->op = op & 0xff;
000896      p->iAgg = -1;
000897      sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
000898      sqlite3ExprCheckHeight(pParse, p->nHeight);
000899    }else{
000900      sqlite3ExprDelete(pParse->db, pLeft);
000901      sqlite3ExprDelete(pParse->db, pRight);
000902    }
000903    return p;
000904  }
000905  
000906  /*
000907  ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
000908  ** do a memory allocation failure) then delete the pSelect object.
000909  */
000910  void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
000911    if( pExpr ){
000912      pExpr->x.pSelect = pSelect;
000913      ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
000914      sqlite3ExprSetHeightAndFlags(pParse, pExpr);
000915    }else{
000916      assert( pParse->db->mallocFailed );
000917      sqlite3SelectDelete(pParse->db, pSelect);
000918    }
000919  }
000920  
000921  
000922  /*
000923  ** Join two expressions using an AND operator.  If either expression is
000924  ** NULL, then just return the other expression.
000925  **
000926  ** If one side or the other of the AND is known to be false, then instead
000927  ** of returning an AND expression, just return a constant expression with
000928  ** a value of false.
000929  */
000930  Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
000931    sqlite3 *db = pParse->db;
000932    if( pLeft==0  ){
000933      return pRight;
000934    }else if( pRight==0 ){
000935      return pLeft;
000936    }else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
000937      sqlite3ExprUnmapAndDelete(pParse, pLeft);
000938      sqlite3ExprUnmapAndDelete(pParse, pRight);
000939      return sqlite3Expr(db, TK_INTEGER, "0");
000940    }else{
000941      return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
000942    }
000943  }
000944  
000945  /*
000946  ** Construct a new expression node for a function with multiple
000947  ** arguments.
000948  */
000949  Expr *sqlite3ExprFunction(
000950    Parse *pParse,        /* Parsing context */
000951    ExprList *pList,      /* Argument list */
000952    Token *pToken,        /* Name of the function */
000953    int eDistinct         /* SF_Distinct or SF_ALL or 0 */
000954  ){
000955    Expr *pNew;
000956    sqlite3 *db = pParse->db;
000957    assert( pToken );
000958    pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
000959    if( pNew==0 ){
000960      sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
000961      return 0;
000962    }
000963    if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
000964      sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
000965    }
000966    pNew->x.pList = pList;
000967    ExprSetProperty(pNew, EP_HasFunc);
000968    assert( !ExprHasProperty(pNew, EP_xIsSelect) );
000969    sqlite3ExprSetHeightAndFlags(pParse, pNew);
000970    if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
000971    return pNew;
000972  }
000973  
000974  /*
000975  ** Assign a variable number to an expression that encodes a wildcard
000976  ** in the original SQL statement.  
000977  **
000978  ** Wildcards consisting of a single "?" are assigned the next sequential
000979  ** variable number.
000980  **
000981  ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
000982  ** sure "nnn" is not too big to avoid a denial of service attack when
000983  ** the SQL statement comes from an external source.
000984  **
000985  ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
000986  ** as the previous instance of the same wildcard.  Or if this is the first
000987  ** instance of the wildcard, the next sequential variable number is
000988  ** assigned.
000989  */
000990  void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
000991    sqlite3 *db = pParse->db;
000992    const char *z;
000993    ynVar x;
000994  
000995    if( pExpr==0 ) return;
000996    assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
000997    z = pExpr->u.zToken;
000998    assert( z!=0 );
000999    assert( z[0]!=0 );
001000    assert( n==(u32)sqlite3Strlen30(z) );
001001    if( z[1]==0 ){
001002      /* Wildcard of the form "?".  Assign the next variable number */
001003      assert( z[0]=='?' );
001004      x = (ynVar)(++pParse->nVar);
001005    }else{
001006      int doAdd = 0;
001007      if( z[0]=='?' ){
001008        /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
001009        ** use it as the variable number */
001010        i64 i;
001011        int bOk;
001012        if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
001013          i = z[1]-'0';  /* The common case of ?N for a single digit N */
001014          bOk = 1;
001015        }else{
001016          bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
001017        }
001018        testcase( i==0 );
001019        testcase( i==1 );
001020        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
001021        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
001022        if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
001023          sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
001024              db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
001025          return;
001026        }
001027        x = (ynVar)i;
001028        if( x>pParse->nVar ){
001029          pParse->nVar = (int)x;
001030          doAdd = 1;
001031        }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
001032          doAdd = 1;
001033        }
001034      }else{
001035        /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
001036        ** number as the prior appearance of the same name, or if the name
001037        ** has never appeared before, reuse the same variable number
001038        */
001039        x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
001040        if( x==0 ){
001041          x = (ynVar)(++pParse->nVar);
001042          doAdd = 1;
001043        }
001044      }
001045      if( doAdd ){
001046        pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
001047      }
001048    }
001049    pExpr->iColumn = x;
001050    if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
001051      sqlite3ErrorMsg(pParse, "too many SQL variables");
001052    }
001053  }
001054  
001055  /*
001056  ** Recursively delete an expression tree.
001057  */
001058  static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
001059    assert( p!=0 );
001060    /* Sanity check: Assert that the IntValue is non-negative if it exists */
001061    assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
001062  
001063    assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
001064    assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
001065            || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
001066  #ifdef SQLITE_DEBUG
001067    if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
001068      assert( p->pLeft==0 );
001069      assert( p->pRight==0 );
001070      assert( p->x.pSelect==0 );
001071    }
001072  #endif
001073    if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
001074      /* The Expr.x union is never used at the same time as Expr.pRight */
001075      assert( p->x.pList==0 || p->pRight==0 );
001076      if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
001077      if( p->pRight ){
001078        assert( !ExprHasProperty(p, EP_WinFunc) );
001079        sqlite3ExprDeleteNN(db, p->pRight);
001080      }else if( ExprHasProperty(p, EP_xIsSelect) ){
001081        assert( !ExprHasProperty(p, EP_WinFunc) );
001082        sqlite3SelectDelete(db, p->x.pSelect);
001083      }else{
001084        sqlite3ExprListDelete(db, p->x.pList);
001085  #ifndef SQLITE_OMIT_WINDOWFUNC
001086        if( ExprHasProperty(p, EP_WinFunc) ){
001087          sqlite3WindowDelete(db, p->y.pWin);
001088        }
001089  #endif
001090      }
001091    }
001092    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
001093    if( !ExprHasProperty(p, EP_Static) ){
001094      sqlite3DbFreeNN(db, p);
001095    }
001096  }
001097  void sqlite3ExprDelete(sqlite3 *db, Expr *p){
001098    if( p ) sqlite3ExprDeleteNN(db, p);
001099  }
001100  
001101  /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
001102  ** expression.
001103  */
001104  void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
001105    if( p ){
001106      if( IN_RENAME_OBJECT ){
001107        sqlite3RenameExprUnmap(pParse, p);
001108      }
001109      sqlite3ExprDeleteNN(pParse->db, p);
001110    }
001111  }
001112  
001113  /*
001114  ** Return the number of bytes allocated for the expression structure 
001115  ** passed as the first argument. This is always one of EXPR_FULLSIZE,
001116  ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
001117  */
001118  static int exprStructSize(Expr *p){
001119    if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
001120    if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
001121    return EXPR_FULLSIZE;
001122  }
001123  
001124  /*
001125  ** The dupedExpr*Size() routines each return the number of bytes required
001126  ** to store a copy of an expression or expression tree.  They differ in
001127  ** how much of the tree is measured.
001128  **
001129  **     dupedExprStructSize()     Size of only the Expr structure 
001130  **     dupedExprNodeSize()       Size of Expr + space for token
001131  **     dupedExprSize()           Expr + token + subtree components
001132  **
001133  ***************************************************************************
001134  **
001135  ** The dupedExprStructSize() function returns two values OR-ed together:  
001136  ** (1) the space required for a copy of the Expr structure only and 
001137  ** (2) the EP_xxx flags that indicate what the structure size should be.
001138  ** The return values is always one of:
001139  **
001140  **      EXPR_FULLSIZE
001141  **      EXPR_REDUCEDSIZE   | EP_Reduced
001142  **      EXPR_TOKENONLYSIZE | EP_TokenOnly
001143  **
001144  ** The size of the structure can be found by masking the return value
001145  ** of this routine with 0xfff.  The flags can be found by masking the
001146  ** return value with EP_Reduced|EP_TokenOnly.
001147  **
001148  ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
001149  ** (unreduced) Expr objects as they or originally constructed by the parser.
001150  ** During expression analysis, extra information is computed and moved into
001151  ** later parts of the Expr object and that extra information might get chopped
001152  ** off if the expression is reduced.  Note also that it does not work to
001153  ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
001154  ** to reduce a pristine expression tree from the parser.  The implementation
001155  ** of dupedExprStructSize() contain multiple assert() statements that attempt
001156  ** to enforce this constraint.
001157  */
001158  static int dupedExprStructSize(Expr *p, int flags){
001159    int nSize;
001160    assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
001161    assert( EXPR_FULLSIZE<=0xfff );
001162    assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
001163    if( 0==flags || p->op==TK_SELECT_COLUMN 
001164  #ifndef SQLITE_OMIT_WINDOWFUNC
001165     || ExprHasProperty(p, EP_WinFunc)
001166  #endif
001167    ){
001168      nSize = EXPR_FULLSIZE;
001169    }else{
001170      assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
001171      assert( !ExprHasProperty(p, EP_FromJoin) ); 
001172      assert( !ExprHasProperty(p, EP_MemToken) );
001173      assert( !ExprHasProperty(p, EP_NoReduce) );
001174      if( p->pLeft || p->x.pList ){
001175        nSize = EXPR_REDUCEDSIZE | EP_Reduced;
001176      }else{
001177        assert( p->pRight==0 );
001178        nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
001179      }
001180    }
001181    return nSize;
001182  }
001183  
001184  /*
001185  ** This function returns the space in bytes required to store the copy 
001186  ** of the Expr structure and a copy of the Expr.u.zToken string (if that
001187  ** string is defined.)
001188  */
001189  static int dupedExprNodeSize(Expr *p, int flags){
001190    int nByte = dupedExprStructSize(p, flags) & 0xfff;
001191    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
001192      nByte += sqlite3Strlen30NN(p->u.zToken)+1;
001193    }
001194    return ROUND8(nByte);
001195  }
001196  
001197  /*
001198  ** Return the number of bytes required to create a duplicate of the 
001199  ** expression passed as the first argument. The second argument is a
001200  ** mask containing EXPRDUP_XXX flags.
001201  **
001202  ** The value returned includes space to create a copy of the Expr struct
001203  ** itself and the buffer referred to by Expr.u.zToken, if any.
001204  **
001205  ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
001206  ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
001207  ** and Expr.pRight variables (but not for any structures pointed to or 
001208  ** descended from the Expr.x.pList or Expr.x.pSelect variables).
001209  */
001210  static int dupedExprSize(Expr *p, int flags){
001211    int nByte = 0;
001212    if( p ){
001213      nByte = dupedExprNodeSize(p, flags);
001214      if( flags&EXPRDUP_REDUCE ){
001215        nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
001216      }
001217    }
001218    return nByte;
001219  }
001220  
001221  /*
001222  ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
001223  ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
001224  ** to store the copy of expression p, the copies of p->u.zToken
001225  ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
001226  ** if any. Before returning, *pzBuffer is set to the first byte past the
001227  ** portion of the buffer copied into by this function.
001228  */
001229  static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
001230    Expr *pNew;           /* Value to return */
001231    u8 *zAlloc;           /* Memory space from which to build Expr object */
001232    u32 staticFlag;       /* EP_Static if space not obtained from malloc */
001233  
001234    assert( db!=0 );
001235    assert( p );
001236    assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
001237    assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
001238  
001239    /* Figure out where to write the new Expr structure. */
001240    if( pzBuffer ){
001241      zAlloc = *pzBuffer;
001242      staticFlag = EP_Static;
001243    }else{
001244      zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
001245      staticFlag = 0;
001246    }
001247    pNew = (Expr *)zAlloc;
001248  
001249    if( pNew ){
001250      /* Set nNewSize to the size allocated for the structure pointed to
001251      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
001252      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
001253      ** by the copy of the p->u.zToken string (if any).
001254      */
001255      const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
001256      const int nNewSize = nStructSize & 0xfff;
001257      int nToken;
001258      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
001259        nToken = sqlite3Strlen30(p->u.zToken) + 1;
001260      }else{
001261        nToken = 0;
001262      }
001263      if( dupFlags ){
001264        assert( ExprHasProperty(p, EP_Reduced)==0 );
001265        memcpy(zAlloc, p, nNewSize);
001266      }else{
001267        u32 nSize = (u32)exprStructSize(p);
001268        memcpy(zAlloc, p, nSize);
001269        if( nSize<EXPR_FULLSIZE ){ 
001270          memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
001271        }
001272      }
001273  
001274      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
001275      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
001276      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
001277      pNew->flags |= staticFlag;
001278  
001279      /* Copy the p->u.zToken string, if any. */
001280      if( nToken ){
001281        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
001282        memcpy(zToken, p->u.zToken, nToken);
001283      }
001284  
001285      if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
001286        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
001287        if( ExprHasProperty(p, EP_xIsSelect) ){
001288          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
001289        }else{
001290          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
001291        }
001292      }
001293  
001294      /* Fill in pNew->pLeft and pNew->pRight. */
001295      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
001296        zAlloc += dupedExprNodeSize(p, dupFlags);
001297        if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
001298          pNew->pLeft = p->pLeft ?
001299                        exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
001300          pNew->pRight = p->pRight ?
001301                         exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
001302        }
001303  #ifndef SQLITE_OMIT_WINDOWFUNC
001304        if( ExprHasProperty(p, EP_WinFunc) ){
001305          pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
001306          assert( ExprHasProperty(pNew, EP_WinFunc) );
001307        }
001308  #endif /* SQLITE_OMIT_WINDOWFUNC */
001309        if( pzBuffer ){
001310          *pzBuffer = zAlloc;
001311        }
001312      }else{
001313        if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
001314          if( pNew->op==TK_SELECT_COLUMN ){
001315            pNew->pLeft = p->pLeft;
001316            assert( p->iColumn==0 || p->pRight==0 );
001317            assert( p->pRight==0  || p->pRight==p->pLeft );
001318          }else{
001319            pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
001320          }
001321          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
001322        }
001323      }
001324    }
001325    return pNew;
001326  }
001327  
001328  /*
001329  ** Create and return a deep copy of the object passed as the second 
001330  ** argument. If an OOM condition is encountered, NULL is returned
001331  ** and the db->mallocFailed flag set.
001332  */
001333  #ifndef SQLITE_OMIT_CTE
001334  static With *withDup(sqlite3 *db, With *p){
001335    With *pRet = 0;
001336    if( p ){
001337      sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
001338      pRet = sqlite3DbMallocZero(db, nByte);
001339      if( pRet ){
001340        int i;
001341        pRet->nCte = p->nCte;
001342        for(i=0; i<p->nCte; i++){
001343          pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
001344          pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
001345          pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
001346        }
001347      }
001348    }
001349    return pRet;
001350  }
001351  #else
001352  # define withDup(x,y) 0
001353  #endif
001354  
001355  #ifndef SQLITE_OMIT_WINDOWFUNC
001356  /*
001357  ** The gatherSelectWindows() procedure and its helper routine
001358  ** gatherSelectWindowsCallback() are used to scan all the expressions
001359  ** an a newly duplicated SELECT statement and gather all of the Window
001360  ** objects found there, assembling them onto the linked list at Select->pWin.
001361  */
001362  static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
001363    if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
001364      Select *pSelect = pWalker->u.pSelect;
001365      Window *pWin = pExpr->y.pWin;
001366      assert( pWin );
001367      assert( IsWindowFunc(pExpr) );
001368      assert( pWin->ppThis==0 );
001369      sqlite3WindowLink(pSelect, pWin);
001370    }
001371    return WRC_Continue;
001372  }
001373  static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
001374    return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
001375  }
001376  static void gatherSelectWindows(Select *p){
001377    Walker w;
001378    w.xExprCallback = gatherSelectWindowsCallback;
001379    w.xSelectCallback = gatherSelectWindowsSelectCallback;
001380    w.xSelectCallback2 = 0;
001381    w.pParse = 0;
001382    w.u.pSelect = p;
001383    sqlite3WalkSelect(&w, p);
001384  }
001385  #endif
001386  
001387  
001388  /*
001389  ** The following group of routines make deep copies of expressions,
001390  ** expression lists, ID lists, and select statements.  The copies can
001391  ** be deleted (by being passed to their respective ...Delete() routines)
001392  ** without effecting the originals.
001393  **
001394  ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
001395  ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
001396  ** by subsequent calls to sqlite*ListAppend() routines.
001397  **
001398  ** Any tables that the SrcList might point to are not duplicated.
001399  **
001400  ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
001401  ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
001402  ** truncated version of the usual Expr structure that will be stored as
001403  ** part of the in-memory representation of the database schema.
001404  */
001405  Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
001406    assert( flags==0 || flags==EXPRDUP_REDUCE );
001407    return p ? exprDup(db, p, flags, 0) : 0;
001408  }
001409  ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
001410    ExprList *pNew;
001411    struct ExprList_item *pItem, *pOldItem;
001412    int i;
001413    Expr *pPriorSelectCol = 0;
001414    assert( db!=0 );
001415    if( p==0 ) return 0;
001416    pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
001417    if( pNew==0 ) return 0;
001418    pNew->nExpr = p->nExpr;
001419    pItem = pNew->a;
001420    pOldItem = p->a;
001421    for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
001422      Expr *pOldExpr = pOldItem->pExpr;
001423      Expr *pNewExpr;
001424      pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
001425      if( pOldExpr 
001426       && pOldExpr->op==TK_SELECT_COLUMN
001427       && (pNewExpr = pItem->pExpr)!=0 
001428      ){
001429        assert( pNewExpr->iColumn==0 || i>0 );
001430        if( pNewExpr->iColumn==0 ){
001431          assert( pOldExpr->pLeft==pOldExpr->pRight );
001432          pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
001433        }else{
001434          assert( i>0 );
001435          assert( pItem[-1].pExpr!=0 );
001436          assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
001437          assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
001438          pNewExpr->pLeft = pPriorSelectCol;
001439        }
001440      }
001441      pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
001442      pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
001443      pItem->sortFlags = pOldItem->sortFlags;
001444      pItem->done = 0;
001445      pItem->bNulls = pOldItem->bNulls;
001446      pItem->bSpanIsTab = pOldItem->bSpanIsTab;
001447      pItem->bSorterRef = pOldItem->bSorterRef;
001448      pItem->u = pOldItem->u;
001449    }
001450    return pNew;
001451  }
001452  
001453  /*
001454  ** If cursors, triggers, views and subqueries are all omitted from
001455  ** the build, then none of the following routines, except for 
001456  ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
001457  ** called with a NULL argument.
001458  */
001459  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
001460   || !defined(SQLITE_OMIT_SUBQUERY)
001461  SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
001462    SrcList *pNew;
001463    int i;
001464    int nByte;
001465    assert( db!=0 );
001466    if( p==0 ) return 0;
001467    nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
001468    pNew = sqlite3DbMallocRawNN(db, nByte );
001469    if( pNew==0 ) return 0;
001470    pNew->nSrc = pNew->nAlloc = p->nSrc;
001471    for(i=0; i<p->nSrc; i++){
001472      struct SrcList_item *pNewItem = &pNew->a[i];
001473      struct SrcList_item *pOldItem = &p->a[i];
001474      Table *pTab;
001475      pNewItem->pSchema = pOldItem->pSchema;
001476      pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
001477      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
001478      pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
001479      pNewItem->fg = pOldItem->fg;
001480      pNewItem->iCursor = pOldItem->iCursor;
001481      pNewItem->addrFillSub = pOldItem->addrFillSub;
001482      pNewItem->regReturn = pOldItem->regReturn;
001483      if( pNewItem->fg.isIndexedBy ){
001484        pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
001485      }
001486      pNewItem->pIBIndex = pOldItem->pIBIndex;
001487      if( pNewItem->fg.isTabFunc ){
001488        pNewItem->u1.pFuncArg = 
001489            sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
001490      }
001491      pTab = pNewItem->pTab = pOldItem->pTab;
001492      if( pTab ){
001493        pTab->nTabRef++;
001494      }
001495      pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
001496      pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
001497      pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
001498      pNewItem->colUsed = pOldItem->colUsed;
001499    }
001500    return pNew;
001501  }
001502  IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
001503    IdList *pNew;
001504    int i;
001505    assert( db!=0 );
001506    if( p==0 ) return 0;
001507    pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
001508    if( pNew==0 ) return 0;
001509    pNew->nId = p->nId;
001510    pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
001511    if( pNew->a==0 ){
001512      sqlite3DbFreeNN(db, pNew);
001513      return 0;
001514    }
001515    /* Note that because the size of the allocation for p->a[] is not
001516    ** necessarily a power of two, sqlite3IdListAppend() may not be called
001517    ** on the duplicate created by this function. */
001518    for(i=0; i<p->nId; i++){
001519      struct IdList_item *pNewItem = &pNew->a[i];
001520      struct IdList_item *pOldItem = &p->a[i];
001521      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
001522      pNewItem->idx = pOldItem->idx;
001523    }
001524    return pNew;
001525  }
001526  Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
001527    Select *pRet = 0;
001528    Select *pNext = 0;
001529    Select **pp = &pRet;
001530    Select *p;
001531  
001532    assert( db!=0 );
001533    for(p=pDup; p; p=p->pPrior){
001534      Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
001535      if( pNew==0 ) break;
001536      pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
001537      pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
001538      pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
001539      pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
001540      pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
001541      pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
001542      pNew->op = p->op;
001543      pNew->pNext = pNext;
001544      pNew->pPrior = 0;
001545      pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
001546      pNew->iLimit = 0;
001547      pNew->iOffset = 0;
001548      pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
001549      pNew->addrOpenEphm[0] = -1;
001550      pNew->addrOpenEphm[1] = -1;
001551      pNew->nSelectRow = p->nSelectRow;
001552      pNew->pWith = withDup(db, p->pWith);
001553  #ifndef SQLITE_OMIT_WINDOWFUNC
001554      pNew->pWin = 0;
001555      pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
001556      if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
001557  #endif
001558      pNew->selId = p->selId;
001559      *pp = pNew;
001560      pp = &pNew->pPrior;
001561      pNext = pNew;
001562    }
001563  
001564    return pRet;
001565  }
001566  #else
001567  Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
001568    assert( p==0 );
001569    return 0;
001570  }
001571  #endif
001572  
001573  
001574  /*
001575  ** Add a new element to the end of an expression list.  If pList is
001576  ** initially NULL, then create a new expression list.
001577  **
001578  ** The pList argument must be either NULL or a pointer to an ExprList
001579  ** obtained from a prior call to sqlite3ExprListAppend().  This routine
001580  ** may not be used with an ExprList obtained from sqlite3ExprListDup().
001581  ** Reason:  This routine assumes that the number of slots in pList->a[]
001582  ** is a power of two.  That is true for sqlite3ExprListAppend() returns
001583  ** but is not necessarily true from the return value of sqlite3ExprListDup().
001584  **
001585  ** If a memory allocation error occurs, the entire list is freed and
001586  ** NULL is returned.  If non-NULL is returned, then it is guaranteed
001587  ** that the new entry was successfully appended.
001588  */
001589  ExprList *sqlite3ExprListAppend(
001590    Parse *pParse,          /* Parsing context */
001591    ExprList *pList,        /* List to which to append. Might be NULL */
001592    Expr *pExpr             /* Expression to be appended. Might be NULL */
001593  ){
001594    struct ExprList_item *pItem;
001595    sqlite3 *db = pParse->db;
001596    assert( db!=0 );
001597    if( pList==0 ){
001598      pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
001599      if( pList==0 ){
001600        goto no_mem;
001601      }
001602      pList->nExpr = 0;
001603    }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
001604      ExprList *pNew;
001605      pNew = sqlite3DbRealloc(db, pList, 
001606           sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
001607      if( pNew==0 ){
001608        goto no_mem;
001609      }
001610      pList = pNew;
001611    }
001612    pItem = &pList->a[pList->nExpr++];
001613    assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
001614    assert( offsetof(struct ExprList_item,pExpr)==0 );
001615    memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
001616    pItem->pExpr = pExpr;
001617    return pList;
001618  
001619  no_mem:     
001620    /* Avoid leaking memory if malloc has failed. */
001621    sqlite3ExprDelete(db, pExpr);
001622    sqlite3ExprListDelete(db, pList);
001623    return 0;
001624  }
001625  
001626  /*
001627  ** pColumns and pExpr form a vector assignment which is part of the SET
001628  ** clause of an UPDATE statement.  Like this:
001629  **
001630  **        (a,b,c) = (expr1,expr2,expr3)
001631  ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
001632  **
001633  ** For each term of the vector assignment, append new entries to the
001634  ** expression list pList.  In the case of a subquery on the RHS, append
001635  ** TK_SELECT_COLUMN expressions.
001636  */
001637  ExprList *sqlite3ExprListAppendVector(
001638    Parse *pParse,         /* Parsing context */
001639    ExprList *pList,       /* List to which to append. Might be NULL */
001640    IdList *pColumns,      /* List of names of LHS of the assignment */
001641    Expr *pExpr            /* Vector expression to be appended. Might be NULL */
001642  ){
001643    sqlite3 *db = pParse->db;
001644    int n;
001645    int i;
001646    int iFirst = pList ? pList->nExpr : 0;
001647    /* pColumns can only be NULL due to an OOM but an OOM will cause an
001648    ** exit prior to this routine being invoked */
001649    if( NEVER(pColumns==0) ) goto vector_append_error;
001650    if( pExpr==0 ) goto vector_append_error;
001651  
001652    /* If the RHS is a vector, then we can immediately check to see that 
001653    ** the size of the RHS and LHS match.  But if the RHS is a SELECT, 
001654    ** wildcards ("*") in the result set of the SELECT must be expanded before
001655    ** we can do the size check, so defer the size check until code generation.
001656    */
001657    if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
001658      sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
001659                      pColumns->nId, n);
001660      goto vector_append_error;
001661    }
001662  
001663    for(i=0; i<pColumns->nId; i++){
001664      Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
001665      assert( pSubExpr!=0 || db->mallocFailed );
001666      assert( pSubExpr==0 || pSubExpr->iTable==0 );
001667      if( pSubExpr==0 ) continue;
001668      pSubExpr->iTable = pColumns->nId;
001669      pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
001670      if( pList ){
001671        assert( pList->nExpr==iFirst+i+1 );
001672        pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
001673        pColumns->a[i].zName = 0;
001674      }
001675    }
001676  
001677    if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
001678      Expr *pFirst = pList->a[iFirst].pExpr;
001679      assert( pFirst!=0 );
001680      assert( pFirst->op==TK_SELECT_COLUMN );
001681       
001682      /* Store the SELECT statement in pRight so it will be deleted when
001683      ** sqlite3ExprListDelete() is called */
001684      pFirst->pRight = pExpr;
001685      pExpr = 0;
001686  
001687      /* Remember the size of the LHS in iTable so that we can check that
001688      ** the RHS and LHS sizes match during code generation. */
001689      pFirst->iTable = pColumns->nId;
001690    }
001691  
001692  vector_append_error:
001693    sqlite3ExprUnmapAndDelete(pParse, pExpr);
001694    sqlite3IdListDelete(db, pColumns);
001695    return pList;
001696  }
001697  
001698  /*
001699  ** Set the sort order for the last element on the given ExprList.
001700  */
001701  void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
001702    struct ExprList_item *pItem;
001703    if( p==0 ) return;
001704    assert( p->nExpr>0 );
001705  
001706    assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
001707    assert( iSortOrder==SQLITE_SO_UNDEFINED 
001708         || iSortOrder==SQLITE_SO_ASC 
001709         || iSortOrder==SQLITE_SO_DESC 
001710    );
001711    assert( eNulls==SQLITE_SO_UNDEFINED 
001712         || eNulls==SQLITE_SO_ASC 
001713         || eNulls==SQLITE_SO_DESC 
001714    );
001715  
001716    pItem = &p->a[p->nExpr-1];
001717    assert( pItem->bNulls==0 );
001718    if( iSortOrder==SQLITE_SO_UNDEFINED ){
001719      iSortOrder = SQLITE_SO_ASC;
001720    }
001721    pItem->sortFlags = (u8)iSortOrder;
001722  
001723    if( eNulls!=SQLITE_SO_UNDEFINED ){
001724      pItem->bNulls = 1;
001725      if( iSortOrder!=eNulls ){
001726        pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
001727      }
001728    }
001729  }
001730  
001731  /*
001732  ** Set the ExprList.a[].zName element of the most recently added item
001733  ** on the expression list.
001734  **
001735  ** pList might be NULL following an OOM error.  But pName should never be
001736  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
001737  ** is set.
001738  */
001739  void sqlite3ExprListSetName(
001740    Parse *pParse,          /* Parsing context */
001741    ExprList *pList,        /* List to which to add the span. */
001742    Token *pName,           /* Name to be added */
001743    int dequote             /* True to cause the name to be dequoted */
001744  ){
001745    assert( pList!=0 || pParse->db->mallocFailed!=0 );
001746    if( pList ){
001747      struct ExprList_item *pItem;
001748      assert( pList->nExpr>0 );
001749      pItem = &pList->a[pList->nExpr-1];
001750      assert( pItem->zName==0 );
001751      pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
001752      if( dequote ) sqlite3Dequote(pItem->zName);
001753      if( IN_RENAME_OBJECT ){
001754        sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
001755      }
001756    }
001757  }
001758  
001759  /*
001760  ** Set the ExprList.a[].zSpan element of the most recently added item
001761  ** on the expression list.
001762  **
001763  ** pList might be NULL following an OOM error.  But pSpan should never be
001764  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
001765  ** is set.
001766  */
001767  void sqlite3ExprListSetSpan(
001768    Parse *pParse,          /* Parsing context */
001769    ExprList *pList,        /* List to which to add the span. */
001770    const char *zStart,     /* Start of the span */
001771    const char *zEnd        /* End of the span */
001772  ){
001773    sqlite3 *db = pParse->db;
001774    assert( pList!=0 || db->mallocFailed!=0 );
001775    if( pList ){
001776      struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
001777      assert( pList->nExpr>0 );
001778      sqlite3DbFree(db, pItem->zSpan);
001779      pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
001780    }
001781  }
001782  
001783  /*
001784  ** If the expression list pEList contains more than iLimit elements,
001785  ** leave an error message in pParse.
001786  */
001787  void sqlite3ExprListCheckLength(
001788    Parse *pParse,
001789    ExprList *pEList,
001790    const char *zObject
001791  ){
001792    int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
001793    testcase( pEList && pEList->nExpr==mx );
001794    testcase( pEList && pEList->nExpr==mx+1 );
001795    if( pEList && pEList->nExpr>mx ){
001796      sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
001797    }
001798  }
001799  
001800  /*
001801  ** Delete an entire expression list.
001802  */
001803  static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
001804    int i = pList->nExpr;
001805    struct ExprList_item *pItem =  pList->a;
001806    assert( pList->nExpr>0 );
001807    do{
001808      sqlite3ExprDelete(db, pItem->pExpr);
001809      sqlite3DbFree(db, pItem->zName);
001810      sqlite3DbFree(db, pItem->zSpan);
001811      pItem++;
001812    }while( --i>0 );
001813    sqlite3DbFreeNN(db, pList);
001814  }
001815  void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
001816    if( pList ) exprListDeleteNN(db, pList);
001817  }
001818  
001819  /*
001820  ** Return the bitwise-OR of all Expr.flags fields in the given
001821  ** ExprList.
001822  */
001823  u32 sqlite3ExprListFlags(const ExprList *pList){
001824    int i;
001825    u32 m = 0;
001826    assert( pList!=0 );
001827    for(i=0; i<pList->nExpr; i++){
001828       Expr *pExpr = pList->a[i].pExpr;
001829       assert( pExpr!=0 );
001830       m |= pExpr->flags;
001831    }
001832    return m;
001833  }
001834  
001835  /*
001836  ** This is a SELECT-node callback for the expression walker that
001837  ** always "fails".  By "fail" in this case, we mean set
001838  ** pWalker->eCode to zero and abort.
001839  **
001840  ** This callback is used by multiple expression walkers.
001841  */
001842  int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
001843    UNUSED_PARAMETER(NotUsed);
001844    pWalker->eCode = 0;
001845    return WRC_Abort;
001846  }
001847  
001848  /*
001849  ** If the input expression is an ID with the name "true" or "false"
001850  ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
001851  ** the conversion happened, and zero if the expression is unaltered.
001852  */
001853  int sqlite3ExprIdToTrueFalse(Expr *pExpr){
001854    assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
001855    if( !ExprHasProperty(pExpr, EP_Quoted)
001856     && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
001857         || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
001858    ){
001859      pExpr->op = TK_TRUEFALSE;
001860      ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
001861      return 1;
001862    }
001863    return 0;
001864  }
001865  
001866  /*
001867  ** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
001868  ** and 0 if it is FALSE.
001869  */
001870  int sqlite3ExprTruthValue(const Expr *pExpr){
001871    pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
001872    assert( pExpr->op==TK_TRUEFALSE );
001873    assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
001874         || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
001875    return pExpr->u.zToken[4]==0;
001876  }
001877  
001878  /*
001879  ** If pExpr is an AND or OR expression, try to simplify it by eliminating
001880  ** terms that are always true or false.  Return the simplified expression.
001881  ** Or return the original expression if no simplification is possible.
001882  **
001883  ** Examples:
001884  **
001885  **     (x<10) AND true                =>   (x<10)
001886  **     (x<10) AND false               =>   false
001887  **     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)
001888  **     (x<10) AND (y=22 OR true)      =>   (x<10)
001889  **     (y=22) OR true                 =>   true
001890  */
001891  Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
001892    assert( pExpr!=0 );
001893    if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
001894      Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
001895      Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
001896      if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
001897        pExpr = pExpr->op==TK_AND ? pRight : pLeft;
001898      }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
001899        pExpr = pExpr->op==TK_AND ? pLeft : pRight;
001900      }
001901    }
001902    return pExpr;
001903  }
001904  
001905  
001906  /*
001907  ** These routines are Walker callbacks used to check expressions to
001908  ** see if they are "constant" for some definition of constant.  The
001909  ** Walker.eCode value determines the type of "constant" we are looking
001910  ** for.
001911  **
001912  ** These callback routines are used to implement the following:
001913  **
001914  **     sqlite3ExprIsConstant()                  pWalker->eCode==1
001915  **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
001916  **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
001917  **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
001918  **
001919  ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
001920  ** is found to not be a constant.
001921  **
001922  ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
001923  ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
001924  ** an existing schema and 4 when processing a new statement.  A bound
001925  ** parameter raises an error for new statements, but is silently converted
001926  ** to NULL for existing schemas.  This allows sqlite_master tables that 
001927  ** contain a bound parameter because they were generated by older versions
001928  ** of SQLite to be parsed by newer versions of SQLite without raising a
001929  ** malformed schema error.
001930  */
001931  static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
001932  
001933    /* If pWalker->eCode is 2 then any term of the expression that comes from
001934    ** the ON or USING clauses of a left join disqualifies the expression
001935    ** from being considered constant. */
001936    if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
001937      pWalker->eCode = 0;
001938      return WRC_Abort;
001939    }
001940  
001941    switch( pExpr->op ){
001942      /* Consider functions to be constant if all their arguments are constant
001943      ** and either pWalker->eCode==4 or 5 or the function has the
001944      ** SQLITE_FUNC_CONST flag. */
001945      case TK_FUNCTION:
001946        if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
001947         && !ExprHasProperty(pExpr, EP_WinFunc)
001948        ){
001949          return WRC_Continue;
001950        }else{
001951          pWalker->eCode = 0;
001952          return WRC_Abort;
001953        }
001954      case TK_ID:
001955        /* Convert "true" or "false" in a DEFAULT clause into the
001956        ** appropriate TK_TRUEFALSE operator */
001957        if( sqlite3ExprIdToTrueFalse(pExpr) ){
001958          return WRC_Prune;
001959        }
001960        /* Fall thru */
001961      case TK_COLUMN:
001962      case TK_AGG_FUNCTION:
001963      case TK_AGG_COLUMN:
001964        testcase( pExpr->op==TK_ID );
001965        testcase( pExpr->op==TK_COLUMN );
001966        testcase( pExpr->op==TK_AGG_FUNCTION );
001967        testcase( pExpr->op==TK_AGG_COLUMN );
001968        if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
001969          return WRC_Continue;
001970        }
001971        if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
001972          return WRC_Continue;
001973        }
001974        /* Fall through */
001975      case TK_IF_NULL_ROW:
001976      case TK_REGISTER:
001977        testcase( pExpr->op==TK_REGISTER );
001978        testcase( pExpr->op==TK_IF_NULL_ROW );
001979        pWalker->eCode = 0;
001980        return WRC_Abort;
001981      case TK_VARIABLE:
001982        if( pWalker->eCode==5 ){
001983          /* Silently convert bound parameters that appear inside of CREATE
001984          ** statements into a NULL when parsing the CREATE statement text out
001985          ** of the sqlite_master table */
001986          pExpr->op = TK_NULL;
001987        }else if( pWalker->eCode==4 ){
001988          /* A bound parameter in a CREATE statement that originates from
001989          ** sqlite3_prepare() causes an error */
001990          pWalker->eCode = 0;
001991          return WRC_Abort;
001992        }
001993        /* Fall through */
001994      default:
001995        testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
001996        testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
001997        return WRC_Continue;
001998    }
001999  }
002000  static int exprIsConst(Expr *p, int initFlag, int iCur){
002001    Walker w;
002002    w.eCode = initFlag;
002003    w.xExprCallback = exprNodeIsConstant;
002004    w.xSelectCallback = sqlite3SelectWalkFail;
002005  #ifdef SQLITE_DEBUG
002006    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
002007  #endif
002008    w.u.iCur = iCur;
002009    sqlite3WalkExpr(&w, p);
002010    return w.eCode;
002011  }
002012  
002013  /*
002014  ** Walk an expression tree.  Return non-zero if the expression is constant
002015  ** and 0 if it involves variables or function calls.
002016  **
002017  ** For the purposes of this function, a double-quoted string (ex: "abc")
002018  ** is considered a variable but a single-quoted string (ex: 'abc') is
002019  ** a constant.
002020  */
002021  int sqlite3ExprIsConstant(Expr *p){
002022    return exprIsConst(p, 1, 0);
002023  }
002024  
002025  /*
002026  ** Walk an expression tree.  Return non-zero if
002027  **
002028  **   (1) the expression is constant, and
002029  **   (2) the expression does originate in the ON or USING clause
002030  **       of a LEFT JOIN, and
002031  **   (3) the expression does not contain any EP_FixedCol TK_COLUMN
002032  **       operands created by the constant propagation optimization.
002033  **
002034  ** When this routine returns true, it indicates that the expression
002035  ** can be added to the pParse->pConstExpr list and evaluated once when
002036  ** the prepared statement starts up.  See sqlite3ExprCodeAtInit().
002037  */
002038  int sqlite3ExprIsConstantNotJoin(Expr *p){
002039    return exprIsConst(p, 2, 0);
002040  }
002041  
002042  /*
002043  ** Walk an expression tree.  Return non-zero if the expression is constant
002044  ** for any single row of the table with cursor iCur.  In other words, the
002045  ** expression must not refer to any non-deterministic function nor any
002046  ** table other than iCur.
002047  */
002048  int sqlite3ExprIsTableConstant(Expr *p, int iCur){
002049    return exprIsConst(p, 3, iCur);
002050  }
002051  
002052  
002053  /*
002054  ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
002055  */
002056  static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
002057    ExprList *pGroupBy = pWalker->u.pGroupBy;
002058    int i;
002059  
002060    /* Check if pExpr is identical to any GROUP BY term. If so, consider
002061    ** it constant.  */
002062    for(i=0; i<pGroupBy->nExpr; i++){
002063      Expr *p = pGroupBy->a[i].pExpr;
002064      if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
002065        CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
002066        if( sqlite3IsBinary(pColl) ){
002067          return WRC_Prune;
002068        }
002069      }
002070    }
002071  
002072    /* Check if pExpr is a sub-select. If so, consider it variable. */
002073    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
002074      pWalker->eCode = 0;
002075      return WRC_Abort;
002076    }
002077  
002078    return exprNodeIsConstant(pWalker, pExpr);
002079  }
002080  
002081  /*
002082  ** Walk the expression tree passed as the first argument. Return non-zero
002083  ** if the expression consists entirely of constants or copies of terms 
002084  ** in pGroupBy that sort with the BINARY collation sequence.
002085  **
002086  ** This routine is used to determine if a term of the HAVING clause can
002087  ** be promoted into the WHERE clause.  In order for such a promotion to work,
002088  ** the value of the HAVING clause term must be the same for all members of
002089  ** a "group".  The requirement that the GROUP BY term must be BINARY
002090  ** assumes that no other collating sequence will have a finer-grained
002091  ** grouping than binary.  In other words (A=B COLLATE binary) implies
002092  ** A=B in every other collating sequence.  The requirement that the
002093  ** GROUP BY be BINARY is stricter than necessary.  It would also work
002094  ** to promote HAVING clauses that use the same alternative collating
002095  ** sequence as the GROUP BY term, but that is much harder to check,
002096  ** alternative collating sequences are uncommon, and this is only an
002097  ** optimization, so we take the easy way out and simply require the
002098  ** GROUP BY to use the BINARY collating sequence.
002099  */
002100  int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
002101    Walker w;
002102    w.eCode = 1;
002103    w.xExprCallback = exprNodeIsConstantOrGroupBy;
002104    w.xSelectCallback = 0;
002105    w.u.pGroupBy = pGroupBy;
002106    w.pParse = pParse;
002107    sqlite3WalkExpr(&w, p);
002108    return w.eCode;
002109  }
002110  
002111  /*
002112  ** Walk an expression tree.  Return non-zero if the expression is constant
002113  ** or a function call with constant arguments.  Return and 0 if there
002114  ** are any variables.
002115  **
002116  ** For the purposes of this function, a double-quoted string (ex: "abc")
002117  ** is considered a variable but a single-quoted string (ex: 'abc') is
002118  ** a constant.
002119  */
002120  int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
002121    assert( isInit==0 || isInit==1 );
002122    return exprIsConst(p, 4+isInit, 0);
002123  }
002124  
002125  #ifdef SQLITE_ENABLE_CURSOR_HINTS
002126  /*
002127  ** Walk an expression tree.  Return 1 if the expression contains a
002128  ** subquery of some kind.  Return 0 if there are no subqueries.
002129  */
002130  int sqlite3ExprContainsSubquery(Expr *p){
002131    Walker w;
002132    w.eCode = 1;
002133    w.xExprCallback = sqlite3ExprWalkNoop;
002134    w.xSelectCallback = sqlite3SelectWalkFail;
002135  #ifdef SQLITE_DEBUG
002136    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
002137  #endif
002138    sqlite3WalkExpr(&w, p);
002139    return w.eCode==0;
002140  }
002141  #endif
002142  
002143  /*
002144  ** If the expression p codes a constant integer that is small enough
002145  ** to fit in a 32-bit integer, return 1 and put the value of the integer
002146  ** in *pValue.  If the expression is not an integer or if it is too big
002147  ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
002148  */
002149  int sqlite3ExprIsInteger(Expr *p, int *pValue){
002150    int rc = 0;
002151    if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
002152  
002153    /* If an expression is an integer literal that fits in a signed 32-bit
002154    ** integer, then the EP_IntValue flag will have already been set */
002155    assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
002156             || sqlite3GetInt32(p->u.zToken, &rc)==0 );
002157  
002158    if( p->flags & EP_IntValue ){
002159      *pValue = p->u.iValue;
002160      return 1;
002161    }
002162    switch( p->op ){
002163      case TK_UPLUS: {
002164        rc = sqlite3ExprIsInteger(p->pLeft, pValue);
002165        break;
002166      }
002167      case TK_UMINUS: {
002168        int v;
002169        if( sqlite3ExprIsInteger(p->pLeft, &v) ){
002170          assert( v!=(-2147483647-1) );
002171          *pValue = -v;
002172          rc = 1;
002173        }
002174        break;
002175      }
002176      default: break;
002177    }
002178    return rc;
002179  }
002180  
002181  /*
002182  ** Return FALSE if there is no chance that the expression can be NULL.
002183  **
002184  ** If the expression might be NULL or if the expression is too complex
002185  ** to tell return TRUE.  
002186  **
002187  ** This routine is used as an optimization, to skip OP_IsNull opcodes
002188  ** when we know that a value cannot be NULL.  Hence, a false positive
002189  ** (returning TRUE when in fact the expression can never be NULL) might
002190  ** be a small performance hit but is otherwise harmless.  On the other
002191  ** hand, a false negative (returning FALSE when the result could be NULL)
002192  ** will likely result in an incorrect answer.  So when in doubt, return
002193  ** TRUE.
002194  */
002195  int sqlite3ExprCanBeNull(const Expr *p){
002196    u8 op;
002197    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
002198      p = p->pLeft;
002199    }
002200    op = p->op;
002201    if( op==TK_REGISTER ) op = p->op2;
002202    switch( op ){
002203      case TK_INTEGER:
002204      case TK_STRING:
002205      case TK_FLOAT:
002206      case TK_BLOB:
002207        return 0;
002208      case TK_COLUMN:
002209        return ExprHasProperty(p, EP_CanBeNull) ||
002210               p->y.pTab==0 ||  /* Reference to column of index on expression */
002211               (p->iColumn>=0
002212                && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
002213                && p->y.pTab->aCol[p->iColumn].notNull==0);
002214      default:
002215        return 1;
002216    }
002217  }
002218  
002219  /*
002220  ** Return TRUE if the given expression is a constant which would be
002221  ** unchanged by OP_Affinity with the affinity given in the second
002222  ** argument.
002223  **
002224  ** This routine is used to determine if the OP_Affinity operation
002225  ** can be omitted.  When in doubt return FALSE.  A false negative
002226  ** is harmless.  A false positive, however, can result in the wrong
002227  ** answer.
002228  */
002229  int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
002230    u8 op;
002231    int unaryMinus = 0;
002232    if( aff==SQLITE_AFF_BLOB ) return 1;
002233    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
002234      if( p->op==TK_UMINUS ) unaryMinus = 1;
002235      p = p->pLeft;
002236    }
002237    op = p->op;
002238    if( op==TK_REGISTER ) op = p->op2;
002239    switch( op ){
002240      case TK_INTEGER: {
002241        return aff>=SQLITE_AFF_NUMERIC;
002242      }
002243      case TK_FLOAT: {
002244        return aff>=SQLITE_AFF_NUMERIC;
002245      }
002246      case TK_STRING: {
002247        return !unaryMinus && aff==SQLITE_AFF_TEXT;
002248      }
002249      case TK_BLOB: {
002250        return !unaryMinus;
002251      }
002252      case TK_COLUMN: {
002253        assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
002254        return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
002255      }
002256      default: {
002257        return 0;
002258      }
002259    }
002260  }
002261  
002262  /*
002263  ** Return TRUE if the given string is a row-id column name.
002264  */
002265  int sqlite3IsRowid(const char *z){
002266    if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
002267    if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
002268    if( sqlite3StrICmp(z, "OID")==0 ) return 1;
002269    return 0;
002270  }
002271  
002272  /*
002273  ** pX is the RHS of an IN operator.  If pX is a SELECT statement 
002274  ** that can be simplified to a direct table access, then return
002275  ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
002276  ** or if the SELECT statement needs to be manifested into a transient
002277  ** table, then return NULL.
002278  */
002279  #ifndef SQLITE_OMIT_SUBQUERY
002280  static Select *isCandidateForInOpt(Expr *pX){
002281    Select *p;
002282    SrcList *pSrc;
002283    ExprList *pEList;
002284    Table *pTab;
002285    int i;
002286    if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
002287    if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
002288    p = pX->x.pSelect;
002289    if( p->pPrior ) return 0;              /* Not a compound SELECT */
002290    if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
002291      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
002292      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
002293      return 0; /* No DISTINCT keyword and no aggregate functions */
002294    }
002295    if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
002296    if( p->pLimit ) return 0;              /* Has no LIMIT clause */
002297    if( p->pWhere ) return 0;              /* Has no WHERE clause */
002298    pSrc = p->pSrc;
002299    assert( pSrc!=0 );
002300    if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
002301    if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
002302    pTab = pSrc->a[0].pTab;
002303    assert( pTab!=0 );
002304    assert( pTab->pSelect==0 );            /* FROM clause is not a view */
002305    if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
002306    pEList = p->pEList;
002307    assert( pEList!=0 );
002308    /* All SELECT results must be columns. */
002309    for(i=0; i<pEList->nExpr; i++){
002310      Expr *pRes = pEList->a[i].pExpr;
002311      if( pRes->op!=TK_COLUMN ) return 0;
002312      assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
002313    }
002314    return p;
002315  }
002316  #endif /* SQLITE_OMIT_SUBQUERY */
002317  
002318  #ifndef SQLITE_OMIT_SUBQUERY
002319  /*
002320  ** Generate code that checks the left-most column of index table iCur to see if
002321  ** it contains any NULL entries.  Cause the register at regHasNull to be set
002322  ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
002323  ** to be set to NULL if iCur contains one or more NULL values.
002324  */
002325  static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
002326    int addr1;
002327    sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
002328    addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
002329    sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
002330    sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
002331    VdbeComment((v, "first_entry_in(%d)", iCur));
002332    sqlite3VdbeJumpHere(v, addr1);
002333  }
002334  #endif
002335  
002336  
002337  #ifndef SQLITE_OMIT_SUBQUERY
002338  /*
002339  ** The argument is an IN operator with a list (not a subquery) on the 
002340  ** right-hand side.  Return TRUE if that list is constant.
002341  */
002342  static int sqlite3InRhsIsConstant(Expr *pIn){
002343    Expr *pLHS;
002344    int res;
002345    assert( !ExprHasProperty(pIn, EP_xIsSelect) );
002346    pLHS = pIn->pLeft;
002347    pIn->pLeft = 0;
002348    res = sqlite3ExprIsConstant(pIn);
002349    pIn->pLeft = pLHS;
002350    return res;
002351  }
002352  #endif
002353  
002354  /*
002355  ** This function is used by the implementation of the IN (...) operator.
002356  ** The pX parameter is the expression on the RHS of the IN operator, which
002357  ** might be either a list of expressions or a subquery.
002358  **
002359  ** The job of this routine is to find or create a b-tree object that can
002360  ** be used either to test for membership in the RHS set or to iterate through
002361  ** all members of the RHS set, skipping duplicates.
002362  **
002363  ** A cursor is opened on the b-tree object that is the RHS of the IN operator
002364  ** and pX->iTable is set to the index of that cursor.
002365  **
002366  ** The returned value of this function indicates the b-tree type, as follows:
002367  **
002368  **   IN_INDEX_ROWID      - The cursor was opened on a database table.
002369  **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
002370  **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
002371  **   IN_INDEX_EPH        - The cursor was opened on a specially created and
002372  **                         populated epheremal table.
002373  **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
002374  **                         implemented as a sequence of comparisons.
002375  **
002376  ** An existing b-tree might be used if the RHS expression pX is a simple
002377  ** subquery such as:
002378  **
002379  **     SELECT <column1>, <column2>... FROM <table>
002380  **
002381  ** If the RHS of the IN operator is a list or a more complex subquery, then
002382  ** an ephemeral table might need to be generated from the RHS and then
002383  ** pX->iTable made to point to the ephemeral table instead of an
002384  ** existing table.
002385  **
002386  ** The inFlags parameter must contain, at a minimum, one of the bits
002387  ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
002388  ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
002389  ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
002390  ** be used to loop over all values of the RHS of the IN operator.
002391  **
002392  ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
002393  ** through the set members) then the b-tree must not contain duplicates.
002394  ** An epheremal table will be created unless the selected columns are guaranteed
002395  ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
002396  ** a UNIQUE constraint or index.
002397  **
002398  ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
002399  ** for fast set membership tests) then an epheremal table must 
002400  ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 
002401  ** index can be found with the specified <columns> as its left-most.
002402  **
002403  ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
002404  ** if the RHS of the IN operator is a list (not a subquery) then this
002405  ** routine might decide that creating an ephemeral b-tree for membership
002406  ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
002407  ** calling routine should implement the IN operator using a sequence
002408  ** of Eq or Ne comparison operations.
002409  **
002410  ** When the b-tree is being used for membership tests, the calling function
002411  ** might need to know whether or not the RHS side of the IN operator
002412  ** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
002413  ** if there is any chance that the (...) might contain a NULL value at
002414  ** runtime, then a register is allocated and the register number written
002415  ** to *prRhsHasNull. If there is no chance that the (...) contains a
002416  ** NULL value, then *prRhsHasNull is left unchanged.
002417  **
002418  ** If a register is allocated and its location stored in *prRhsHasNull, then
002419  ** the value in that register will be NULL if the b-tree contains one or more
002420  ** NULL values, and it will be some non-NULL value if the b-tree contains no
002421  ** NULL values.
002422  **
002423  ** If the aiMap parameter is not NULL, it must point to an array containing
002424  ** one element for each column returned by the SELECT statement on the RHS
002425  ** of the IN(...) operator. The i'th entry of the array is populated with the
002426  ** offset of the index column that matches the i'th column returned by the
002427  ** SELECT. For example, if the expression and selected index are:
002428  **
002429  **   (?,?,?) IN (SELECT a, b, c FROM t1)
002430  **   CREATE INDEX i1 ON t1(b, c, a);
002431  **
002432  ** then aiMap[] is populated with {2, 0, 1}.
002433  */
002434  #ifndef SQLITE_OMIT_SUBQUERY
002435  int sqlite3FindInIndex(
002436    Parse *pParse,             /* Parsing context */
002437    Expr *pX,                  /* The IN expression */
002438    u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
002439    int *prRhsHasNull,         /* Register holding NULL status.  See notes */
002440    int *aiMap,                /* Mapping from Index fields to RHS fields */
002441    int *piTab                 /* OUT: index to use */
002442  ){
002443    Select *p;                            /* SELECT to the right of IN operator */
002444    int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
002445    int iTab = pParse->nTab++;            /* Cursor of the RHS table */
002446    int mustBeUnique;                     /* True if RHS must be unique */
002447    Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
002448  
002449    assert( pX->op==TK_IN );
002450    mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
002451  
002452    /* If the RHS of this IN(...) operator is a SELECT, and if it matters 
002453    ** whether or not the SELECT result contains NULL values, check whether
002454    ** or not NULL is actually possible (it may not be, for example, due 
002455    ** to NOT NULL constraints in the schema). If no NULL values are possible,
002456    ** set prRhsHasNull to 0 before continuing.  */
002457    if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
002458      int i;
002459      ExprList *pEList = pX->x.pSelect->pEList;
002460      for(i=0; i<pEList->nExpr; i++){
002461        if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
002462      }
002463      if( i==pEList->nExpr ){
002464        prRhsHasNull = 0;
002465      }
002466    }
002467  
002468    /* Check to see if an existing table or index can be used to
002469    ** satisfy the query.  This is preferable to generating a new 
002470    ** ephemeral table.  */
002471    if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
002472      sqlite3 *db = pParse->db;              /* Database connection */
002473      Table *pTab;                           /* Table <table>. */
002474      i16 iDb;                               /* Database idx for pTab */
002475      ExprList *pEList = p->pEList;
002476      int nExpr = pEList->nExpr;
002477  
002478      assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
002479      assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
002480      assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
002481      pTab = p->pSrc->a[0].pTab;
002482  
002483      /* Code an OP_Transaction and OP_TableLock for <table>. */
002484      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
002485      sqlite3CodeVerifySchema(pParse, iDb);
002486      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
002487  
002488      assert(v);  /* sqlite3GetVdbe() has always been previously called */
002489      if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
002490        /* The "x IN (SELECT rowid FROM table)" case */
002491        int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
002492        VdbeCoverage(v);
002493  
002494        sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
002495        eType = IN_INDEX_ROWID;
002496        ExplainQueryPlan((pParse, 0,
002497              "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
002498        sqlite3VdbeJumpHere(v, iAddr);
002499      }else{
002500        Index *pIdx;                         /* Iterator variable */
002501        int affinity_ok = 1;
002502        int i;
002503  
002504        /* Check that the affinity that will be used to perform each 
002505        ** comparison is the same as the affinity of each column in table
002506        ** on the RHS of the IN operator.  If it not, it is not possible to
002507        ** use any index of the RHS table.  */
002508        for(i=0; i<nExpr && affinity_ok; i++){
002509          Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
002510          int iCol = pEList->a[i].pExpr->iColumn;
002511          char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
002512          char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
002513          testcase( cmpaff==SQLITE_AFF_BLOB );
002514          testcase( cmpaff==SQLITE_AFF_TEXT );
002515          switch( cmpaff ){
002516            case SQLITE_AFF_BLOB:
002517              break;
002518            case SQLITE_AFF_TEXT:
002519              /* sqlite3CompareAffinity() only returns TEXT if one side or the
002520              ** other has no affinity and the other side is TEXT.  Hence,
002521              ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
002522              ** and for the term on the LHS of the IN to have no affinity. */
002523              assert( idxaff==SQLITE_AFF_TEXT );
002524              break;
002525            default:
002526              affinity_ok = sqlite3IsNumericAffinity(idxaff);
002527          }
002528        }
002529  
002530        if( affinity_ok ){
002531          /* Search for an existing index that will work for this IN operator */
002532          for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
002533            Bitmask colUsed;      /* Columns of the index used */
002534            Bitmask mCol;         /* Mask for the current column */
002535            if( pIdx->nColumn<nExpr ) continue;
002536            if( pIdx->pPartIdxWhere!=0 ) continue;
002537            /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
002538            ** BITMASK(nExpr) without overflowing */
002539            testcase( pIdx->nColumn==BMS-2 );
002540            testcase( pIdx->nColumn==BMS-1 );
002541            if( pIdx->nColumn>=BMS-1 ) continue;
002542            if( mustBeUnique ){
002543              if( pIdx->nKeyCol>nExpr
002544               ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
002545              ){
002546                continue;  /* This index is not unique over the IN RHS columns */
002547              }
002548            }
002549    
002550            colUsed = 0;   /* Columns of index used so far */
002551            for(i=0; i<nExpr; i++){
002552              Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
002553              Expr *pRhs = pEList->a[i].pExpr;
002554              CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
002555              int j;
002556    
002557              assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
002558              for(j=0; j<nExpr; j++){
002559                if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
002560                assert( pIdx->azColl[j] );
002561                if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
002562                  continue;
002563                }
002564                break;
002565              }
002566              if( j==nExpr ) break;
002567              mCol = MASKBIT(j);
002568              if( mCol & colUsed ) break; /* Each column used only once */
002569              colUsed |= mCol;
002570              if( aiMap ) aiMap[i] = j;
002571            }
002572    
002573            assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
002574            if( colUsed==(MASKBIT(nExpr)-1) ){
002575              /* If we reach this point, that means the index pIdx is usable */
002576              int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
002577              ExplainQueryPlan((pParse, 0,
002578                                "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
002579              sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
002580              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
002581              VdbeComment((v, "%s", pIdx->zName));
002582              assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
002583              eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
002584    
002585              if( prRhsHasNull ){
002586  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
002587                i64 mask = (1<<nExpr)-1;
002588                sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 
002589                    iTab, 0, 0, (u8*)&mask, P4_INT64);
002590  #endif
002591                *prRhsHasNull = ++pParse->nMem;
002592                if( nExpr==1 ){
002593                  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
002594                }
002595              }
002596              sqlite3VdbeJumpHere(v, iAddr);
002597            }
002598          } /* End loop over indexes */
002599        } /* End if( affinity_ok ) */
002600      } /* End if not an rowid index */
002601    } /* End attempt to optimize using an index */
002602  
002603    /* If no preexisting index is available for the IN clause
002604    ** and IN_INDEX_NOOP is an allowed reply
002605    ** and the RHS of the IN operator is a list, not a subquery
002606    ** and the RHS is not constant or has two or fewer terms,
002607    ** then it is not worth creating an ephemeral table to evaluate
002608    ** the IN operator so return IN_INDEX_NOOP.
002609    */
002610    if( eType==0
002611     && (inFlags & IN_INDEX_NOOP_OK)
002612     && !ExprHasProperty(pX, EP_xIsSelect)
002613     && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
002614    ){
002615      eType = IN_INDEX_NOOP;
002616    }
002617  
002618    if( eType==0 ){
002619      /* Could not find an existing table or index to use as the RHS b-tree.
002620      ** We will have to generate an ephemeral table to do the job.
002621      */
002622      u32 savedNQueryLoop = pParse->nQueryLoop;
002623      int rMayHaveNull = 0;
002624      eType = IN_INDEX_EPH;
002625      if( inFlags & IN_INDEX_LOOP ){
002626        pParse->nQueryLoop = 0;
002627      }else if( prRhsHasNull ){
002628        *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
002629      }
002630      assert( pX->op==TK_IN );
002631      sqlite3CodeRhsOfIN(pParse, pX, iTab);
002632      if( rMayHaveNull ){
002633        sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
002634      }
002635      pParse->nQueryLoop = savedNQueryLoop;
002636    }
002637  
002638    if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
002639      int i, n;
002640      n = sqlite3ExprVectorSize(pX->pLeft);
002641      for(i=0; i<n; i++) aiMap[i] = i;
002642    }
002643    *piTab = iTab;
002644    return eType;
002645  }
002646  #endif
002647  
002648  #ifndef SQLITE_OMIT_SUBQUERY
002649  /*
002650  ** Argument pExpr is an (?, ?...) IN(...) expression. This 
002651  ** function allocates and returns a nul-terminated string containing 
002652  ** the affinities to be used for each column of the comparison.
002653  **
002654  ** It is the responsibility of the caller to ensure that the returned
002655  ** string is eventually freed using sqlite3DbFree().
002656  */
002657  static char *exprINAffinity(Parse *pParse, Expr *pExpr){
002658    Expr *pLeft = pExpr->pLeft;
002659    int nVal = sqlite3ExprVectorSize(pLeft);
002660    Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
002661    char *zRet;
002662  
002663    assert( pExpr->op==TK_IN );
002664    zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
002665    if( zRet ){
002666      int i;
002667      for(i=0; i<nVal; i++){
002668        Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
002669        char a = sqlite3ExprAffinity(pA);
002670        if( pSelect ){
002671          zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
002672        }else{
002673          zRet[i] = a;
002674        }
002675      }
002676      zRet[nVal] = '\0';
002677    }
002678    return zRet;
002679  }
002680  #endif
002681  
002682  #ifndef SQLITE_OMIT_SUBQUERY
002683  /*
002684  ** Load the Parse object passed as the first argument with an error 
002685  ** message of the form:
002686  **
002687  **   "sub-select returns N columns - expected M"
002688  */   
002689  void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
002690    if( pParse->nErr==0 ){
002691      const char *zFmt = "sub-select returns %d columns - expected %d";
002692      sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
002693    }
002694  }
002695  #endif
002696  
002697  /*
002698  ** Expression pExpr is a vector that has been used in a context where
002699  ** it is not permitted. If pExpr is a sub-select vector, this routine 
002700  ** loads the Parse object with a message of the form:
002701  **
002702  **   "sub-select returns N columns - expected 1"
002703  **
002704  ** Or, if it is a regular scalar vector:
002705  **
002706  **   "row value misused"
002707  */   
002708  void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
002709  #ifndef SQLITE_OMIT_SUBQUERY
002710    if( pExpr->flags & EP_xIsSelect ){
002711      sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
002712    }else
002713  #endif
002714    {
002715      sqlite3ErrorMsg(pParse, "row value misused");
002716    }
002717  }
002718  
002719  #ifndef SQLITE_OMIT_SUBQUERY
002720  /*
002721  ** Generate code that will construct an ephemeral table containing all terms
002722  ** in the RHS of an IN operator.  The IN operator can be in either of two
002723  ** forms:
002724  **
002725  **     x IN (4,5,11)              -- IN operator with list on right-hand side
002726  **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
002727  **
002728  ** The pExpr parameter is the IN operator.  The cursor number for the
002729  ** constructed ephermeral table is returned.  The first time the ephemeral
002730  ** table is computed, the cursor number is also stored in pExpr->iTable,
002731  ** however the cursor number returned might not be the same, as it might
002732  ** have been duplicated using OP_OpenDup.
002733  **
002734  ** If the LHS expression ("x" in the examples) is a column value, or
002735  ** the SELECT statement returns a column value, then the affinity of that
002736  ** column is used to build the index keys. If both 'x' and the
002737  ** SELECT... statement are columns, then numeric affinity is used
002738  ** if either column has NUMERIC or INTEGER affinity. If neither
002739  ** 'x' nor the SELECT... statement are columns, then numeric affinity
002740  ** is used.
002741  */
002742  void sqlite3CodeRhsOfIN(
002743    Parse *pParse,          /* Parsing context */
002744    Expr *pExpr,            /* The IN operator */
002745    int iTab                /* Use this cursor number */
002746  ){
002747    int addrOnce = 0;           /* Address of the OP_Once instruction at top */
002748    int addr;                   /* Address of OP_OpenEphemeral instruction */
002749    Expr *pLeft;                /* the LHS of the IN operator */
002750    KeyInfo *pKeyInfo = 0;      /* Key information */
002751    int nVal;                   /* Size of vector pLeft */
002752    Vdbe *v;                    /* The prepared statement under construction */
002753  
002754    v = pParse->pVdbe;
002755    assert( v!=0 );
002756  
002757    /* The evaluation of the IN must be repeated every time it
002758    ** is encountered if any of the following is true:
002759    **
002760    **    *  The right-hand side is a correlated subquery
002761    **    *  The right-hand side is an expression list containing variables
002762    **    *  We are inside a trigger
002763    **
002764    ** If all of the above are false, then we can compute the RHS just once
002765    ** and reuse it many names.
002766    */
002767    if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
002768      /* Reuse of the RHS is allowed */
002769      /* If this routine has already been coded, but the previous code
002770      ** might not have been invoked yet, so invoke it now as a subroutine. 
002771      */
002772      if( ExprHasProperty(pExpr, EP_Subrtn) ){
002773        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
002774        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
002775          ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
002776                pExpr->x.pSelect->selId));
002777        }
002778        sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
002779                          pExpr->y.sub.iAddr);
002780        sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
002781        sqlite3VdbeJumpHere(v, addrOnce);
002782        return;
002783      }
002784  
002785      /* Begin coding the subroutine */
002786      ExprSetProperty(pExpr, EP_Subrtn);
002787      pExpr->y.sub.regReturn = ++pParse->nMem;
002788      pExpr->y.sub.iAddr =
002789        sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
002790      VdbeComment((v, "return address"));
002791  
002792      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
002793    }
002794  
002795    /* Check to see if this is a vector IN operator */
002796    pLeft = pExpr->pLeft;
002797    nVal = sqlite3ExprVectorSize(pLeft);
002798  
002799    /* Construct the ephemeral table that will contain the content of
002800    ** RHS of the IN operator.
002801    */
002802    pExpr->iTable = iTab;
002803    addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
002804  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002805    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
002806      VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
002807    }else{
002808      VdbeComment((v, "RHS of IN operator"));
002809    }
002810  #endif
002811    pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
002812  
002813    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
002814      /* Case 1:     expr IN (SELECT ...)
002815      **
002816      ** Generate code to write the results of the select into the temporary
002817      ** table allocated and opened above.
002818      */
002819      Select *pSelect = pExpr->x.pSelect;
002820      ExprList *pEList = pSelect->pEList;
002821  
002822      ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
002823          addrOnce?"":"CORRELATED ", pSelect->selId
002824      ));
002825      /* If the LHS and RHS of the IN operator do not match, that
002826      ** error will have been caught long before we reach this point. */
002827      if( ALWAYS(pEList->nExpr==nVal) ){
002828        SelectDest dest;
002829        int i;
002830        sqlite3SelectDestInit(&dest, SRT_Set, iTab);
002831        dest.zAffSdst = exprINAffinity(pParse, pExpr);
002832        pSelect->iLimit = 0;
002833        testcase( pSelect->selFlags & SF_Distinct );
002834        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
002835        if( sqlite3Select(pParse, pSelect, &dest) ){
002836          sqlite3DbFree(pParse->db, dest.zAffSdst);
002837          sqlite3KeyInfoUnref(pKeyInfo);
002838          return;
002839        }
002840        sqlite3DbFree(pParse->db, dest.zAffSdst);
002841        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
002842        assert( pEList!=0 );
002843        assert( pEList->nExpr>0 );
002844        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
002845        for(i=0; i<nVal; i++){
002846          Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
002847          pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
002848              pParse, p, pEList->a[i].pExpr
002849          );
002850        }
002851      }
002852    }else if( ALWAYS(pExpr->x.pList!=0) ){
002853      /* Case 2:     expr IN (exprlist)
002854      **
002855      ** For each expression, build an index key from the evaluation and
002856      ** store it in the temporary table. If <expr> is a column, then use
002857      ** that columns affinity when building index keys. If <expr> is not
002858      ** a column, use numeric affinity.
002859      */
002860      char affinity;            /* Affinity of the LHS of the IN */
002861      int i;
002862      ExprList *pList = pExpr->x.pList;
002863      struct ExprList_item *pItem;
002864      int r1, r2;
002865      affinity = sqlite3ExprAffinity(pLeft);
002866      if( affinity<=SQLITE_AFF_NONE ){
002867        affinity = SQLITE_AFF_BLOB;
002868      }
002869      if( pKeyInfo ){
002870        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
002871        pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
002872      }
002873  
002874      /* Loop through each expression in <exprlist>. */
002875      r1 = sqlite3GetTempReg(pParse);
002876      r2 = sqlite3GetTempReg(pParse);
002877      for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
002878        Expr *pE2 = pItem->pExpr;
002879  
002880        /* If the expression is not constant then we will need to
002881        ** disable the test that was generated above that makes sure
002882        ** this code only executes once.  Because for a non-constant
002883        ** expression we need to rerun this code each time.
002884        */
002885        if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
002886          sqlite3VdbeChangeToNoop(v, addrOnce);
002887          ExprClearProperty(pExpr, EP_Subrtn);
002888          addrOnce = 0;
002889        }
002890  
002891        /* Evaluate the expression and insert it into the temp table */
002892        sqlite3ExprCode(pParse, pE2, r1);
002893        sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
002894        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
002895      }
002896      sqlite3ReleaseTempReg(pParse, r1);
002897      sqlite3ReleaseTempReg(pParse, r2);
002898    }
002899    if( pKeyInfo ){
002900      sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
002901    }
002902    if( addrOnce ){
002903      sqlite3VdbeJumpHere(v, addrOnce);
002904      /* Subroutine return */
002905      sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
002906      sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
002907      sqlite3ClearTempRegCache(pParse);
002908    }
002909  }
002910  #endif /* SQLITE_OMIT_SUBQUERY */
002911  
002912  /*
002913  ** Generate code for scalar subqueries used as a subquery expression
002914  ** or EXISTS operator:
002915  **
002916  **     (SELECT a FROM b)          -- subquery
002917  **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
002918  **
002919  ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
002920  **
002921  ** Return the register that holds the result.  For a multi-column SELECT, 
002922  ** the result is stored in a contiguous array of registers and the
002923  ** return value is the register of the left-most result column.
002924  ** Return 0 if an error occurs.
002925  */
002926  #ifndef SQLITE_OMIT_SUBQUERY
002927  int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
002928    int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
002929    int rReg = 0;               /* Register storing resulting */
002930    Select *pSel;               /* SELECT statement to encode */
002931    SelectDest dest;            /* How to deal with SELECT result */
002932    int nReg;                   /* Registers to allocate */
002933    Expr *pLimit;               /* New limit expression */
002934  
002935    Vdbe *v = pParse->pVdbe;
002936    assert( v!=0 );
002937    testcase( pExpr->op==TK_EXISTS );
002938    testcase( pExpr->op==TK_SELECT );
002939    assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
002940    assert( ExprHasProperty(pExpr, EP_xIsSelect) );
002941    pSel = pExpr->x.pSelect;
002942  
002943    /* The evaluation of the EXISTS/SELECT must be repeated every time it
002944    ** is encountered if any of the following is true:
002945    **
002946    **    *  The right-hand side is a correlated subquery
002947    **    *  The right-hand side is an expression list containing variables
002948    **    *  We are inside a trigger
002949    **
002950    ** If all of the above are false, then we can run this code just once
002951    ** save the results, and reuse the same result on subsequent invocations.
002952    */
002953    if( !ExprHasProperty(pExpr, EP_VarSelect) ){
002954      /* If this routine has already been coded, then invoke it as a
002955      ** subroutine. */
002956      if( ExprHasProperty(pExpr, EP_Subrtn) ){
002957        ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
002958        sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
002959                          pExpr->y.sub.iAddr);
002960        return pExpr->iTable;
002961      }
002962  
002963      /* Begin coding the subroutine */
002964      ExprSetProperty(pExpr, EP_Subrtn);
002965      pExpr->y.sub.regReturn = ++pParse->nMem;
002966      pExpr->y.sub.iAddr =
002967        sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
002968      VdbeComment((v, "return address"));
002969  
002970      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
002971    }
002972    
002973    /* For a SELECT, generate code to put the values for all columns of
002974    ** the first row into an array of registers and return the index of
002975    ** the first register.
002976    **
002977    ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
002978    ** into a register and return that register number.
002979    **
002980    ** In both cases, the query is augmented with "LIMIT 1".  Any 
002981    ** preexisting limit is discarded in place of the new LIMIT 1.
002982    */
002983    ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
002984          addrOnce?"":"CORRELATED ", pSel->selId));
002985    nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
002986    sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
002987    pParse->nMem += nReg;
002988    if( pExpr->op==TK_SELECT ){
002989      dest.eDest = SRT_Mem;
002990      dest.iSdst = dest.iSDParm;
002991      dest.nSdst = nReg;
002992      sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
002993      VdbeComment((v, "Init subquery result"));
002994    }else{
002995      dest.eDest = SRT_Exists;
002996      sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
002997      VdbeComment((v, "Init EXISTS result"));
002998    }
002999    if( pSel->pLimit ){
003000      /* The subquery already has a limit.  If the pre-existing limit is X
003001      ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
003002      sqlite3 *db = pParse->db;
003003      pLimit = sqlite3Expr(db, TK_INTEGER, "0");
003004      if( pLimit ){
003005        pLimit->affExpr = SQLITE_AFF_NUMERIC;
003006        pLimit = sqlite3PExpr(pParse, TK_NE,
003007                              sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
003008      }
003009      sqlite3ExprDelete(db, pSel->pLimit->pLeft);
003010      pSel->pLimit->pLeft = pLimit;
003011    }else{
003012      /* If there is no pre-existing limit add a limit of 1 */
003013      pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
003014      pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
003015    }
003016    pSel->iLimit = 0;
003017    if( sqlite3Select(pParse, pSel, &dest) ){
003018      return 0;
003019    }
003020    pExpr->iTable = rReg = dest.iSDParm;
003021    ExprSetVVAProperty(pExpr, EP_NoReduce);
003022    if( addrOnce ){
003023      sqlite3VdbeJumpHere(v, addrOnce);
003024  
003025      /* Subroutine return */
003026      sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
003027      sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
003028      sqlite3ClearTempRegCache(pParse);
003029    }
003030  
003031    return rReg;
003032  }
003033  #endif /* SQLITE_OMIT_SUBQUERY */
003034  
003035  #ifndef SQLITE_OMIT_SUBQUERY
003036  /*
003037  ** Expr pIn is an IN(...) expression. This function checks that the 
003038  ** sub-select on the RHS of the IN() operator has the same number of 
003039  ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 
003040  ** a sub-query, that the LHS is a vector of size 1.
003041  */
003042  int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
003043    int nVector = sqlite3ExprVectorSize(pIn->pLeft);
003044    if( (pIn->flags & EP_xIsSelect) ){
003045      if( nVector!=pIn->x.pSelect->pEList->nExpr ){
003046        sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
003047        return 1;
003048      }
003049    }else if( nVector!=1 ){
003050      sqlite3VectorErrorMsg(pParse, pIn->pLeft);
003051      return 1;
003052    }
003053    return 0;
003054  }
003055  #endif
003056  
003057  #ifndef SQLITE_OMIT_SUBQUERY
003058  /*
003059  ** Generate code for an IN expression.
003060  **
003061  **      x IN (SELECT ...)
003062  **      x IN (value, value, ...)
003063  **
003064  ** The left-hand side (LHS) is a scalar or vector expression.  The 
003065  ** right-hand side (RHS) is an array of zero or more scalar values, or a
003066  ** subquery.  If the RHS is a subquery, the number of result columns must
003067  ** match the number of columns in the vector on the LHS.  If the RHS is
003068  ** a list of values, the LHS must be a scalar. 
003069  **
003070  ** The IN operator is true if the LHS value is contained within the RHS.
003071  ** The result is false if the LHS is definitely not in the RHS.  The 
003072  ** result is NULL if the presence of the LHS in the RHS cannot be 
003073  ** determined due to NULLs.
003074  **
003075  ** This routine generates code that jumps to destIfFalse if the LHS is not 
003076  ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
003077  ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
003078  ** within the RHS then fall through.
003079  **
003080  ** See the separate in-operator.md documentation file in the canonical
003081  ** SQLite source tree for additional information.
003082  */
003083  static void sqlite3ExprCodeIN(
003084    Parse *pParse,        /* Parsing and code generating context */
003085    Expr *pExpr,          /* The IN expression */
003086    int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
003087    int destIfNull        /* Jump here if the results are unknown due to NULLs */
003088  ){
003089    int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
003090    int eType;            /* Type of the RHS */
003091    int rLhs;             /* Register(s) holding the LHS values */
003092    int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
003093    Vdbe *v;              /* Statement under construction */
003094    int *aiMap = 0;       /* Map from vector field to index column */
003095    char *zAff = 0;       /* Affinity string for comparisons */
003096    int nVector;          /* Size of vectors for this IN operator */
003097    int iDummy;           /* Dummy parameter to exprCodeVector() */
003098    Expr *pLeft;          /* The LHS of the IN operator */
003099    int i;                /* loop counter */
003100    int destStep2;        /* Where to jump when NULLs seen in step 2 */
003101    int destStep6 = 0;    /* Start of code for Step 6 */
003102    int addrTruthOp;      /* Address of opcode that determines the IN is true */
003103    int destNotNull;      /* Jump here if a comparison is not true in step 6 */
003104    int addrTop;          /* Top of the step-6 loop */ 
003105    int iTab = 0;         /* Index to use */
003106  
003107    pLeft = pExpr->pLeft;
003108    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
003109    zAff = exprINAffinity(pParse, pExpr);
003110    nVector = sqlite3ExprVectorSize(pExpr->pLeft);
003111    aiMap = (int*)sqlite3DbMallocZero(
003112        pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
003113    );
003114    if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
003115  
003116    /* Attempt to compute the RHS. After this step, if anything other than
003117    ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
003118    ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
003119    ** the RHS has not yet been coded.  */
003120    v = pParse->pVdbe;
003121    assert( v!=0 );       /* OOM detected prior to this routine */
003122    VdbeNoopComment((v, "begin IN expr"));
003123    eType = sqlite3FindInIndex(pParse, pExpr,
003124                               IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
003125                               destIfFalse==destIfNull ? 0 : &rRhsHasNull,
003126                               aiMap, &iTab);
003127  
003128    assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
003129         || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 
003130    );
003131  #ifdef SQLITE_DEBUG
003132    /* Confirm that aiMap[] contains nVector integer values between 0 and
003133    ** nVector-1. */
003134    for(i=0; i<nVector; i++){
003135      int j, cnt;
003136      for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
003137      assert( cnt==1 );
003138    }
003139  #endif
003140  
003141    /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 
003142    ** vector, then it is stored in an array of nVector registers starting 
003143    ** at r1.
003144    **
003145    ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
003146    ** so that the fields are in the same order as an existing index.   The
003147    ** aiMap[] array contains a mapping from the original LHS field order to
003148    ** the field order that matches the RHS index.
003149    */
003150    rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
003151    for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
003152    if( i==nVector ){
003153      /* LHS fields are not reordered */
003154      rLhs = rLhsOrig;
003155    }else{
003156      /* Need to reorder the LHS fields according to aiMap */
003157      rLhs = sqlite3GetTempRange(pParse, nVector);
003158      for(i=0; i<nVector; i++){
003159        sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
003160      }
003161    }
003162  
003163    /* If sqlite3FindInIndex() did not find or create an index that is
003164    ** suitable for evaluating the IN operator, then evaluate using a
003165    ** sequence of comparisons.
003166    **
003167    ** This is step (1) in the in-operator.md optimized algorithm.
003168    */
003169    if( eType==IN_INDEX_NOOP ){
003170      ExprList *pList = pExpr->x.pList;
003171      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
003172      int labelOk = sqlite3VdbeMakeLabel(pParse);
003173      int r2, regToFree;
003174      int regCkNull = 0;
003175      int ii;
003176      int bLhsReal;  /* True if the LHS of the IN has REAL affinity */
003177      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
003178      if( destIfNull!=destIfFalse ){
003179        regCkNull = sqlite3GetTempReg(pParse);
003180        sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
003181      }
003182      bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
003183      for(ii=0; ii<pList->nExpr; ii++){
003184        if( bLhsReal ){
003185          r2 = regToFree = sqlite3GetTempReg(pParse);
003186          sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
003187          sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
003188        }else{
003189          r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
003190        }
003191        if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
003192          sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
003193        }
003194        if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
003195          int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
003196          sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
003197                            (void*)pColl, P4_COLLSEQ);
003198          VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
003199          VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
003200          VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
003201          VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
003202          sqlite3VdbeChangeP5(v, zAff[0]);
003203        }else{
003204          int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
003205          assert( destIfNull==destIfFalse );
003206          sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
003207                            (void*)pColl, P4_COLLSEQ);
003208          VdbeCoverageIf(v, op==OP_Ne);
003209          VdbeCoverageIf(v, op==OP_IsNull);
003210          sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
003211        }
003212        sqlite3ReleaseTempReg(pParse, regToFree);
003213      }
003214      if( regCkNull ){
003215        sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
003216        sqlite3VdbeGoto(v, destIfFalse);
003217      }
003218      sqlite3VdbeResolveLabel(v, labelOk);
003219      sqlite3ReleaseTempReg(pParse, regCkNull);
003220      goto sqlite3ExprCodeIN_finished;
003221    }
003222  
003223    /* Step 2: Check to see if the LHS contains any NULL columns.  If the
003224    ** LHS does contain NULLs then the result must be either FALSE or NULL.
003225    ** We will then skip the binary search of the RHS.
003226    */
003227    if( destIfNull==destIfFalse ){
003228      destStep2 = destIfFalse;
003229    }else{
003230      destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
003231    }
003232    if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
003233    for(i=0; i<nVector; i++){
003234      Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
003235      if( sqlite3ExprCanBeNull(p) ){
003236        sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
003237        VdbeCoverage(v);
003238      }
003239    }
003240  
003241    /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
003242    ** of the RHS using the LHS as a probe.  If found, the result is
003243    ** true.
003244    */
003245    if( eType==IN_INDEX_ROWID ){
003246      /* In this case, the RHS is the ROWID of table b-tree and so we also
003247      ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
003248      ** into a single opcode. */
003249      sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
003250      VdbeCoverage(v);
003251      addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
003252    }else{
003253      sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
003254      if( destIfFalse==destIfNull ){
003255        /* Combine Step 3 and Step 5 into a single opcode */
003256        sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
003257                             rLhs, nVector); VdbeCoverage(v);
003258        goto sqlite3ExprCodeIN_finished;
003259      }
003260      /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
003261      addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
003262                                        rLhs, nVector); VdbeCoverage(v);
003263    }
003264  
003265    /* Step 4.  If the RHS is known to be non-NULL and we did not find
003266    ** an match on the search above, then the result must be FALSE.
003267    */
003268    if( rRhsHasNull && nVector==1 ){
003269      sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
003270      VdbeCoverage(v);
003271    }
003272  
003273    /* Step 5.  If we do not care about the difference between NULL and
003274    ** FALSE, then just return false. 
003275    */
003276    if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
003277  
003278    /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
003279    ** If any comparison is NULL, then the result is NULL.  If all
003280    ** comparisons are FALSE then the final result is FALSE.
003281    **
003282    ** For a scalar LHS, it is sufficient to check just the first row
003283    ** of the RHS.
003284    */
003285    if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
003286    addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
003287    VdbeCoverage(v);
003288    if( nVector>1 ){
003289      destNotNull = sqlite3VdbeMakeLabel(pParse);
003290    }else{
003291      /* For nVector==1, combine steps 6 and 7 by immediately returning
003292      ** FALSE if the first comparison is not NULL */
003293      destNotNull = destIfFalse;
003294    }
003295    for(i=0; i<nVector; i++){
003296      Expr *p;
003297      CollSeq *pColl;
003298      int r3 = sqlite3GetTempReg(pParse);
003299      p = sqlite3VectorFieldSubexpr(pLeft, i);
003300      pColl = sqlite3ExprCollSeq(pParse, p);
003301      sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
003302      sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
003303                        (void*)pColl, P4_COLLSEQ);
003304      VdbeCoverage(v);
003305      sqlite3ReleaseTempReg(pParse, r3);
003306    }
003307    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
003308    if( nVector>1 ){
003309      sqlite3VdbeResolveLabel(v, destNotNull);
003310      sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
003311      VdbeCoverage(v);
003312  
003313      /* Step 7:  If we reach this point, we know that the result must
003314      ** be false. */
003315      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
003316    }
003317  
003318    /* Jumps here in order to return true. */
003319    sqlite3VdbeJumpHere(v, addrTruthOp);
003320  
003321  sqlite3ExprCodeIN_finished:
003322    if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
003323    VdbeComment((v, "end IN expr"));
003324  sqlite3ExprCodeIN_oom_error:
003325    sqlite3DbFree(pParse->db, aiMap);
003326    sqlite3DbFree(pParse->db, zAff);
003327  }
003328  #endif /* SQLITE_OMIT_SUBQUERY */
003329  
003330  #ifndef SQLITE_OMIT_FLOATING_POINT
003331  /*
003332  ** Generate an instruction that will put the floating point
003333  ** value described by z[0..n-1] into register iMem.
003334  **
003335  ** The z[] string will probably not be zero-terminated.  But the 
003336  ** z[n] character is guaranteed to be something that does not look
003337  ** like the continuation of the number.
003338  */
003339  static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
003340    if( ALWAYS(z!=0) ){
003341      double value;
003342      sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
003343      assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
003344      if( negateFlag ) value = -value;
003345      sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
003346    }
003347  }
003348  #endif
003349  
003350  
003351  /*
003352  ** Generate an instruction that will put the integer describe by
003353  ** text z[0..n-1] into register iMem.
003354  **
003355  ** Expr.u.zToken is always UTF8 and zero-terminated.
003356  */
003357  static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
003358    Vdbe *v = pParse->pVdbe;
003359    if( pExpr->flags & EP_IntValue ){
003360      int i = pExpr->u.iValue;
003361      assert( i>=0 );
003362      if( negFlag ) i = -i;
003363      sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
003364    }else{
003365      int c;
003366      i64 value;
003367      const char *z = pExpr->u.zToken;
003368      assert( z!=0 );
003369      c = sqlite3DecOrHexToI64(z, &value);
003370      if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
003371  #ifdef SQLITE_OMIT_FLOATING_POINT
003372        sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
003373  #else
003374  #ifndef SQLITE_OMIT_HEX_INTEGER
003375        if( sqlite3_strnicmp(z,"0x",2)==0 ){
003376          sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
003377        }else
003378  #endif
003379        {
003380          codeReal(v, z, negFlag, iMem);
003381        }
003382  #endif
003383      }else{
003384        if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
003385        sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
003386      }
003387    }
003388  }
003389  
003390  
003391  /* Generate code that will load into register regOut a value that is
003392  ** appropriate for the iIdxCol-th column of index pIdx.
003393  */
003394  void sqlite3ExprCodeLoadIndexColumn(
003395    Parse *pParse,  /* The parsing context */
003396    Index *pIdx,    /* The index whose column is to be loaded */
003397    int iTabCur,    /* Cursor pointing to a table row */
003398    int iIdxCol,    /* The column of the index to be loaded */
003399    int regOut      /* Store the index column value in this register */
003400  ){
003401    i16 iTabCol = pIdx->aiColumn[iIdxCol];
003402    if( iTabCol==XN_EXPR ){
003403      assert( pIdx->aColExpr );
003404      assert( pIdx->aColExpr->nExpr>iIdxCol );
003405      pParse->iSelfTab = iTabCur + 1;
003406      sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
003407      pParse->iSelfTab = 0;
003408    }else{
003409      sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
003410                                      iTabCol, regOut);
003411    }
003412  }
003413  
003414  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
003415  /*
003416  ** Generate code that will compute the value of generated column pCol
003417  ** and store the result in register regOut
003418  */
003419  void sqlite3ExprCodeGeneratedColumn(
003420    Parse *pParse,
003421    Column *pCol,
003422    int regOut
003423  ){
003424    int iAddr;
003425    Vdbe *v = pParse->pVdbe;
003426    assert( v!=0 );
003427    assert( pParse->iSelfTab!=0 );
003428    if( pParse->iSelfTab>0 ){
003429      iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
003430    }else{
003431      iAddr = 0;
003432    }
003433    sqlite3ExprCode(pParse, pCol->pDflt, regOut);
003434    if( pCol->affinity>=SQLITE_AFF_TEXT ){
003435      sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
003436    }
003437    if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
003438  }
003439  #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
003440  
003441  /*
003442  ** Generate code to extract the value of the iCol-th column of a table.
003443  */
003444  void sqlite3ExprCodeGetColumnOfTable(
003445    Vdbe *v,        /* Parsing context */
003446    Table *pTab,    /* The table containing the value */
003447    int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
003448    int iCol,       /* Index of the column to extract */
003449    int regOut      /* Extract the value into this register */
003450  ){
003451    Column *pCol;
003452    assert( v!=0 );
003453    if( pTab==0 ){
003454      sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
003455      return;
003456    }
003457    if( iCol<0 || iCol==pTab->iPKey ){
003458      sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
003459    }else{
003460      int op;
003461      int x;
003462      if( IsVirtual(pTab) ){
003463        op = OP_VColumn;
003464        x = iCol;
003465  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
003466      }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
003467        Parse *pParse = sqlite3VdbeParser(v);
003468        if( pCol->colFlags & COLFLAG_BUSY ){
003469          sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
003470        }else{
003471          int savedSelfTab = pParse->iSelfTab;
003472          pCol->colFlags |= COLFLAG_BUSY;
003473          pParse->iSelfTab = iTabCur+1;
003474          sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
003475          pParse->iSelfTab = savedSelfTab;
003476          pCol->colFlags &= ~COLFLAG_BUSY;
003477        }
003478        return;
003479  #endif
003480      }else if( !HasRowid(pTab) ){
003481        testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
003482        x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
003483        op = OP_Column;
003484      }else{
003485        x = sqlite3TableColumnToStorage(pTab,iCol);
003486        testcase( x!=iCol );
003487        op = OP_Column;
003488      }
003489      sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
003490      sqlite3ColumnDefault(v, pTab, iCol, regOut);
003491    }
003492  }
003493  
003494  /*
003495  ** Generate code that will extract the iColumn-th column from
003496  ** table pTab and store the column value in register iReg. 
003497  **
003498  ** There must be an open cursor to pTab in iTable when this routine
003499  ** is called.  If iColumn<0 then code is generated that extracts the rowid.
003500  */
003501  int sqlite3ExprCodeGetColumn(
003502    Parse *pParse,   /* Parsing and code generating context */
003503    Table *pTab,     /* Description of the table we are reading from */
003504    int iColumn,     /* Index of the table column */
003505    int iTable,      /* The cursor pointing to the table */
003506    int iReg,        /* Store results here */
003507    u8 p5            /* P5 value for OP_Column + FLAGS */
003508  ){
003509    assert( pParse->pVdbe!=0 );
003510    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
003511    if( p5 ){
003512      VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
003513      if( pOp->opcode==OP_Column ) pOp->p5 = p5;
003514    }
003515    return iReg;
003516  }
003517  
003518  /*
003519  ** Generate code to move content from registers iFrom...iFrom+nReg-1
003520  ** over to iTo..iTo+nReg-1.
003521  */
003522  void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
003523    sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
003524  }
003525  
003526  /*
003527  ** Convert a scalar expression node to a TK_REGISTER referencing
003528  ** register iReg.  The caller must ensure that iReg already contains
003529  ** the correct value for the expression.
003530  */
003531  static void exprToRegister(Expr *pExpr, int iReg){
003532    Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
003533    p->op2 = p->op;
003534    p->op = TK_REGISTER;
003535    p->iTable = iReg;
003536    ExprClearProperty(p, EP_Skip);
003537  }
003538  
003539  /*
003540  ** Evaluate an expression (either a vector or a scalar expression) and store
003541  ** the result in continguous temporary registers.  Return the index of
003542  ** the first register used to store the result.
003543  **
003544  ** If the returned result register is a temporary scalar, then also write
003545  ** that register number into *piFreeable.  If the returned result register
003546  ** is not a temporary or if the expression is a vector set *piFreeable
003547  ** to 0.
003548  */
003549  static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
003550    int iResult;
003551    int nResult = sqlite3ExprVectorSize(p);
003552    if( nResult==1 ){
003553      iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
003554    }else{
003555      *piFreeable = 0;
003556      if( p->op==TK_SELECT ){
003557  #if SQLITE_OMIT_SUBQUERY
003558        iResult = 0;
003559  #else
003560        iResult = sqlite3CodeSubselect(pParse, p);
003561  #endif
003562      }else{
003563        int i;
003564        iResult = pParse->nMem+1;
003565        pParse->nMem += nResult;
003566        for(i=0; i<nResult; i++){
003567          sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
003568        }
003569      }
003570    }
003571    return iResult;
003572  }
003573  
003574  
003575  /*
003576  ** Generate code into the current Vdbe to evaluate the given
003577  ** expression.  Attempt to store the results in register "target".
003578  ** Return the register where results are stored.
003579  **
003580  ** With this routine, there is no guarantee that results will
003581  ** be stored in target.  The result might be stored in some other
003582  ** register if it is convenient to do so.  The calling function
003583  ** must check the return code and move the results to the desired
003584  ** register.
003585  */
003586  int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
003587    Vdbe *v = pParse->pVdbe;  /* The VM under construction */
003588    int op;                   /* The opcode being coded */
003589    int inReg = target;       /* Results stored in register inReg */
003590    int regFree1 = 0;         /* If non-zero free this temporary register */
003591    int regFree2 = 0;         /* If non-zero free this temporary register */
003592    int r1, r2;               /* Various register numbers */
003593    Expr tempX;               /* Temporary expression node */
003594    int p5 = 0;
003595  
003596    assert( target>0 && target<=pParse->nMem );
003597    if( v==0 ){
003598      assert( pParse->db->mallocFailed );
003599      return 0;
003600    }
003601  
003602  expr_code_doover:
003603    if( pExpr==0 ){
003604      op = TK_NULL;
003605    }else{
003606      op = pExpr->op;
003607    }
003608    switch( op ){
003609      case TK_AGG_COLUMN: {
003610        AggInfo *pAggInfo = pExpr->pAggInfo;
003611        struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
003612        if( !pAggInfo->directMode ){
003613          assert( pCol->iMem>0 );
003614          return pCol->iMem;
003615        }else if( pAggInfo->useSortingIdx ){
003616          sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
003617                                pCol->iSorterColumn, target);
003618          return target;
003619        }
003620        /* Otherwise, fall thru into the TK_COLUMN case */
003621      }
003622      case TK_COLUMN: {
003623        int iTab = pExpr->iTable;
003624        int iReg;
003625        if( ExprHasProperty(pExpr, EP_FixedCol) ){
003626          /* This COLUMN expression is really a constant due to WHERE clause
003627          ** constraints, and that constant is coded by the pExpr->pLeft
003628          ** expresssion.  However, make sure the constant has the correct
003629          ** datatype by applying the Affinity of the table column to the
003630          ** constant.
003631          */
003632          int aff;
003633          iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
003634          if( pExpr->y.pTab ){
003635            aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
003636          }else{
003637            aff = pExpr->affExpr;
003638          }
003639          if( aff>SQLITE_AFF_BLOB ){
003640            static const char zAff[] = "B\000C\000D\000E";
003641            assert( SQLITE_AFF_BLOB=='A' );
003642            assert( SQLITE_AFF_TEXT=='B' );
003643            if( iReg!=target ){
003644              sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
003645              iReg = target;
003646            }
003647            sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
003648                              &zAff[(aff-'B')*2], P4_STATIC);
003649          }
003650          return iReg;
003651        }
003652        if( iTab<0 ){
003653          if( pParse->iSelfTab<0 ){
003654            /* Other columns in the same row for CHECK constraints or
003655            ** generated columns or for inserting into partial index.
003656            ** The row is unpacked into registers beginning at
003657            ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register
003658            ** immediately prior to the first column.
003659            */
003660            Column *pCol;
003661            Table *pTab = pExpr->y.pTab;
003662            int iSrc;
003663            int iCol = pExpr->iColumn;
003664            assert( pTab!=0 );
003665            assert( iCol>=XN_ROWID );
003666            assert( iCol<pTab->nCol );
003667            if( iCol<0 ){
003668              return -1-pParse->iSelfTab;
003669            }
003670            pCol = pTab->aCol + iCol;
003671            testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
003672            iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
003673  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
003674            if( pCol->colFlags & COLFLAG_GENERATED ){
003675              if( pCol->colFlags & COLFLAG_BUSY ){
003676                sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
003677                                pCol->zName);
003678                return 0;
003679              }
003680              pCol->colFlags |= COLFLAG_BUSY;
003681              if( pCol->colFlags & COLFLAG_NOTAVAIL ){
003682                sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
003683              }
003684              pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
003685              return iSrc;
003686            }else
003687  #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
003688            if( pCol->affinity==SQLITE_AFF_REAL ){
003689              sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
003690              sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
003691              return target;
003692            }else{
003693              return iSrc;
003694            }
003695          }else{
003696            /* Coding an expression that is part of an index where column names
003697            ** in the index refer to the table to which the index belongs */
003698            iTab = pParse->iSelfTab - 1;
003699          }
003700        }
003701        iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
003702                                 pExpr->iColumn, iTab, target,
003703                                 pExpr->op2);
003704        if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
003705          sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
003706        }
003707        return iReg;
003708      }
003709      case TK_INTEGER: {
003710        codeInteger(pParse, pExpr, 0, target);
003711        return target;
003712      }
003713      case TK_TRUEFALSE: {
003714        sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
003715        return target;
003716      }
003717  #ifndef SQLITE_OMIT_FLOATING_POINT
003718      case TK_FLOAT: {
003719        assert( !ExprHasProperty(pExpr, EP_IntValue) );
003720        codeReal(v, pExpr->u.zToken, 0, target);
003721        return target;
003722      }
003723  #endif
003724      case TK_STRING: {
003725        assert( !ExprHasProperty(pExpr, EP_IntValue) );
003726        sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
003727        return target;
003728      }
003729      default: {
003730        /* Make NULL the default case so that if a bug causes an illegal
003731        ** Expr node to be passed into this function, it will be handled
003732        ** sanely and not crash.  But keep the assert() to bring the problem
003733        ** to the attention of the developers. */
003734        assert( op==TK_NULL );
003735        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
003736        return target;
003737      }
003738  #ifndef SQLITE_OMIT_BLOB_LITERAL
003739      case TK_BLOB: {
003740        int n;
003741        const char *z;
003742        char *zBlob;
003743        assert( !ExprHasProperty(pExpr, EP_IntValue) );
003744        assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
003745        assert( pExpr->u.zToken[1]=='\'' );
003746        z = &pExpr->u.zToken[2];
003747        n = sqlite3Strlen30(z) - 1;
003748        assert( z[n]=='\'' );
003749        zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
003750        sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
003751        return target;
003752      }
003753  #endif
003754      case TK_VARIABLE: {
003755        assert( !ExprHasProperty(pExpr, EP_IntValue) );
003756        assert( pExpr->u.zToken!=0 );
003757        assert( pExpr->u.zToken[0]!=0 );
003758        sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
003759        if( pExpr->u.zToken[1]!=0 ){
003760          const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
003761          assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
003762          pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
003763          sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
003764        }
003765        return target;
003766      }
003767      case TK_REGISTER: {
003768        return pExpr->iTable;
003769      }
003770  #ifndef SQLITE_OMIT_CAST
003771      case TK_CAST: {
003772        /* Expressions of the form:   CAST(pLeft AS token) */
003773        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
003774        if( inReg!=target ){
003775          sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
003776          inReg = target;
003777        }
003778        sqlite3VdbeAddOp2(v, OP_Cast, target,
003779                          sqlite3AffinityType(pExpr->u.zToken, 0));
003780        return inReg;
003781      }
003782  #endif /* SQLITE_OMIT_CAST */
003783      case TK_IS:
003784      case TK_ISNOT:
003785        op = (op==TK_IS) ? TK_EQ : TK_NE;
003786        p5 = SQLITE_NULLEQ;
003787        /* fall-through */
003788      case TK_LT:
003789      case TK_LE:
003790      case TK_GT:
003791      case TK_GE:
003792      case TK_NE:
003793      case TK_EQ: {
003794        Expr *pLeft = pExpr->pLeft;
003795        if( sqlite3ExprIsVector(pLeft) ){
003796          codeVectorCompare(pParse, pExpr, target, op, p5);
003797        }else{
003798          r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
003799          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
003800          codeCompare(pParse, pLeft, pExpr->pRight, op,
003801              r1, r2, inReg, SQLITE_STOREP2 | p5,
003802              ExprHasProperty(pExpr,EP_Commuted));
003803          assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
003804          assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
003805          assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
003806          assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
003807          assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
003808          assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
003809          testcase( regFree1==0 );
003810          testcase( regFree2==0 );
003811        }
003812        break;
003813      }
003814      case TK_AND:
003815      case TK_OR:
003816      case TK_PLUS:
003817      case TK_STAR:
003818      case TK_MINUS:
003819      case TK_REM:
003820      case TK_BITAND:
003821      case TK_BITOR:
003822      case TK_SLASH:
003823      case TK_LSHIFT:
003824      case TK_RSHIFT: 
003825      case TK_CONCAT: {
003826        assert( TK_AND==OP_And );            testcase( op==TK_AND );
003827        assert( TK_OR==OP_Or );              testcase( op==TK_OR );
003828        assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
003829        assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
003830        assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
003831        assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
003832        assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
003833        assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
003834        assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
003835        assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
003836        assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
003837        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
003838        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
003839        sqlite3VdbeAddOp3(v, op, r2, r1, target);
003840        testcase( regFree1==0 );
003841        testcase( regFree2==0 );
003842        break;
003843      }
003844      case TK_UMINUS: {
003845        Expr *pLeft = pExpr->pLeft;
003846        assert( pLeft );
003847        if( pLeft->op==TK_INTEGER ){
003848          codeInteger(pParse, pLeft, 1, target);
003849          return target;
003850  #ifndef SQLITE_OMIT_FLOATING_POINT
003851        }else if( pLeft->op==TK_FLOAT ){
003852          assert( !ExprHasProperty(pExpr, EP_IntValue) );
003853          codeReal(v, pLeft->u.zToken, 1, target);
003854          return target;
003855  #endif
003856        }else{
003857          tempX.op = TK_INTEGER;
003858          tempX.flags = EP_IntValue|EP_TokenOnly;
003859          tempX.u.iValue = 0;
003860          r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
003861          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
003862          sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
003863          testcase( regFree2==0 );
003864        }
003865        break;
003866      }
003867      case TK_BITNOT:
003868      case TK_NOT: {
003869        assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
003870        assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
003871        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
003872        testcase( regFree1==0 );
003873        sqlite3VdbeAddOp2(v, op, r1, inReg);
003874        break;
003875      }
003876      case TK_TRUTH: {
003877        int isTrue;    /* IS TRUE or IS NOT TRUE */
003878        int bNormal;   /* IS TRUE or IS FALSE */
003879        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
003880        testcase( regFree1==0 );
003881        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
003882        bNormal = pExpr->op2==TK_IS;
003883        testcase( isTrue && bNormal);
003884        testcase( !isTrue && bNormal);
003885        sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
003886        break;
003887      }
003888      case TK_ISNULL:
003889      case TK_NOTNULL: {
003890        int addr;
003891        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
003892        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
003893        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
003894        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
003895        testcase( regFree1==0 );
003896        addr = sqlite3VdbeAddOp1(v, op, r1);
003897        VdbeCoverageIf(v, op==TK_ISNULL);
003898        VdbeCoverageIf(v, op==TK_NOTNULL);
003899        sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
003900        sqlite3VdbeJumpHere(v, addr);
003901        break;
003902      }
003903      case TK_AGG_FUNCTION: {
003904        AggInfo *pInfo = pExpr->pAggInfo;
003905        if( pInfo==0 ){
003906          assert( !ExprHasProperty(pExpr, EP_IntValue) );
003907          sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
003908        }else{
003909          return pInfo->aFunc[pExpr->iAgg].iMem;
003910        }
003911        break;
003912      }
003913      case TK_FUNCTION: {
003914        ExprList *pFarg;       /* List of function arguments */
003915        int nFarg;             /* Number of function arguments */
003916        FuncDef *pDef;         /* The function definition object */
003917        const char *zId;       /* The function name */
003918        u32 constMask = 0;     /* Mask of function arguments that are constant */
003919        int i;                 /* Loop counter */
003920        sqlite3 *db = pParse->db;  /* The database connection */
003921        u8 enc = ENC(db);      /* The text encoding used by this database */
003922        CollSeq *pColl = 0;    /* A collating sequence */
003923  
003924  #ifndef SQLITE_OMIT_WINDOWFUNC
003925        if( ExprHasProperty(pExpr, EP_WinFunc) ){
003926          return pExpr->y.pWin->regResult;
003927        }
003928  #endif
003929  
003930        if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
003931          /* SQL functions can be expensive. So try to move constant functions
003932          ** out of the inner loop, even if that means an extra OP_Copy. */
003933          return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
003934        }
003935        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
003936        if( ExprHasProperty(pExpr, EP_TokenOnly) ){
003937          pFarg = 0;
003938        }else{
003939          pFarg = pExpr->x.pList;
003940        }
003941        nFarg = pFarg ? pFarg->nExpr : 0;
003942        assert( !ExprHasProperty(pExpr, EP_IntValue) );
003943        zId = pExpr->u.zToken;
003944        pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
003945  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
003946        if( pDef==0 && pParse->explain ){
003947          pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
003948        }
003949  #endif
003950        if( pDef==0 || pDef->xFinalize!=0 ){
003951          sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
003952          break;
003953        }
003954  
003955        /* Attempt a direct implementation of the built-in COALESCE() and
003956        ** IFNULL() functions.  This avoids unnecessary evaluation of
003957        ** arguments past the first non-NULL argument.
003958        */
003959        if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
003960          int endCoalesce = sqlite3VdbeMakeLabel(pParse);
003961          assert( nFarg>=2 );
003962          sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
003963          for(i=1; i<nFarg; i++){
003964            sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
003965            VdbeCoverage(v);
003966            sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
003967          }
003968          sqlite3VdbeResolveLabel(v, endCoalesce);
003969          break;
003970        }
003971  
003972        /* The UNLIKELY() function is a no-op.  The result is the value
003973        ** of the first argument.
003974        */
003975        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
003976          assert( nFarg>=1 );
003977          return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
003978        }
003979  
003980  #ifdef SQLITE_DEBUG
003981        /* The AFFINITY() function evaluates to a string that describes
003982        ** the type affinity of the argument.  This is used for testing of
003983        ** the SQLite type logic.
003984        */
003985        if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
003986          const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
003987          char aff;
003988          assert( nFarg==1 );
003989          aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
003990          sqlite3VdbeLoadString(v, target, 
003991                  (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
003992          return target;
003993        }
003994  #endif
003995  
003996        for(i=0; i<nFarg; i++){
003997          if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
003998            testcase( i==31 );
003999            constMask |= MASKBIT32(i);
004000          }
004001          if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
004002            pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
004003          }
004004        }
004005        if( pFarg ){
004006          if( constMask ){
004007            r1 = pParse->nMem+1;
004008            pParse->nMem += nFarg;
004009          }else{
004010            r1 = sqlite3GetTempRange(pParse, nFarg);
004011          }
004012  
004013          /* For length() and typeof() functions with a column argument,
004014          ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
004015          ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
004016          ** loading.
004017          */
004018          if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
004019            u8 exprOp;
004020            assert( nFarg==1 );
004021            assert( pFarg->a[0].pExpr!=0 );
004022            exprOp = pFarg->a[0].pExpr->op;
004023            if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
004024              assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
004025              assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
004026              testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
004027              pFarg->a[0].pExpr->op2 = 
004028                    pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
004029            }
004030          }
004031  
004032          sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
004033                                  SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
004034        }else{
004035          r1 = 0;
004036        }
004037  #ifndef SQLITE_OMIT_VIRTUALTABLE
004038        /* Possibly overload the function if the first argument is
004039        ** a virtual table column.
004040        **
004041        ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
004042        ** second argument, not the first, as the argument to test to
004043        ** see if it is a column in a virtual table.  This is done because
004044        ** the left operand of infix functions (the operand we want to
004045        ** control overloading) ends up as the second argument to the
004046        ** function.  The expression "A glob B" is equivalent to 
004047        ** "glob(B,A).  We want to use the A in "A glob B" to test
004048        ** for function overloading.  But we use the B term in "glob(B,A)".
004049        */
004050        if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
004051          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
004052        }else if( nFarg>0 ){
004053          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
004054        }
004055  #endif
004056        if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
004057          if( !pColl ) pColl = db->pDfltColl; 
004058          sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
004059        }
004060  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
004061        if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
004062          Expr *pArg = pFarg->a[0].pExpr;
004063          if( pArg->op==TK_COLUMN ){
004064            sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
004065          }else{
004066            sqlite3VdbeAddOp2(v, OP_Null, 0, target);
004067          }
004068        }else
004069  #endif
004070        {
004071          sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
004072                                     pDef, pExpr->op2);
004073        }
004074        if( nFarg ){
004075          if( constMask==0 ){
004076            sqlite3ReleaseTempRange(pParse, r1, nFarg);
004077          }else{
004078            sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask);
004079          }
004080        }
004081        return target;
004082      }
004083  #ifndef SQLITE_OMIT_SUBQUERY
004084      case TK_EXISTS:
004085      case TK_SELECT: {
004086        int nCol;
004087        testcase( op==TK_EXISTS );
004088        testcase( op==TK_SELECT );
004089        if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
004090          sqlite3SubselectError(pParse, nCol, 1);
004091        }else{
004092          return sqlite3CodeSubselect(pParse, pExpr);
004093        }
004094        break;
004095      }
004096      case TK_SELECT_COLUMN: {
004097        int n;
004098        if( pExpr->pLeft->iTable==0 ){
004099          pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
004100        }
004101        assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
004102        if( pExpr->iTable!=0
004103         && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
004104        ){
004105          sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
004106                                  pExpr->iTable, n);
004107        }
004108        return pExpr->pLeft->iTable + pExpr->iColumn;
004109      }
004110      case TK_IN: {
004111        int destIfFalse = sqlite3VdbeMakeLabel(pParse);
004112        int destIfNull = sqlite3VdbeMakeLabel(pParse);
004113        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
004114        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
004115        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
004116        sqlite3VdbeResolveLabel(v, destIfFalse);
004117        sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
004118        sqlite3VdbeResolveLabel(v, destIfNull);
004119        return target;
004120      }
004121  #endif /* SQLITE_OMIT_SUBQUERY */
004122  
004123  
004124      /*
004125      **    x BETWEEN y AND z
004126      **
004127      ** This is equivalent to
004128      **
004129      **    x>=y AND x<=z
004130      **
004131      ** X is stored in pExpr->pLeft.
004132      ** Y is stored in pExpr->pList->a[0].pExpr.
004133      ** Z is stored in pExpr->pList->a[1].pExpr.
004134      */
004135      case TK_BETWEEN: {
004136        exprCodeBetween(pParse, pExpr, target, 0, 0);
004137        return target;
004138      }
004139      case TK_SPAN:
004140      case TK_COLLATE: 
004141      case TK_UPLUS: {
004142        pExpr = pExpr->pLeft;
004143        goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
004144      }
004145  
004146      case TK_TRIGGER: {
004147        /* If the opcode is TK_TRIGGER, then the expression is a reference
004148        ** to a column in the new.* or old.* pseudo-tables available to
004149        ** trigger programs. In this case Expr.iTable is set to 1 for the
004150        ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
004151        ** is set to the column of the pseudo-table to read, or to -1 to
004152        ** read the rowid field.
004153        **
004154        ** The expression is implemented using an OP_Param opcode. The p1
004155        ** parameter is set to 0 for an old.rowid reference, or to (i+1)
004156        ** to reference another column of the old.* pseudo-table, where 
004157        ** i is the index of the column. For a new.rowid reference, p1 is
004158        ** set to (n+1), where n is the number of columns in each pseudo-table.
004159        ** For a reference to any other column in the new.* pseudo-table, p1
004160        ** is set to (n+2+i), where n and i are as defined previously. For
004161        ** example, if the table on which triggers are being fired is
004162        ** declared as:
004163        **
004164        **   CREATE TABLE t1(a, b);
004165        **
004166        ** Then p1 is interpreted as follows:
004167        **
004168        **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
004169        **   p1==1   ->    old.a         p1==4   ->    new.a
004170        **   p1==2   ->    old.b         p1==5   ->    new.b       
004171        */
004172        Table *pTab = pExpr->y.pTab;
004173        int iCol = pExpr->iColumn;
004174        int p1 = pExpr->iTable * (pTab->nCol+1) + 1 
004175                       + sqlite3TableColumnToStorage(pTab, iCol);
004176  
004177        assert( pExpr->iTable==0 || pExpr->iTable==1 );
004178        assert( iCol>=-1 && iCol<pTab->nCol );
004179        assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
004180        assert( p1>=0 && p1<(pTab->nCol*2+2) );
004181  
004182        sqlite3VdbeAddOp2(v, OP_Param, p1, target);
004183        VdbeComment((v, "r[%d]=%s.%s", target,
004184          (pExpr->iTable ? "new" : "old"),
004185          (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
004186        ));
004187  
004188  #ifndef SQLITE_OMIT_FLOATING_POINT
004189        /* If the column has REAL affinity, it may currently be stored as an
004190        ** integer. Use OP_RealAffinity to make sure it is really real.
004191        **
004192        ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
004193        ** floating point when extracting it from the record.  */
004194        if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
004195          sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
004196        }
004197  #endif
004198        break;
004199      }
004200  
004201      case TK_VECTOR: {
004202        sqlite3ErrorMsg(pParse, "row value misused");
004203        break;
004204      }
004205  
004206      /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
004207      ** that derive from the right-hand table of a LEFT JOIN.  The
004208      ** Expr.iTable value is the table number for the right-hand table.
004209      ** The expression is only evaluated if that table is not currently
004210      ** on a LEFT JOIN NULL row.
004211      */
004212      case TK_IF_NULL_ROW: {
004213        int addrINR;
004214        u8 okConstFactor = pParse->okConstFactor;
004215        addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
004216        /* Temporarily disable factoring of constant expressions, since
004217        ** even though expressions may appear to be constant, they are not
004218        ** really constant because they originate from the right-hand side
004219        ** of a LEFT JOIN. */
004220        pParse->okConstFactor = 0;
004221        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
004222        pParse->okConstFactor = okConstFactor;
004223        sqlite3VdbeJumpHere(v, addrINR);
004224        sqlite3VdbeChangeP3(v, addrINR, inReg);
004225        break;
004226      }
004227  
004228      /*
004229      ** Form A:
004230      **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
004231      **
004232      ** Form B:
004233      **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
004234      **
004235      ** Form A is can be transformed into the equivalent form B as follows:
004236      **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
004237      **        WHEN x=eN THEN rN ELSE y END
004238      **
004239      ** X (if it exists) is in pExpr->pLeft.
004240      ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
004241      ** odd.  The Y is also optional.  If the number of elements in x.pList
004242      ** is even, then Y is omitted and the "otherwise" result is NULL.
004243      ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
004244      **
004245      ** The result of the expression is the Ri for the first matching Ei,
004246      ** or if there is no matching Ei, the ELSE term Y, or if there is
004247      ** no ELSE term, NULL.
004248      */
004249      case TK_CASE: {
004250        int endLabel;                     /* GOTO label for end of CASE stmt */
004251        int nextCase;                     /* GOTO label for next WHEN clause */
004252        int nExpr;                        /* 2x number of WHEN terms */
004253        int i;                            /* Loop counter */
004254        ExprList *pEList;                 /* List of WHEN terms */
004255        struct ExprList_item *aListelem;  /* Array of WHEN terms */
004256        Expr opCompare;                   /* The X==Ei expression */
004257        Expr *pX;                         /* The X expression */
004258        Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
004259        Expr *pDel = 0;
004260        sqlite3 *db = pParse->db;
004261  
004262        assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
004263        assert(pExpr->x.pList->nExpr > 0);
004264        pEList = pExpr->x.pList;
004265        aListelem = pEList->a;
004266        nExpr = pEList->nExpr;
004267        endLabel = sqlite3VdbeMakeLabel(pParse);
004268        if( (pX = pExpr->pLeft)!=0 ){
004269          pDel = sqlite3ExprDup(db, pX, 0);
004270          if( db->mallocFailed ){
004271            sqlite3ExprDelete(db, pDel);
004272            break;
004273          }
004274          testcase( pX->op==TK_COLUMN );
004275          exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
004276          testcase( regFree1==0 );
004277          memset(&opCompare, 0, sizeof(opCompare));
004278          opCompare.op = TK_EQ;
004279          opCompare.pLeft = pDel;
004280          pTest = &opCompare;
004281          /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
004282          ** The value in regFree1 might get SCopy-ed into the file result.
004283          ** So make sure that the regFree1 register is not reused for other
004284          ** purposes and possibly overwritten.  */
004285          regFree1 = 0;
004286        }
004287        for(i=0; i<nExpr-1; i=i+2){
004288          if( pX ){
004289            assert( pTest!=0 );
004290            opCompare.pRight = aListelem[i].pExpr;
004291          }else{
004292            pTest = aListelem[i].pExpr;
004293          }
004294          nextCase = sqlite3VdbeMakeLabel(pParse);
004295          testcase( pTest->op==TK_COLUMN );
004296          sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
004297          testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
004298          sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
004299          sqlite3VdbeGoto(v, endLabel);
004300          sqlite3VdbeResolveLabel(v, nextCase);
004301        }
004302        if( (nExpr&1)!=0 ){
004303          sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
004304        }else{
004305          sqlite3VdbeAddOp2(v, OP_Null, 0, target);
004306        }
004307        sqlite3ExprDelete(db, pDel);
004308        sqlite3VdbeResolveLabel(v, endLabel);
004309        break;
004310      }
004311  #ifndef SQLITE_OMIT_TRIGGER
004312      case TK_RAISE: {
004313        assert( pExpr->affExpr==OE_Rollback 
004314             || pExpr->affExpr==OE_Abort
004315             || pExpr->affExpr==OE_Fail
004316             || pExpr->affExpr==OE_Ignore
004317        );
004318        if( !pParse->pTriggerTab ){
004319          sqlite3ErrorMsg(pParse,
004320                         "RAISE() may only be used within a trigger-program");
004321          return 0;
004322        }
004323        if( pExpr->affExpr==OE_Abort ){
004324          sqlite3MayAbort(pParse);
004325        }
004326        assert( !ExprHasProperty(pExpr, EP_IntValue) );
004327        if( pExpr->affExpr==OE_Ignore ){
004328          sqlite3VdbeAddOp4(
004329              v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
004330          VdbeCoverage(v);
004331        }else{
004332          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
004333                                pExpr->affExpr, pExpr->u.zToken, 0, 0);
004334        }
004335  
004336        break;
004337      }
004338  #endif
004339    }
004340    sqlite3ReleaseTempReg(pParse, regFree1);
004341    sqlite3ReleaseTempReg(pParse, regFree2);
004342    return inReg;
004343  }
004344  
004345  /*
004346  ** Factor out the code of the given expression to initialization time.
004347  **
004348  ** If regDest>=0 then the result is always stored in that register and the
004349  ** result is not reusable.  If regDest<0 then this routine is free to 
004350  ** store the value whereever it wants.  The register where the expression 
004351  ** is stored is returned.  When regDest<0, two identical expressions will
004352  ** code to the same register.
004353  */
004354  int sqlite3ExprCodeAtInit(
004355    Parse *pParse,    /* Parsing context */
004356    Expr *pExpr,      /* The expression to code when the VDBE initializes */
004357    int regDest       /* Store the value in this register */
004358  ){
004359    ExprList *p;
004360    assert( ConstFactorOk(pParse) );
004361    p = pParse->pConstExpr;
004362    if( regDest<0 && p ){
004363      struct ExprList_item *pItem;
004364      int i;
004365      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
004366        if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
004367          return pItem->u.iConstExprReg;
004368        }
004369      }
004370    }
004371    pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
004372    p = sqlite3ExprListAppend(pParse, p, pExpr);
004373    if( p ){
004374       struct ExprList_item *pItem = &p->a[p->nExpr-1];
004375       pItem->reusable = regDest<0;
004376       if( regDest<0 ) regDest = ++pParse->nMem;
004377       pItem->u.iConstExprReg = regDest;
004378    }
004379    pParse->pConstExpr = p;
004380    return regDest;
004381  }
004382  
004383  /*
004384  ** Generate code to evaluate an expression and store the results
004385  ** into a register.  Return the register number where the results
004386  ** are stored.
004387  **
004388  ** If the register is a temporary register that can be deallocated,
004389  ** then write its number into *pReg.  If the result register is not
004390  ** a temporary, then set *pReg to zero.
004391  **
004392  ** If pExpr is a constant, then this routine might generate this
004393  ** code to fill the register in the initialization section of the
004394  ** VDBE program, in order to factor it out of the evaluation loop.
004395  */
004396  int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
004397    int r2;
004398    pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
004399    if( ConstFactorOk(pParse)
004400     && pExpr->op!=TK_REGISTER
004401     && sqlite3ExprIsConstantNotJoin(pExpr)
004402    ){
004403      *pReg  = 0;
004404      r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
004405    }else{
004406      int r1 = sqlite3GetTempReg(pParse);
004407      r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
004408      if( r2==r1 ){
004409        *pReg = r1;
004410      }else{
004411        sqlite3ReleaseTempReg(pParse, r1);
004412        *pReg = 0;
004413      }
004414    }
004415    return r2;
004416  }
004417  
004418  /*
004419  ** Generate code that will evaluate expression pExpr and store the
004420  ** results in register target.  The results are guaranteed to appear
004421  ** in register target.
004422  */
004423  void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
004424    int inReg;
004425  
004426    assert( target>0 && target<=pParse->nMem );
004427    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
004428    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
004429    if( inReg!=target && pParse->pVdbe ){
004430      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
004431    }
004432  }
004433  
004434  /*
004435  ** Make a transient copy of expression pExpr and then code it using
004436  ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
004437  ** except that the input expression is guaranteed to be unchanged.
004438  */
004439  void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
004440    sqlite3 *db = pParse->db;
004441    pExpr = sqlite3ExprDup(db, pExpr, 0);
004442    if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
004443    sqlite3ExprDelete(db, pExpr);
004444  }
004445  
004446  /*
004447  ** Generate code that will evaluate expression pExpr and store the
004448  ** results in register target.  The results are guaranteed to appear
004449  ** in register target.  If the expression is constant, then this routine
004450  ** might choose to code the expression at initialization time.
004451  */
004452  void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
004453    if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
004454      sqlite3ExprCodeAtInit(pParse, pExpr, target);
004455    }else{
004456      sqlite3ExprCode(pParse, pExpr, target);
004457    }
004458  }
004459  
004460  /*
004461  ** Generate code that pushes the value of every element of the given
004462  ** expression list into a sequence of registers beginning at target.
004463  **
004464  ** Return the number of elements evaluated.  The number returned will
004465  ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
004466  ** is defined.
004467  **
004468  ** The SQLITE_ECEL_DUP flag prevents the arguments from being
004469  ** filled using OP_SCopy.  OP_Copy must be used instead.
004470  **
004471  ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
004472  ** factored out into initialization code.
004473  **
004474  ** The SQLITE_ECEL_REF flag means that expressions in the list with
004475  ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
004476  ** in registers at srcReg, and so the value can be copied from there.
004477  ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
004478  ** are simply omitted rather than being copied from srcReg.
004479  */
004480  int sqlite3ExprCodeExprList(
004481    Parse *pParse,     /* Parsing context */
004482    ExprList *pList,   /* The expression list to be coded */
004483    int target,        /* Where to write results */
004484    int srcReg,        /* Source registers if SQLITE_ECEL_REF */
004485    u8 flags           /* SQLITE_ECEL_* flags */
004486  ){
004487    struct ExprList_item *pItem;
004488    int i, j, n;
004489    u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
004490    Vdbe *v = pParse->pVdbe;
004491    assert( pList!=0 );
004492    assert( target>0 );
004493    assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
004494    n = pList->nExpr;
004495    if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
004496    for(pItem=pList->a, i=0; i<n; i++, pItem++){
004497      Expr *pExpr = pItem->pExpr;
004498  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
004499      if( pItem->bSorterRef ){
004500        i--;
004501        n--;
004502      }else
004503  #endif
004504      if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
004505        if( flags & SQLITE_ECEL_OMITREF ){
004506          i--;
004507          n--;
004508        }else{
004509          sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
004510        }
004511      }else if( (flags & SQLITE_ECEL_FACTOR)!=0
004512             && sqlite3ExprIsConstantNotJoin(pExpr)
004513      ){
004514        sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
004515      }else{
004516        int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
004517        if( inReg!=target+i ){
004518          VdbeOp *pOp;
004519          if( copyOp==OP_Copy
004520           && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
004521           && pOp->p1+pOp->p3+1==inReg
004522           && pOp->p2+pOp->p3+1==target+i
004523          ){
004524            pOp->p3++;
004525          }else{
004526            sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
004527          }
004528        }
004529      }
004530    }
004531    return n;
004532  }
004533  
004534  /*
004535  ** Generate code for a BETWEEN operator.
004536  **
004537  **    x BETWEEN y AND z
004538  **
004539  ** The above is equivalent to 
004540  **
004541  **    x>=y AND x<=z
004542  **
004543  ** Code it as such, taking care to do the common subexpression
004544  ** elimination of x.
004545  **
004546  ** The xJumpIf parameter determines details:
004547  **
004548  **    NULL:                   Store the boolean result in reg[dest]
004549  **    sqlite3ExprIfTrue:      Jump to dest if true
004550  **    sqlite3ExprIfFalse:     Jump to dest if false
004551  **
004552  ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
004553  */
004554  static void exprCodeBetween(
004555    Parse *pParse,    /* Parsing and code generating context */
004556    Expr *pExpr,      /* The BETWEEN expression */
004557    int dest,         /* Jump destination or storage location */
004558    void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
004559    int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
004560  ){
004561    Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
004562    Expr compLeft;    /* The  x>=y  term */
004563    Expr compRight;   /* The  x<=z  term */
004564    int regFree1 = 0; /* Temporary use register */
004565    Expr *pDel = 0;
004566    sqlite3 *db = pParse->db;
004567  
004568    memset(&compLeft, 0, sizeof(Expr));
004569    memset(&compRight, 0, sizeof(Expr));
004570    memset(&exprAnd, 0, sizeof(Expr));
004571  
004572    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
004573    pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
004574    if( db->mallocFailed==0 ){
004575      exprAnd.op = TK_AND;
004576      exprAnd.pLeft = &compLeft;
004577      exprAnd.pRight = &compRight;
004578      compLeft.op = TK_GE;
004579      compLeft.pLeft = pDel;
004580      compLeft.pRight = pExpr->x.pList->a[0].pExpr;
004581      compRight.op = TK_LE;
004582      compRight.pLeft = pDel;
004583      compRight.pRight = pExpr->x.pList->a[1].pExpr;
004584      exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
004585      if( xJump ){
004586        xJump(pParse, &exprAnd, dest, jumpIfNull);
004587      }else{
004588        /* Mark the expression is being from the ON or USING clause of a join
004589        ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
004590        ** it into the Parse.pConstExpr list.  We should use a new bit for this,
004591        ** for clarity, but we are out of bits in the Expr.flags field so we
004592        ** have to reuse the EP_FromJoin bit.  Bummer. */
004593        pDel->flags |= EP_FromJoin;
004594        sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
004595      }
004596      sqlite3ReleaseTempReg(pParse, regFree1);
004597    }
004598    sqlite3ExprDelete(db, pDel);
004599  
004600    /* Ensure adequate test coverage */
004601    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
004602    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
004603    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
004604    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
004605    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
004606    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
004607    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
004608    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
004609    testcase( xJump==0 );
004610  }
004611  
004612  /*
004613  ** Generate code for a boolean expression such that a jump is made
004614  ** to the label "dest" if the expression is true but execution
004615  ** continues straight thru if the expression is false.
004616  **
004617  ** If the expression evaluates to NULL (neither true nor false), then
004618  ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
004619  **
004620  ** This code depends on the fact that certain token values (ex: TK_EQ)
004621  ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
004622  ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
004623  ** the make process cause these values to align.  Assert()s in the code
004624  ** below verify that the numbers are aligned correctly.
004625  */
004626  void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
004627    Vdbe *v = pParse->pVdbe;
004628    int op = 0;
004629    int regFree1 = 0;
004630    int regFree2 = 0;
004631    int r1, r2;
004632  
004633    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
004634    if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
004635    if( NEVER(pExpr==0) ) return;  /* No way this can happen */
004636    op = pExpr->op;
004637    switch( op ){
004638      case TK_AND:
004639      case TK_OR: {
004640        Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
004641        if( pAlt!=pExpr ){
004642          sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
004643        }else if( op==TK_AND ){
004644          int d2 = sqlite3VdbeMakeLabel(pParse);
004645          testcase( jumpIfNull==0 );
004646          sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
004647                             jumpIfNull^SQLITE_JUMPIFNULL);
004648          sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
004649          sqlite3VdbeResolveLabel(v, d2);
004650        }else{
004651          testcase( jumpIfNull==0 );
004652          sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
004653          sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
004654        }
004655        break;
004656      }
004657      case TK_NOT: {
004658        testcase( jumpIfNull==0 );
004659        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
004660        break;
004661      }
004662      case TK_TRUTH: {
004663        int isNot;      /* IS NOT TRUE or IS NOT FALSE */
004664        int isTrue;     /* IS TRUE or IS NOT TRUE */
004665        testcase( jumpIfNull==0 );
004666        isNot = pExpr->op2==TK_ISNOT;
004667        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
004668        testcase( isTrue && isNot );
004669        testcase( !isTrue && isNot );
004670        if( isTrue ^ isNot ){
004671          sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
004672                            isNot ? SQLITE_JUMPIFNULL : 0);
004673        }else{
004674          sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
004675                             isNot ? SQLITE_JUMPIFNULL : 0);
004676        }
004677        break;
004678      }
004679      case TK_IS:
004680      case TK_ISNOT:
004681        testcase( op==TK_IS );
004682        testcase( op==TK_ISNOT );
004683        op = (op==TK_IS) ? TK_EQ : TK_NE;
004684        jumpIfNull = SQLITE_NULLEQ;
004685        /* Fall thru */
004686      case TK_LT:
004687      case TK_LE:
004688      case TK_GT:
004689      case TK_GE:
004690      case TK_NE:
004691      case TK_EQ: {
004692        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
004693        testcase( jumpIfNull==0 );
004694        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
004695        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
004696        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
004697                    r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
004698        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
004699        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
004700        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
004701        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
004702        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
004703        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
004704        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
004705        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
004706        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
004707        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
004708        testcase( regFree1==0 );
004709        testcase( regFree2==0 );
004710        break;
004711      }
004712      case TK_ISNULL:
004713      case TK_NOTNULL: {
004714        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
004715        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
004716        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
004717        sqlite3VdbeAddOp2(v, op, r1, dest);
004718        VdbeCoverageIf(v, op==TK_ISNULL);
004719        VdbeCoverageIf(v, op==TK_NOTNULL);
004720        testcase( regFree1==0 );
004721        break;
004722      }
004723      case TK_BETWEEN: {
004724        testcase( jumpIfNull==0 );
004725        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
004726        break;
004727      }
004728  #ifndef SQLITE_OMIT_SUBQUERY
004729      case TK_IN: {
004730        int destIfFalse = sqlite3VdbeMakeLabel(pParse);
004731        int destIfNull = jumpIfNull ? dest : destIfFalse;
004732        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
004733        sqlite3VdbeGoto(v, dest);
004734        sqlite3VdbeResolveLabel(v, destIfFalse);
004735        break;
004736      }
004737  #endif
004738      default: {
004739      default_expr:
004740        if( ExprAlwaysTrue(pExpr) ){
004741          sqlite3VdbeGoto(v, dest);
004742        }else if( ExprAlwaysFalse(pExpr) ){
004743          /* No-op */
004744        }else{
004745          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
004746          sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
004747          VdbeCoverage(v);
004748          testcase( regFree1==0 );
004749          testcase( jumpIfNull==0 );
004750        }
004751        break;
004752      }
004753    }
004754    sqlite3ReleaseTempReg(pParse, regFree1);
004755    sqlite3ReleaseTempReg(pParse, regFree2);  
004756  }
004757  
004758  /*
004759  ** Generate code for a boolean expression such that a jump is made
004760  ** to the label "dest" if the expression is false but execution
004761  ** continues straight thru if the expression is true.
004762  **
004763  ** If the expression evaluates to NULL (neither true nor false) then
004764  ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
004765  ** is 0.
004766  */
004767  void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
004768    Vdbe *v = pParse->pVdbe;
004769    int op = 0;
004770    int regFree1 = 0;
004771    int regFree2 = 0;
004772    int r1, r2;
004773  
004774    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
004775    if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
004776    if( pExpr==0 )    return;
004777  
004778    /* The value of pExpr->op and op are related as follows:
004779    **
004780    **       pExpr->op            op
004781    **       ---------          ----------
004782    **       TK_ISNULL          OP_NotNull
004783    **       TK_NOTNULL         OP_IsNull
004784    **       TK_NE              OP_Eq
004785    **       TK_EQ              OP_Ne
004786    **       TK_GT              OP_Le
004787    **       TK_LE              OP_Gt
004788    **       TK_GE              OP_Lt
004789    **       TK_LT              OP_Ge
004790    **
004791    ** For other values of pExpr->op, op is undefined and unused.
004792    ** The value of TK_ and OP_ constants are arranged such that we
004793    ** can compute the mapping above using the following expression.
004794    ** Assert()s verify that the computation is correct.
004795    */
004796    op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
004797  
004798    /* Verify correct alignment of TK_ and OP_ constants
004799    */
004800    assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
004801    assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
004802    assert( pExpr->op!=TK_NE || op==OP_Eq );
004803    assert( pExpr->op!=TK_EQ || op==OP_Ne );
004804    assert( pExpr->op!=TK_LT || op==OP_Ge );
004805    assert( pExpr->op!=TK_LE || op==OP_Gt );
004806    assert( pExpr->op!=TK_GT || op==OP_Le );
004807    assert( pExpr->op!=TK_GE || op==OP_Lt );
004808  
004809    switch( pExpr->op ){
004810      case TK_AND:
004811      case TK_OR: {
004812        Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
004813        if( pAlt!=pExpr ){
004814          sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
004815        }else if( pExpr->op==TK_AND ){
004816          testcase( jumpIfNull==0 );
004817          sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
004818          sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
004819        }else{
004820          int d2 = sqlite3VdbeMakeLabel(pParse);
004821          testcase( jumpIfNull==0 );
004822          sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
004823                            jumpIfNull^SQLITE_JUMPIFNULL);
004824          sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
004825          sqlite3VdbeResolveLabel(v, d2);
004826        }
004827        break;
004828      }
004829      case TK_NOT: {
004830        testcase( jumpIfNull==0 );
004831        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
004832        break;
004833      }
004834      case TK_TRUTH: {
004835        int isNot;   /* IS NOT TRUE or IS NOT FALSE */
004836        int isTrue;  /* IS TRUE or IS NOT TRUE */
004837        testcase( jumpIfNull==0 );
004838        isNot = pExpr->op2==TK_ISNOT;
004839        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
004840        testcase( isTrue && isNot );
004841        testcase( !isTrue && isNot );
004842        if( isTrue ^ isNot ){
004843          /* IS TRUE and IS NOT FALSE */
004844          sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
004845                             isNot ? 0 : SQLITE_JUMPIFNULL);
004846  
004847        }else{
004848          /* IS FALSE and IS NOT TRUE */
004849          sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
004850                            isNot ? 0 : SQLITE_JUMPIFNULL);
004851        }
004852        break;
004853      }
004854      case TK_IS:
004855      case TK_ISNOT:
004856        testcase( pExpr->op==TK_IS );
004857        testcase( pExpr->op==TK_ISNOT );
004858        op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
004859        jumpIfNull = SQLITE_NULLEQ;
004860        /* Fall thru */
004861      case TK_LT:
004862      case TK_LE:
004863      case TK_GT:
004864      case TK_GE:
004865      case TK_NE:
004866      case TK_EQ: {
004867        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
004868        testcase( jumpIfNull==0 );
004869        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
004870        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
004871        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
004872                    r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
004873        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
004874        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
004875        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
004876        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
004877        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
004878        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
004879        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
004880        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
004881        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
004882        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
004883        testcase( regFree1==0 );
004884        testcase( regFree2==0 );
004885        break;
004886      }
004887      case TK_ISNULL:
004888      case TK_NOTNULL: {
004889        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
004890        sqlite3VdbeAddOp2(v, op, r1, dest);
004891        testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
004892        testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
004893        testcase( regFree1==0 );
004894        break;
004895      }
004896      case TK_BETWEEN: {
004897        testcase( jumpIfNull==0 );
004898        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
004899        break;
004900      }
004901  #ifndef SQLITE_OMIT_SUBQUERY
004902      case TK_IN: {
004903        if( jumpIfNull ){
004904          sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
004905        }else{
004906          int destIfNull = sqlite3VdbeMakeLabel(pParse);
004907          sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
004908          sqlite3VdbeResolveLabel(v, destIfNull);
004909        }
004910        break;
004911      }
004912  #endif
004913      default: {
004914      default_expr: 
004915        if( ExprAlwaysFalse(pExpr) ){
004916          sqlite3VdbeGoto(v, dest);
004917        }else if( ExprAlwaysTrue(pExpr) ){
004918          /* no-op */
004919        }else{
004920          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
004921          sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
004922          VdbeCoverage(v);
004923          testcase( regFree1==0 );
004924          testcase( jumpIfNull==0 );
004925        }
004926        break;
004927      }
004928    }
004929    sqlite3ReleaseTempReg(pParse, regFree1);
004930    sqlite3ReleaseTempReg(pParse, regFree2);
004931  }
004932  
004933  /*
004934  ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
004935  ** code generation, and that copy is deleted after code generation. This
004936  ** ensures that the original pExpr is unchanged.
004937  */
004938  void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
004939    sqlite3 *db = pParse->db;
004940    Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
004941    if( db->mallocFailed==0 ){
004942      sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
004943    }
004944    sqlite3ExprDelete(db, pCopy);
004945  }
004946  
004947  /*
004948  ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
004949  ** type of expression.
004950  **
004951  ** If pExpr is a simple SQL value - an integer, real, string, blob
004952  ** or NULL value - then the VDBE currently being prepared is configured
004953  ** to re-prepare each time a new value is bound to variable pVar.
004954  **
004955  ** Additionally, if pExpr is a simple SQL value and the value is the
004956  ** same as that currently bound to variable pVar, non-zero is returned.
004957  ** Otherwise, if the values are not the same or if pExpr is not a simple
004958  ** SQL value, zero is returned.
004959  */
004960  static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
004961    int res = 0;
004962    int iVar;
004963    sqlite3_value *pL, *pR = 0;
004964    
004965    sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
004966    if( pR ){
004967      iVar = pVar->iColumn;
004968      sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
004969      pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
004970      if( pL ){
004971        if( sqlite3_value_type(pL)==SQLITE_TEXT ){
004972          sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
004973        }
004974        res =  0==sqlite3MemCompare(pL, pR, 0);
004975      }
004976      sqlite3ValueFree(pR);
004977      sqlite3ValueFree(pL);
004978    }
004979  
004980    return res;
004981  }
004982  
004983  /*
004984  ** Do a deep comparison of two expression trees.  Return 0 if the two
004985  ** expressions are completely identical.  Return 1 if they differ only
004986  ** by a COLLATE operator at the top level.  Return 2 if there are differences
004987  ** other than the top-level COLLATE operator.
004988  **
004989  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
004990  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
004991  **
004992  ** The pA side might be using TK_REGISTER.  If that is the case and pB is
004993  ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
004994  **
004995  ** Sometimes this routine will return 2 even if the two expressions
004996  ** really are equivalent.  If we cannot prove that the expressions are
004997  ** identical, we return 2 just to be safe.  So if this routine
004998  ** returns 2, then you do not really know for certain if the two
004999  ** expressions are the same.  But if you get a 0 or 1 return, then you
005000  ** can be sure the expressions are the same.  In the places where
005001  ** this routine is used, it does not hurt to get an extra 2 - that
005002  ** just might result in some slightly slower code.  But returning
005003  ** an incorrect 0 or 1 could lead to a malfunction.
005004  **
005005  ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
005006  ** pParse->pReprepare can be matched against literals in pB.  The 
005007  ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
005008  ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 
005009  ** Argument pParse should normally be NULL. If it is not NULL and pA or
005010  ** pB causes a return value of 2.
005011  */
005012  int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
005013    u32 combinedFlags;
005014    if( pA==0 || pB==0 ){
005015      return pB==pA ? 0 : 2;
005016    }
005017    if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
005018      return 0;
005019    }
005020    combinedFlags = pA->flags | pB->flags;
005021    if( combinedFlags & EP_IntValue ){
005022      if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
005023        return 0;
005024      }
005025      return 2;
005026    }
005027    if( pA->op!=pB->op || pA->op==TK_RAISE ){
005028      if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
005029        return 1;
005030      }
005031      if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
005032        return 1;
005033      }
005034      return 2;
005035    }
005036    if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
005037      if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
005038        if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
005039  #ifndef SQLITE_OMIT_WINDOWFUNC
005040        assert( pA->op==pB->op );
005041        if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
005042          return 2;
005043        }
005044        if( ExprHasProperty(pA,EP_WinFunc) ){
005045          if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
005046            return 2;
005047          }
005048        }
005049  #endif
005050      }else if( pA->op==TK_NULL ){
005051        return 0;
005052      }else if( pA->op==TK_COLLATE ){
005053        if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
005054      }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
005055        return 2;
005056      }
005057    }
005058    if( (pA->flags & (EP_Distinct|EP_Commuted))
005059       != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
005060    if( (combinedFlags & EP_TokenOnly)==0 ){
005061      if( combinedFlags & EP_xIsSelect ) return 2;
005062      if( (combinedFlags & EP_FixedCol)==0
005063       && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
005064      if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
005065      if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
005066      if( pA->op!=TK_STRING
005067       && pA->op!=TK_TRUEFALSE
005068       && (combinedFlags & EP_Reduced)==0
005069      ){
005070        if( pA->iColumn!=pB->iColumn ) return 2;
005071        if( pA->op2!=pB->op2 ){
005072          if( pA->op==TK_TRUTH ) return 2;
005073          if( pA->op==TK_FUNCTION && iTab<0 ){
005074            /* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') ));
005075            **     INSERT INTO t1(a) VALUES(julianday('now')+10);
005076            ** Without this test, sqlite3ExprCodeAtInit() will run on the
005077            ** the julianday() of INSERT first, and remember that expression.
005078            ** Then sqlite3ExprCodeInit() will see the julianday() in the CHECK
005079            ** constraint as redundant, reusing the one from the INSERT, even
005080            ** though the julianday() in INSERT lacks the critical NC_IsCheck
005081            ** flag.  See ticket [830277d9db6c3ba1] (2019-10-30)
005082            */
005083            return 2;
005084          }
005085        }
005086        if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
005087          return 2;
005088        }
005089      }
005090    }
005091    return 0;
005092  }
005093  
005094  /*
005095  ** Compare two ExprList objects.  Return 0 if they are identical and 
005096  ** non-zero if they differ in any way.
005097  **
005098  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
005099  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
005100  **
005101  ** This routine might return non-zero for equivalent ExprLists.  The
005102  ** only consequence will be disabled optimizations.  But this routine
005103  ** must never return 0 if the two ExprList objects are different, or
005104  ** a malfunction will result.
005105  **
005106  ** Two NULL pointers are considered to be the same.  But a NULL pointer
005107  ** always differs from a non-NULL pointer.
005108  */
005109  int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
005110    int i;
005111    if( pA==0 && pB==0 ) return 0;
005112    if( pA==0 || pB==0 ) return 1;
005113    if( pA->nExpr!=pB->nExpr ) return 1;
005114    for(i=0; i<pA->nExpr; i++){
005115      Expr *pExprA = pA->a[i].pExpr;
005116      Expr *pExprB = pB->a[i].pExpr;
005117      if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
005118      if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
005119    }
005120    return 0;
005121  }
005122  
005123  /*
005124  ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
005125  ** are ignored.
005126  */
005127  int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
005128    return sqlite3ExprCompare(0,
005129               sqlite3ExprSkipCollateAndLikely(pA),
005130               sqlite3ExprSkipCollateAndLikely(pB),
005131               iTab);
005132  }
005133  
005134  /*
005135  ** Return non-zero if Expr p can only be true if pNN is not NULL.
005136  **
005137  ** Or if seenNot is true, return non-zero if Expr p can only be
005138  ** non-NULL if pNN is not NULL
005139  */
005140  static int exprImpliesNotNull(
005141    Parse *pParse,      /* Parsing context */
005142    Expr *p,            /* The expression to be checked */
005143    Expr *pNN,          /* The expression that is NOT NULL */
005144    int iTab,           /* Table being evaluated */
005145    int seenNot         /* Return true only if p can be any non-NULL value */
005146  ){
005147    assert( p );
005148    assert( pNN );
005149    if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
005150      return pNN->op!=TK_NULL;
005151    }
005152    switch( p->op ){
005153      case TK_IN: {
005154        if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
005155        assert( ExprHasProperty(p,EP_xIsSelect)
005156             || (p->x.pList!=0 && p->x.pList->nExpr>0) );
005157        return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
005158      }
005159      case TK_BETWEEN: {
005160        ExprList *pList = p->x.pList;
005161        assert( pList!=0 );
005162        assert( pList->nExpr==2 );
005163        if( seenNot ) return 0;
005164        if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
005165         || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
005166        ){
005167          return 1;
005168        }
005169        return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
005170      }
005171      case TK_EQ:
005172      case TK_NE:
005173      case TK_LT:
005174      case TK_LE:
005175      case TK_GT:
005176      case TK_GE:
005177      case TK_PLUS:
005178      case TK_MINUS:
005179      case TK_BITOR:
005180      case TK_LSHIFT:
005181      case TK_RSHIFT: 
005182      case TK_CONCAT: 
005183        seenNot = 1;
005184        /* Fall thru */
005185      case TK_STAR:
005186      case TK_REM:
005187      case TK_BITAND:
005188      case TK_SLASH: {
005189        if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
005190        /* Fall thru into the next case */
005191      }
005192      case TK_SPAN:
005193      case TK_COLLATE:
005194      case TK_UPLUS:
005195      case TK_UMINUS: {
005196        return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
005197      }
005198      case TK_TRUTH: {
005199        if( seenNot ) return 0;
005200        if( p->op2!=TK_IS ) return 0;
005201        return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
005202      }
005203      case TK_BITNOT:
005204      case TK_NOT: {
005205        return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
005206      }
005207    }
005208    return 0;
005209  }
005210  
005211  /*
005212  ** Return true if we can prove the pE2 will always be true if pE1 is
005213  ** true.  Return false if we cannot complete the proof or if pE2 might
005214  ** be false.  Examples:
005215  **
005216  **     pE1: x==5       pE2: x==5             Result: true
005217  **     pE1: x>0        pE2: x==5             Result: false
005218  **     pE1: x=21       pE2: x=21 OR y=43     Result: true
005219  **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
005220  **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
005221  **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
005222  **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
005223  **
005224  ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
005225  ** Expr.iTable<0 then assume a table number given by iTab.
005226  **
005227  ** If pParse is not NULL, then the values of bound variables in pE1 are 
005228  ** compared against literal values in pE2 and pParse->pVdbe->expmask is
005229  ** modified to record which bound variables are referenced.  If pParse 
005230  ** is NULL, then false will be returned if pE1 contains any bound variables.
005231  **
005232  ** When in doubt, return false.  Returning true might give a performance
005233  ** improvement.  Returning false might cause a performance reduction, but
005234  ** it will always give the correct answer and is hence always safe.
005235  */
005236  int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
005237    if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
005238      return 1;
005239    }
005240    if( pE2->op==TK_OR
005241     && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
005242               || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
005243    ){
005244      return 1;
005245    }
005246    if( pE2->op==TK_NOTNULL
005247     && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
005248    ){
005249      return 1;
005250    }
005251    return 0;
005252  }
005253  
005254  /*
005255  ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
005256  ** If the expression node requires that the table at pWalker->iCur
005257  ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
005258  **
005259  ** This routine controls an optimization.  False positives (setting
005260  ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
005261  ** (never setting pWalker->eCode) is a harmless missed optimization.
005262  */
005263  static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
005264    testcase( pExpr->op==TK_AGG_COLUMN );
005265    testcase( pExpr->op==TK_AGG_FUNCTION );
005266    if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
005267    switch( pExpr->op ){
005268      case TK_ISNOT:
005269      case TK_ISNULL:
005270      case TK_NOTNULL:
005271      case TK_IS:
005272      case TK_OR:
005273      case TK_VECTOR:
005274      case TK_CASE:
005275      case TK_IN:
005276      case TK_FUNCTION:
005277      case TK_TRUTH:
005278        testcase( pExpr->op==TK_ISNOT );
005279        testcase( pExpr->op==TK_ISNULL );
005280        testcase( pExpr->op==TK_NOTNULL );
005281        testcase( pExpr->op==TK_IS );
005282        testcase( pExpr->op==TK_OR );
005283        testcase( pExpr->op==TK_VECTOR );
005284        testcase( pExpr->op==TK_CASE );
005285        testcase( pExpr->op==TK_IN );
005286        testcase( pExpr->op==TK_FUNCTION );
005287        testcase( pExpr->op==TK_TRUTH );
005288        return WRC_Prune;
005289      case TK_COLUMN:
005290        if( pWalker->u.iCur==pExpr->iTable ){
005291          pWalker->eCode = 1;
005292          return WRC_Abort;
005293        }
005294        return WRC_Prune;
005295  
005296      case TK_AND:
005297        assert( pWalker->eCode==0 );
005298        sqlite3WalkExpr(pWalker, pExpr->pLeft);
005299        if( pWalker->eCode ){
005300          pWalker->eCode = 0;
005301          sqlite3WalkExpr(pWalker, pExpr->pRight);
005302        }
005303        return WRC_Prune;
005304  
005305      case TK_BETWEEN:
005306        if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
005307          assert( pWalker->eCode );
005308          return WRC_Abort;
005309        }
005310        return WRC_Prune;
005311  
005312      /* Virtual tables are allowed to use constraints like x=NULL.  So
005313      ** a term of the form x=y does not prove that y is not null if x
005314      ** is the column of a virtual table */
005315      case TK_EQ:
005316      case TK_NE:
005317      case TK_LT:
005318      case TK_LE:
005319      case TK_GT:
005320      case TK_GE:
005321        testcase( pExpr->op==TK_EQ );
005322        testcase( pExpr->op==TK_NE );
005323        testcase( pExpr->op==TK_LT );
005324        testcase( pExpr->op==TK_LE );
005325        testcase( pExpr->op==TK_GT );
005326        testcase( pExpr->op==TK_GE );
005327        if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
005328         || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
005329        ){
005330         return WRC_Prune;
005331        }
005332  
005333      default:
005334        return WRC_Continue;
005335    }
005336  }
005337  
005338  /*
005339  ** Return true (non-zero) if expression p can only be true if at least
005340  ** one column of table iTab is non-null.  In other words, return true
005341  ** if expression p will always be NULL or false if every column of iTab
005342  ** is NULL.
005343  **
005344  ** False negatives are acceptable.  In other words, it is ok to return
005345  ** zero even if expression p will never be true of every column of iTab
005346  ** is NULL.  A false negative is merely a missed optimization opportunity.
005347  **
005348  ** False positives are not allowed, however.  A false positive may result
005349  ** in an incorrect answer.
005350  **
005351  ** Terms of p that are marked with EP_FromJoin (and hence that come from
005352  ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
005353  **
005354  ** This routine is used to check if a LEFT JOIN can be converted into
005355  ** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
005356  ** clause requires that some column of the right table of the LEFT JOIN
005357  ** be non-NULL, then the LEFT JOIN can be safely converted into an
005358  ** ordinary join.
005359  */
005360  int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
005361    Walker w;
005362    p = sqlite3ExprSkipCollateAndLikely(p);
005363    if( p==0 ) return 0;
005364    if( p->op==TK_NOTNULL ){
005365      p = p->pLeft;
005366    }else{
005367      while( p->op==TK_AND ){
005368        if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
005369        p = p->pRight;
005370      }
005371    }
005372    w.xExprCallback = impliesNotNullRow;
005373    w.xSelectCallback = 0;
005374    w.xSelectCallback2 = 0;
005375    w.eCode = 0;
005376    w.u.iCur = iTab;
005377    sqlite3WalkExpr(&w, p);
005378    return w.eCode;
005379  }
005380  
005381  /*
005382  ** An instance of the following structure is used by the tree walker
005383  ** to determine if an expression can be evaluated by reference to the
005384  ** index only, without having to do a search for the corresponding
005385  ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
005386  ** is the cursor for the table.
005387  */
005388  struct IdxCover {
005389    Index *pIdx;     /* The index to be tested for coverage */
005390    int iCur;        /* Cursor number for the table corresponding to the index */
005391  };
005392  
005393  /*
005394  ** Check to see if there are references to columns in table 
005395  ** pWalker->u.pIdxCover->iCur can be satisfied using the index
005396  ** pWalker->u.pIdxCover->pIdx.
005397  */
005398  static int exprIdxCover(Walker *pWalker, Expr *pExpr){
005399    if( pExpr->op==TK_COLUMN
005400     && pExpr->iTable==pWalker->u.pIdxCover->iCur
005401     && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
005402    ){
005403      pWalker->eCode = 1;
005404      return WRC_Abort;
005405    }
005406    return WRC_Continue;
005407  }
005408  
005409  /*
005410  ** Determine if an index pIdx on table with cursor iCur contains will
005411  ** the expression pExpr.  Return true if the index does cover the
005412  ** expression and false if the pExpr expression references table columns
005413  ** that are not found in the index pIdx.
005414  **
005415  ** An index covering an expression means that the expression can be
005416  ** evaluated using only the index and without having to lookup the
005417  ** corresponding table entry.
005418  */
005419  int sqlite3ExprCoveredByIndex(
005420    Expr *pExpr,        /* The index to be tested */
005421    int iCur,           /* The cursor number for the corresponding table */
005422    Index *pIdx         /* The index that might be used for coverage */
005423  ){
005424    Walker w;
005425    struct IdxCover xcov;
005426    memset(&w, 0, sizeof(w));
005427    xcov.iCur = iCur;
005428    xcov.pIdx = pIdx;
005429    w.xExprCallback = exprIdxCover;
005430    w.u.pIdxCover = &xcov;
005431    sqlite3WalkExpr(&w, pExpr);
005432    return !w.eCode;
005433  }
005434  
005435  
005436  /*
005437  ** An instance of the following structure is used by the tree walker
005438  ** to count references to table columns in the arguments of an 
005439  ** aggregate function, in order to implement the
005440  ** sqlite3FunctionThisSrc() routine.
005441  */
005442  struct SrcCount {
005443    SrcList *pSrc;   /* One particular FROM clause in a nested query */
005444    int nThis;       /* Number of references to columns in pSrcList */
005445    int nOther;      /* Number of references to columns in other FROM clauses */
005446  };
005447  
005448  /*
005449  ** Count the number of references to columns.
005450  */
005451  static int exprSrcCount(Walker *pWalker, Expr *pExpr){
005452    /* There was once a NEVER() on the second term on the grounds that
005453    ** sqlite3FunctionUsesThisSrc() was always called before 
005454    ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet 
005455    ** been converted into TK_AGG_COLUMN. But this is no longer true due
005456    ** to window functions - sqlite3WindowRewrite() may now indirectly call
005457    ** FunctionUsesThisSrc() when creating a new sub-select. */
005458    if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
005459      int i;
005460      struct SrcCount *p = pWalker->u.pSrcCount;
005461      SrcList *pSrc = p->pSrc;
005462      int nSrc = pSrc ? pSrc->nSrc : 0;
005463      for(i=0; i<nSrc; i++){
005464        if( pExpr->iTable==pSrc->a[i].iCursor ) break;
005465      }
005466      if( i<nSrc ){
005467        p->nThis++;
005468      }else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
005469        /* In a well-formed parse tree (no name resolution errors),
005470        ** TK_COLUMN nodes with smaller Expr.iTable values are in an
005471        ** outer context.  Those are the only ones to count as "other" */
005472        p->nOther++;
005473      }
005474    }
005475    return WRC_Continue;
005476  }
005477  
005478  /*
005479  ** Determine if any of the arguments to the pExpr Function reference
005480  ** pSrcList.  Return true if they do.  Also return true if the function
005481  ** has no arguments or has only constant arguments.  Return false if pExpr
005482  ** references columns but not columns of tables found in pSrcList.
005483  */
005484  int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
005485    Walker w;
005486    struct SrcCount cnt;
005487    assert( pExpr->op==TK_AGG_FUNCTION );
005488    memset(&w, 0, sizeof(w));
005489    w.xExprCallback = exprSrcCount;
005490    w.xSelectCallback = sqlite3SelectWalkNoop;
005491    w.u.pSrcCount = &cnt;
005492    cnt.pSrc = pSrcList;
005493    cnt.nThis = 0;
005494    cnt.nOther = 0;
005495    sqlite3WalkExprList(&w, pExpr->x.pList);
005496  #ifndef SQLITE_OMIT_WINDOWFUNC
005497    if( ExprHasProperty(pExpr, EP_WinFunc) ){
005498      sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
005499    }
005500  #endif
005501    return cnt.nThis>0 || cnt.nOther==0;
005502  }
005503  
005504  /*
005505  ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
005506  ** the new element.  Return a negative number if malloc fails.
005507  */
005508  static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
005509    int i;
005510    pInfo->aCol = sqlite3ArrayAllocate(
005511         db,
005512         pInfo->aCol,
005513         sizeof(pInfo->aCol[0]),
005514         &pInfo->nColumn,
005515         &i
005516    );
005517    return i;
005518  }    
005519  
005520  /*
005521  ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
005522  ** the new element.  Return a negative number if malloc fails.
005523  */
005524  static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
005525    int i;
005526    pInfo->aFunc = sqlite3ArrayAllocate(
005527         db, 
005528         pInfo->aFunc,
005529         sizeof(pInfo->aFunc[0]),
005530         &pInfo->nFunc,
005531         &i
005532    );
005533    return i;
005534  }    
005535  
005536  /*
005537  ** This is the xExprCallback for a tree walker.  It is used to
005538  ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
005539  ** for additional information.
005540  */
005541  static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
005542    int i;
005543    NameContext *pNC = pWalker->u.pNC;
005544    Parse *pParse = pNC->pParse;
005545    SrcList *pSrcList = pNC->pSrcList;
005546    AggInfo *pAggInfo = pNC->uNC.pAggInfo;
005547  
005548    assert( pNC->ncFlags & NC_UAggInfo );
005549    switch( pExpr->op ){
005550      case TK_AGG_COLUMN:
005551      case TK_COLUMN: {
005552        testcase( pExpr->op==TK_AGG_COLUMN );
005553        testcase( pExpr->op==TK_COLUMN );
005554        /* Check to see if the column is in one of the tables in the FROM
005555        ** clause of the aggregate query */
005556        if( ALWAYS(pSrcList!=0) ){
005557          struct SrcList_item *pItem = pSrcList->a;
005558          for(i=0; i<pSrcList->nSrc; i++, pItem++){
005559            struct AggInfo_col *pCol;
005560            assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
005561            if( pExpr->iTable==pItem->iCursor ){
005562              /* If we reach this point, it means that pExpr refers to a table
005563              ** that is in the FROM clause of the aggregate query.  
005564              **
005565              ** Make an entry for the column in pAggInfo->aCol[] if there
005566              ** is not an entry there already.
005567              */
005568              int k;
005569              pCol = pAggInfo->aCol;
005570              for(k=0; k<pAggInfo->nColumn; k++, pCol++){
005571                if( pCol->iTable==pExpr->iTable &&
005572                    pCol->iColumn==pExpr->iColumn ){
005573                  break;
005574                }
005575              }
005576              if( (k>=pAggInfo->nColumn)
005577               && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
005578              ){
005579                pCol = &pAggInfo->aCol[k];
005580                pCol->pTab = pExpr->y.pTab;
005581                pCol->iTable = pExpr->iTable;
005582                pCol->iColumn = pExpr->iColumn;
005583                pCol->iMem = ++pParse->nMem;
005584                pCol->iSorterColumn = -1;
005585                pCol->pExpr = pExpr;
005586                if( pAggInfo->pGroupBy ){
005587                  int j, n;
005588                  ExprList *pGB = pAggInfo->pGroupBy;
005589                  struct ExprList_item *pTerm = pGB->a;
005590                  n = pGB->nExpr;
005591                  for(j=0; j<n; j++, pTerm++){
005592                    Expr *pE = pTerm->pExpr;
005593                    if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
005594                        pE->iColumn==pExpr->iColumn ){
005595                      pCol->iSorterColumn = j;
005596                      break;
005597                    }
005598                  }
005599                }
005600                if( pCol->iSorterColumn<0 ){
005601                  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
005602                }
005603              }
005604              /* There is now an entry for pExpr in pAggInfo->aCol[] (either
005605              ** because it was there before or because we just created it).
005606              ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
005607              ** pAggInfo->aCol[] entry.
005608              */
005609              ExprSetVVAProperty(pExpr, EP_NoReduce);
005610              pExpr->pAggInfo = pAggInfo;
005611              pExpr->op = TK_AGG_COLUMN;
005612              pExpr->iAgg = (i16)k;
005613              break;
005614            } /* endif pExpr->iTable==pItem->iCursor */
005615          } /* end loop over pSrcList */
005616        }
005617        return WRC_Prune;
005618      }
005619      case TK_AGG_FUNCTION: {
005620        if( (pNC->ncFlags & NC_InAggFunc)==0
005621         && pWalker->walkerDepth==pExpr->op2
005622        ){
005623          /* Check to see if pExpr is a duplicate of another aggregate 
005624          ** function that is already in the pAggInfo structure
005625          */
005626          struct AggInfo_func *pItem = pAggInfo->aFunc;
005627          for(i=0; i<pAggInfo->nFunc; i++, pItem++){
005628            if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
005629              break;
005630            }
005631          }
005632          if( i>=pAggInfo->nFunc ){
005633            /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
005634            */
005635            u8 enc = ENC(pParse->db);
005636            i = addAggInfoFunc(pParse->db, pAggInfo);
005637            if( i>=0 ){
005638              assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
005639              pItem = &pAggInfo->aFunc[i];
005640              pItem->pExpr = pExpr;
005641              pItem->iMem = ++pParse->nMem;
005642              assert( !ExprHasProperty(pExpr, EP_IntValue) );
005643              pItem->pFunc = sqlite3FindFunction(pParse->db,
005644                     pExpr->u.zToken, 
005645                     pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
005646              if( pExpr->flags & EP_Distinct ){
005647                pItem->iDistinct = pParse->nTab++;
005648              }else{
005649                pItem->iDistinct = -1;
005650              }
005651            }
005652          }
005653          /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
005654          */
005655          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
005656          ExprSetVVAProperty(pExpr, EP_NoReduce);
005657          pExpr->iAgg = (i16)i;
005658          pExpr->pAggInfo = pAggInfo;
005659          return WRC_Prune;
005660        }else{
005661          return WRC_Continue;
005662        }
005663      }
005664    }
005665    return WRC_Continue;
005666  }
005667  static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
005668    UNUSED_PARAMETER(pSelect);
005669    pWalker->walkerDepth++;
005670    return WRC_Continue;
005671  }
005672  static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
005673    UNUSED_PARAMETER(pSelect);
005674    pWalker->walkerDepth--;
005675  }
005676  
005677  /*
005678  ** Analyze the pExpr expression looking for aggregate functions and
005679  ** for variables that need to be added to AggInfo object that pNC->pAggInfo
005680  ** points to.  Additional entries are made on the AggInfo object as
005681  ** necessary.
005682  **
005683  ** This routine should only be called after the expression has been
005684  ** analyzed by sqlite3ResolveExprNames().
005685  */
005686  void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
005687    Walker w;
005688    w.xExprCallback = analyzeAggregate;
005689    w.xSelectCallback = analyzeAggregatesInSelect;
005690    w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
005691    w.walkerDepth = 0;
005692    w.u.pNC = pNC;
005693    w.pParse = 0;
005694    assert( pNC->pSrcList!=0 );
005695    sqlite3WalkExpr(&w, pExpr);
005696  }
005697  
005698  /*
005699  ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
005700  ** expression list.  Return the number of errors.
005701  **
005702  ** If an error is found, the analysis is cut short.
005703  */
005704  void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
005705    struct ExprList_item *pItem;
005706    int i;
005707    if( pList ){
005708      for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
005709        sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
005710      }
005711    }
005712  }
005713  
005714  /*
005715  ** Allocate a single new register for use to hold some intermediate result.
005716  */
005717  int sqlite3GetTempReg(Parse *pParse){
005718    if( pParse->nTempReg==0 ){
005719      return ++pParse->nMem;
005720    }
005721    return pParse->aTempReg[--pParse->nTempReg];
005722  }
005723  
005724  /*
005725  ** Deallocate a register, making available for reuse for some other
005726  ** purpose.
005727  */
005728  void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
005729    if( iReg ){
005730      sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0);
005731      if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
005732        pParse->aTempReg[pParse->nTempReg++] = iReg;
005733      }
005734    }
005735  }
005736  
005737  /*
005738  ** Allocate or deallocate a block of nReg consecutive registers.
005739  */
005740  int sqlite3GetTempRange(Parse *pParse, int nReg){
005741    int i, n;
005742    if( nReg==1 ) return sqlite3GetTempReg(pParse);
005743    i = pParse->iRangeReg;
005744    n = pParse->nRangeReg;
005745    if( nReg<=n ){
005746      pParse->iRangeReg += nReg;
005747      pParse->nRangeReg -= nReg;
005748    }else{
005749      i = pParse->nMem+1;
005750      pParse->nMem += nReg;
005751    }
005752    return i;
005753  }
005754  void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
005755    if( nReg==1 ){
005756      sqlite3ReleaseTempReg(pParse, iReg);
005757      return;
005758    }
005759    sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0);
005760    if( nReg>pParse->nRangeReg ){
005761      pParse->nRangeReg = nReg;
005762      pParse->iRangeReg = iReg;
005763    }
005764  }
005765  
005766  /*
005767  ** Mark all temporary registers as being unavailable for reuse.
005768  **
005769  ** Always invoke this procedure after coding a subroutine or co-routine
005770  ** that might be invoked from other parts of the code, to ensure that
005771  ** the sub/co-routine does not use registers in common with the code that
005772  ** invokes the sub/co-routine.
005773  */
005774  void sqlite3ClearTempRegCache(Parse *pParse){
005775    pParse->nTempReg = 0;
005776    pParse->nRangeReg = 0;
005777  }
005778  
005779  /*
005780  ** Validate that no temporary register falls within the range of
005781  ** iFirst..iLast, inclusive.  This routine is only call from within assert()
005782  ** statements.
005783  */
005784  #ifdef SQLITE_DEBUG
005785  int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
005786    int i;
005787    if( pParse->nRangeReg>0
005788     && pParse->iRangeReg+pParse->nRangeReg > iFirst
005789     && pParse->iRangeReg <= iLast
005790    ){
005791       return 0;
005792    }
005793    for(i=0; i<pParse->nTempReg; i++){
005794      if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
005795        return 0;
005796      }
005797    }
005798    return 1;
005799  }
005800  #endif /* SQLITE_DEBUG */