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