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