xref: /sqlite-3.40.0/src/expr.c (revision 0f801707)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** Return the 'affinity' of the expression pExpr if any.
19 **
20 ** If pExpr is a column, a reference to a column via an 'AS' alias,
21 ** or a sub-select with a column as the return value, then the
22 ** affinity of that column is returned. Otherwise, 0x00 is returned,
23 ** indicating no affinity for the expression.
24 **
25 ** i.e. the WHERE clause expresssions in the following statements all
26 ** have an affinity:
27 **
28 ** CREATE TABLE t1(a);
29 ** SELECT * FROM t1 WHERE a;
30 ** SELECT a AS b FROM t1 WHERE b;
31 ** SELECT * FROM t1 WHERE (select a from t1);
32 */
33 char sqlite3ExprAffinity(Expr *pExpr){
34   int op = pExpr->op;
35   if( op==TK_SELECT ){
36     assert( pExpr->flags&EP_xIsSelect );
37     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
38   }
39 #ifndef SQLITE_OMIT_CAST
40   if( op==TK_CAST ){
41     assert( !ExprHasProperty(pExpr, EP_IntValue) );
42     return sqlite3AffinityType(pExpr->u.zToken);
43   }
44 #endif
45   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
46    && pExpr->pTab!=0
47   ){
48     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
49     ** a TK_COLUMN but was previously evaluated and cached in a register */
50     int j = pExpr->iColumn;
51     if( j<0 ) return SQLITE_AFF_INTEGER;
52     assert( pExpr->pTab && j<pExpr->pTab->nCol );
53     return pExpr->pTab->aCol[j].affinity;
54   }
55   return pExpr->affinity;
56 }
57 
58 /*
59 ** Set the explicit collating sequence for an expression to the
60 ** collating sequence supplied in the second argument.
61 */
62 Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
63   if( pExpr && pColl ){
64     pExpr->pColl = pColl;
65     pExpr->flags |= EP_ExpCollate;
66   }
67   return pExpr;
68 }
69 
70 /*
71 ** Set the collating sequence for expression pExpr to be the collating
72 ** sequence named by pToken.   Return a pointer to the revised expression.
73 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
74 ** flag.  An explicit collating sequence will override implicit
75 ** collating sequences.
76 */
77 Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
78   char *zColl = 0;            /* Dequoted name of collation sequence */
79   CollSeq *pColl;
80   sqlite3 *db = pParse->db;
81   zColl = sqlite3NameFromToken(db, pCollName);
82   pColl = sqlite3LocateCollSeq(pParse, zColl);
83   sqlite3ExprSetColl(pExpr, pColl);
84   sqlite3DbFree(db, zColl);
85   return pExpr;
86 }
87 
88 /*
89 ** Return the default collation sequence for the expression pExpr. If
90 ** there is no default collation type, return 0.
91 */
92 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
93   CollSeq *pColl = 0;
94   Expr *p = pExpr;
95   while( p ){
96     int op;
97     pColl = p->pColl;
98     if( pColl ) break;
99     op = p->op;
100     if( p->pTab!=0 && (
101         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
102     )){
103       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
104       ** a TK_COLUMN but was previously evaluated and cached in a register */
105       const char *zColl;
106       int j = p->iColumn;
107       if( j>=0 ){
108         sqlite3 *db = pParse->db;
109         zColl = p->pTab->aCol[j].zColl;
110         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
111         pExpr->pColl = pColl;
112       }
113       break;
114     }
115     if( op!=TK_CAST && op!=TK_UPLUS ){
116       break;
117     }
118     p = p->pLeft;
119   }
120   if( sqlite3CheckCollSeq(pParse, pColl) ){
121     pColl = 0;
122   }
123   return pColl;
124 }
125 
126 /*
127 ** pExpr is an operand of a comparison operator.  aff2 is the
128 ** type affinity of the other operand.  This routine returns the
129 ** type affinity that should be used for the comparison operator.
130 */
131 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
132   char aff1 = sqlite3ExprAffinity(pExpr);
133   if( aff1 && aff2 ){
134     /* Both sides of the comparison are columns. If one has numeric
135     ** affinity, use that. Otherwise use no affinity.
136     */
137     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
138       return SQLITE_AFF_NUMERIC;
139     }else{
140       return SQLITE_AFF_NONE;
141     }
142   }else if( !aff1 && !aff2 ){
143     /* Neither side of the comparison is a column.  Compare the
144     ** results directly.
145     */
146     return SQLITE_AFF_NONE;
147   }else{
148     /* One side is a column, the other is not. Use the columns affinity. */
149     assert( aff1==0 || aff2==0 );
150     return (aff1 + aff2);
151   }
152 }
153 
154 /*
155 ** pExpr is a comparison operator.  Return the type affinity that should
156 ** be applied to both operands prior to doing the comparison.
157 */
158 static char comparisonAffinity(Expr *pExpr){
159   char aff;
160   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
161           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
162           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
163   assert( pExpr->pLeft );
164   aff = sqlite3ExprAffinity(pExpr->pLeft);
165   if( pExpr->pRight ){
166     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
167   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
168     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
169   }else if( !aff ){
170     aff = SQLITE_AFF_NONE;
171   }
172   return aff;
173 }
174 
175 /*
176 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
177 ** idx_affinity is the affinity of an indexed column. Return true
178 ** if the index with affinity idx_affinity may be used to implement
179 ** the comparison in pExpr.
180 */
181 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
182   char aff = comparisonAffinity(pExpr);
183   switch( aff ){
184     case SQLITE_AFF_NONE:
185       return 1;
186     case SQLITE_AFF_TEXT:
187       return idx_affinity==SQLITE_AFF_TEXT;
188     default:
189       return sqlite3IsNumericAffinity(idx_affinity);
190   }
191 }
192 
193 /*
194 ** Return the P5 value that should be used for a binary comparison
195 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
196 */
197 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
198   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
199   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
200   return aff;
201 }
202 
203 /*
204 ** Return a pointer to the collation sequence that should be used by
205 ** a binary comparison operator comparing pLeft and pRight.
206 **
207 ** If the left hand expression has a collating sequence type, then it is
208 ** used. Otherwise the collation sequence for the right hand expression
209 ** is used, or the default (BINARY) if neither expression has a collating
210 ** type.
211 **
212 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
213 ** it is not considered.
214 */
215 CollSeq *sqlite3BinaryCompareCollSeq(
216   Parse *pParse,
217   Expr *pLeft,
218   Expr *pRight
219 ){
220   CollSeq *pColl;
221   assert( pLeft );
222   if( pLeft->flags & EP_ExpCollate ){
223     assert( pLeft->pColl );
224     pColl = pLeft->pColl;
225   }else if( pRight && pRight->flags & EP_ExpCollate ){
226     assert( pRight->pColl );
227     pColl = pRight->pColl;
228   }else{
229     pColl = sqlite3ExprCollSeq(pParse, pLeft);
230     if( !pColl ){
231       pColl = sqlite3ExprCollSeq(pParse, pRight);
232     }
233   }
234   return pColl;
235 }
236 
237 /*
238 ** Generate code for a comparison operator.
239 */
240 static int codeCompare(
241   Parse *pParse,    /* The parsing (and code generating) context */
242   Expr *pLeft,      /* The left operand */
243   Expr *pRight,     /* The right operand */
244   int opcode,       /* The comparison opcode */
245   int in1, int in2, /* Register holding operands */
246   int dest,         /* Jump here if true.  */
247   int jumpIfNull    /* If true, jump if either operand is NULL */
248 ){
249   int p5;
250   int addr;
251   CollSeq *p4;
252 
253   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
254   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
255   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
256                            (void*)p4, P4_COLLSEQ);
257   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
258   return addr;
259 }
260 
261 #if SQLITE_MAX_EXPR_DEPTH>0
262 /*
263 ** Check that argument nHeight is less than or equal to the maximum
264 ** expression depth allowed. If it is not, leave an error message in
265 ** pParse.
266 */
267 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
268   int rc = SQLITE_OK;
269   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
270   if( nHeight>mxHeight ){
271     sqlite3ErrorMsg(pParse,
272        "Expression tree is too large (maximum depth %d)", mxHeight
273     );
274     rc = SQLITE_ERROR;
275   }
276   return rc;
277 }
278 
279 /* The following three functions, heightOfExpr(), heightOfExprList()
280 ** and heightOfSelect(), are used to determine the maximum height
281 ** of any expression tree referenced by the structure passed as the
282 ** first argument.
283 **
284 ** If this maximum height is greater than the current value pointed
285 ** to by pnHeight, the second parameter, then set *pnHeight to that
286 ** value.
287 */
288 static void heightOfExpr(Expr *p, int *pnHeight){
289   if( p ){
290     if( p->nHeight>*pnHeight ){
291       *pnHeight = p->nHeight;
292     }
293   }
294 }
295 static void heightOfExprList(ExprList *p, int *pnHeight){
296   if( p ){
297     int i;
298     for(i=0; i<p->nExpr; i++){
299       heightOfExpr(p->a[i].pExpr, pnHeight);
300     }
301   }
302 }
303 static void heightOfSelect(Select *p, int *pnHeight){
304   if( p ){
305     heightOfExpr(p->pWhere, pnHeight);
306     heightOfExpr(p->pHaving, pnHeight);
307     heightOfExpr(p->pLimit, pnHeight);
308     heightOfExpr(p->pOffset, pnHeight);
309     heightOfExprList(p->pEList, pnHeight);
310     heightOfExprList(p->pGroupBy, pnHeight);
311     heightOfExprList(p->pOrderBy, pnHeight);
312     heightOfSelect(p->pPrior, pnHeight);
313   }
314 }
315 
316 /*
317 ** Set the Expr.nHeight variable in the structure passed as an
318 ** argument. An expression with no children, Expr.pList or
319 ** Expr.pSelect member has a height of 1. Any other expression
320 ** has a height equal to the maximum height of any other
321 ** referenced Expr plus one.
322 */
323 static void exprSetHeight(Expr *p){
324   int nHeight = 0;
325   heightOfExpr(p->pLeft, &nHeight);
326   heightOfExpr(p->pRight, &nHeight);
327   if( ExprHasProperty(p, EP_xIsSelect) ){
328     heightOfSelect(p->x.pSelect, &nHeight);
329   }else{
330     heightOfExprList(p->x.pList, &nHeight);
331   }
332   p->nHeight = nHeight + 1;
333 }
334 
335 /*
336 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
337 ** the height is greater than the maximum allowed expression depth,
338 ** leave an error in pParse.
339 */
340 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
341   exprSetHeight(p);
342   sqlite3ExprCheckHeight(pParse, p->nHeight);
343 }
344 
345 /*
346 ** Return the maximum height of any expression tree referenced
347 ** by the select statement passed as an argument.
348 */
349 int sqlite3SelectExprHeight(Select *p){
350   int nHeight = 0;
351   heightOfSelect(p, &nHeight);
352   return nHeight;
353 }
354 #else
355   #define exprSetHeight(y)
356 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
357 
358 /*
359 ** This routine is the core allocator for Expr nodes.
360 **
361 ** Construct a new expression node and return a pointer to it.  Memory
362 ** for this node and for the pToken argument is a single allocation
363 ** obtained from sqlite3DbMalloc().  The calling function
364 ** is responsible for making sure the node eventually gets freed.
365 **
366 ** If dequote is true, then the token (if it exists) is dequoted.
367 ** If dequote is false, no dequoting is performance.  The deQuote
368 ** parameter is ignored if pToken is NULL or if the token does not
369 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
370 ** then the EP_DblQuoted flag is set on the expression node.
371 **
372 ** Special case:  If op==TK_INTEGER and pToken points to a string that
373 ** can be translated into a 32-bit integer, then the token is not
374 ** stored in u.zToken.  Instead, the integer values is written
375 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
376 ** is allocated to hold the integer text and the dequote flag is ignored.
377 */
378 Expr *sqlite3ExprAlloc(
379   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
380   int op,                 /* Expression opcode */
381   const Token *pToken,    /* Token argument.  Might be NULL */
382   int dequote             /* True to dequote */
383 ){
384   Expr *pNew;
385   int nExtra = 0;
386   int iValue = 0;
387 
388   if( pToken ){
389     if( op!=TK_INTEGER || pToken->z==0
390           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
391       nExtra = pToken->n+1;
392       assert( iValue>=0 );
393     }
394   }
395   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
396   if( pNew ){
397     pNew->op = (u8)op;
398     pNew->iAgg = -1;
399     if( pToken ){
400       if( nExtra==0 ){
401         pNew->flags |= EP_IntValue;
402         pNew->u.iValue = iValue;
403       }else{
404         int c;
405         pNew->u.zToken = (char*)&pNew[1];
406         assert( pToken->z!=0 || pToken->n==0 );
407         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
408         pNew->u.zToken[pToken->n] = 0;
409         if( dequote && nExtra>=3
410              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
411           sqlite3Dequote(pNew->u.zToken);
412           if( c=='"' ) pNew->flags |= EP_DblQuoted;
413         }
414       }
415     }
416 #if SQLITE_MAX_EXPR_DEPTH>0
417     pNew->nHeight = 1;
418 #endif
419   }
420   return pNew;
421 }
422 
423 /*
424 ** Allocate a new expression node from a zero-terminated token that has
425 ** already been dequoted.
426 */
427 Expr *sqlite3Expr(
428   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
429   int op,                 /* Expression opcode */
430   const char *zToken      /* Token argument.  Might be NULL */
431 ){
432   Token x;
433   x.z = zToken;
434   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
435   return sqlite3ExprAlloc(db, op, &x, 0);
436 }
437 
438 /*
439 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
440 **
441 ** If pRoot==NULL that means that a memory allocation error has occurred.
442 ** In that case, delete the subtrees pLeft and pRight.
443 */
444 void sqlite3ExprAttachSubtrees(
445   sqlite3 *db,
446   Expr *pRoot,
447   Expr *pLeft,
448   Expr *pRight
449 ){
450   if( pRoot==0 ){
451     assert( db->mallocFailed );
452     sqlite3ExprDelete(db, pLeft);
453     sqlite3ExprDelete(db, pRight);
454   }else{
455     if( pRight ){
456       pRoot->pRight = pRight;
457       if( pRight->flags & EP_ExpCollate ){
458         pRoot->flags |= EP_ExpCollate;
459         pRoot->pColl = pRight->pColl;
460       }
461     }
462     if( pLeft ){
463       pRoot->pLeft = pLeft;
464       if( pLeft->flags & EP_ExpCollate ){
465         pRoot->flags |= EP_ExpCollate;
466         pRoot->pColl = pLeft->pColl;
467       }
468     }
469     exprSetHeight(pRoot);
470   }
471 }
472 
473 /*
474 ** Allocate a Expr node which joins as many as two subtrees.
475 **
476 ** One or both of the subtrees can be NULL.  Return a pointer to the new
477 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
478 ** free the subtrees and return NULL.
479 */
480 Expr *sqlite3PExpr(
481   Parse *pParse,          /* Parsing context */
482   int op,                 /* Expression opcode */
483   Expr *pLeft,            /* Left operand */
484   Expr *pRight,           /* Right operand */
485   const Token *pToken     /* Argument token */
486 ){
487   Expr *p;
488   if( op==TK_AND && pLeft && pRight ){
489     /* Take advantage of short-circuit false optimization for AND */
490     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
491   }else{
492     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
493     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
494   }
495   if( p ) {
496     sqlite3ExprCheckHeight(pParse, p->nHeight);
497   }
498   return p;
499 }
500 
501 /*
502 ** Return 1 if an expression must be FALSE in all cases and 0 if the
503 ** expression might be true.  This is an optimization.  If is OK to
504 ** return 0 here even if the expression really is always false (a
505 ** false negative).  But it is a bug to return 1 if the expression
506 ** might be true in some rare circumstances (a false positive.)
507 **
508 ** Note that if the expression is part of conditional for a
509 ** LEFT JOIN, then we cannot determine at compile-time whether or not
510 ** is it true or false, so always return 0.
511 */
512 static int exprAlwaysFalse(Expr *p){
513   int v = 0;
514   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
515   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
516   return v==0;
517 }
518 
519 /*
520 ** Join two expressions using an AND operator.  If either expression is
521 ** NULL, then just return the other expression.
522 **
523 ** If one side or the other of the AND is known to be false, then instead
524 ** of returning an AND expression, just return a constant expression with
525 ** a value of false.
526 */
527 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
528   if( pLeft==0 ){
529     return pRight;
530   }else if( pRight==0 ){
531     return pLeft;
532   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
533     sqlite3ExprDelete(db, pLeft);
534     sqlite3ExprDelete(db, pRight);
535     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
536   }else{
537     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
538     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
539     return pNew;
540   }
541 }
542 
543 /*
544 ** Construct a new expression node for a function with multiple
545 ** arguments.
546 */
547 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
548   Expr *pNew;
549   sqlite3 *db = pParse->db;
550   assert( pToken );
551   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
552   if( pNew==0 ){
553     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
554     return 0;
555   }
556   pNew->x.pList = pList;
557   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
558   sqlite3ExprSetHeight(pParse, pNew);
559   return pNew;
560 }
561 
562 /*
563 ** Assign a variable number to an expression that encodes a wildcard
564 ** in the original SQL statement.
565 **
566 ** Wildcards consisting of a single "?" are assigned the next sequential
567 ** variable number.
568 **
569 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
570 ** sure "nnn" is not too be to avoid a denial of service attack when
571 ** the SQL statement comes from an external source.
572 **
573 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
574 ** as the previous instance of the same wildcard.  Or if this is the first
575 ** instance of the wildcard, the next sequenial variable number is
576 ** assigned.
577 */
578 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
579   sqlite3 *db = pParse->db;
580   const char *z;
581 
582   if( pExpr==0 ) return;
583   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
584   z = pExpr->u.zToken;
585   assert( z!=0 );
586   assert( z[0]!=0 );
587   if( z[1]==0 ){
588     /* Wildcard of the form "?".  Assign the next variable number */
589     assert( z[0]=='?' );
590     pExpr->iColumn = (ynVar)(++pParse->nVar);
591   }else{
592     ynVar x = 0;
593     u32 n = sqlite3Strlen30(z);
594     if( z[0]=='?' ){
595       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
596       ** use it as the variable number */
597       i64 i;
598       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
599       pExpr->iColumn = x = (ynVar)i;
600       testcase( i==0 );
601       testcase( i==1 );
602       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
603       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
604       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
605         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
606             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
607         x = 0;
608       }
609       if( i>pParse->nVar ){
610         pParse->nVar = (int)i;
611       }
612     }else{
613       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
614       ** number as the prior appearance of the same name, or if the name
615       ** has never appeared before, reuse the same variable number
616       */
617       ynVar i;
618       for(i=0; i<pParse->nzVar; i++){
619         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
620           pExpr->iColumn = x = (ynVar)i+1;
621           break;
622         }
623       }
624       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
625     }
626     if( x>0 ){
627       if( x>pParse->nzVar ){
628         char **a;
629         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
630         if( a==0 ) return;  /* Error reported through db->mallocFailed */
631         pParse->azVar = a;
632         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
633         pParse->nzVar = x;
634       }
635       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
636         sqlite3DbFree(db, pParse->azVar[x-1]);
637         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
638       }
639     }
640   }
641   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
642     sqlite3ErrorMsg(pParse, "too many SQL variables");
643   }
644 }
645 
646 /*
647 ** Recursively delete an expression tree.
648 */
649 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
650   if( p==0 ) return;
651   /* Sanity check: Assert that the IntValue is non-negative if it exists */
652   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
653   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
654     sqlite3ExprDelete(db, p->pLeft);
655     sqlite3ExprDelete(db, p->pRight);
656     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
657       sqlite3DbFree(db, p->u.zToken);
658     }
659     if( ExprHasProperty(p, EP_xIsSelect) ){
660       sqlite3SelectDelete(db, p->x.pSelect);
661     }else{
662       sqlite3ExprListDelete(db, p->x.pList);
663     }
664   }
665   if( !ExprHasProperty(p, EP_Static) ){
666     sqlite3DbFree(db, p);
667   }
668 }
669 
670 /*
671 ** Return the number of bytes allocated for the expression structure
672 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
673 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
674 */
675 static int exprStructSize(Expr *p){
676   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
677   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
678   return EXPR_FULLSIZE;
679 }
680 
681 /*
682 ** The dupedExpr*Size() routines each return the number of bytes required
683 ** to store a copy of an expression or expression tree.  They differ in
684 ** how much of the tree is measured.
685 **
686 **     dupedExprStructSize()     Size of only the Expr structure
687 **     dupedExprNodeSize()       Size of Expr + space for token
688 **     dupedExprSize()           Expr + token + subtree components
689 **
690 ***************************************************************************
691 **
692 ** The dupedExprStructSize() function returns two values OR-ed together:
693 ** (1) the space required for a copy of the Expr structure only and
694 ** (2) the EP_xxx flags that indicate what the structure size should be.
695 ** The return values is always one of:
696 **
697 **      EXPR_FULLSIZE
698 **      EXPR_REDUCEDSIZE   | EP_Reduced
699 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
700 **
701 ** The size of the structure can be found by masking the return value
702 ** of this routine with 0xfff.  The flags can be found by masking the
703 ** return value with EP_Reduced|EP_TokenOnly.
704 **
705 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
706 ** (unreduced) Expr objects as they or originally constructed by the parser.
707 ** During expression analysis, extra information is computed and moved into
708 ** later parts of teh Expr object and that extra information might get chopped
709 ** off if the expression is reduced.  Note also that it does not work to
710 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
711 ** to reduce a pristine expression tree from the parser.  The implementation
712 ** of dupedExprStructSize() contain multiple assert() statements that attempt
713 ** to enforce this constraint.
714 */
715 static int dupedExprStructSize(Expr *p, int flags){
716   int nSize;
717   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
718   if( 0==(flags&EXPRDUP_REDUCE) ){
719     nSize = EXPR_FULLSIZE;
720   }else{
721     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
722     assert( !ExprHasProperty(p, EP_FromJoin) );
723     assert( (p->flags2 & EP2_MallocedToken)==0 );
724     assert( (p->flags2 & EP2_Irreducible)==0 );
725     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
726       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
727     }else{
728       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
729     }
730   }
731   return nSize;
732 }
733 
734 /*
735 ** This function returns the space in bytes required to store the copy
736 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
737 ** string is defined.)
738 */
739 static int dupedExprNodeSize(Expr *p, int flags){
740   int nByte = dupedExprStructSize(p, flags) & 0xfff;
741   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
742     nByte += sqlite3Strlen30(p->u.zToken)+1;
743   }
744   return ROUND8(nByte);
745 }
746 
747 /*
748 ** Return the number of bytes required to create a duplicate of the
749 ** expression passed as the first argument. The second argument is a
750 ** mask containing EXPRDUP_XXX flags.
751 **
752 ** The value returned includes space to create a copy of the Expr struct
753 ** itself and the buffer referred to by Expr.u.zToken, if any.
754 **
755 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
756 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
757 ** and Expr.pRight variables (but not for any structures pointed to or
758 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
759 */
760 static int dupedExprSize(Expr *p, int flags){
761   int nByte = 0;
762   if( p ){
763     nByte = dupedExprNodeSize(p, flags);
764     if( flags&EXPRDUP_REDUCE ){
765       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
766     }
767   }
768   return nByte;
769 }
770 
771 /*
772 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
773 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
774 ** to store the copy of expression p, the copies of p->u.zToken
775 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
776 ** if any. Before returning, *pzBuffer is set to the first byte passed the
777 ** portion of the buffer copied into by this function.
778 */
779 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
780   Expr *pNew = 0;                      /* Value to return */
781   if( p ){
782     const int isReduced = (flags&EXPRDUP_REDUCE);
783     u8 *zAlloc;
784     u32 staticFlag = 0;
785 
786     assert( pzBuffer==0 || isReduced );
787 
788     /* Figure out where to write the new Expr structure. */
789     if( pzBuffer ){
790       zAlloc = *pzBuffer;
791       staticFlag = EP_Static;
792     }else{
793       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
794     }
795     pNew = (Expr *)zAlloc;
796 
797     if( pNew ){
798       /* Set nNewSize to the size allocated for the structure pointed to
799       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
800       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
801       ** by the copy of the p->u.zToken string (if any).
802       */
803       const unsigned nStructSize = dupedExprStructSize(p, flags);
804       const int nNewSize = nStructSize & 0xfff;
805       int nToken;
806       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
807         nToken = sqlite3Strlen30(p->u.zToken) + 1;
808       }else{
809         nToken = 0;
810       }
811       if( isReduced ){
812         assert( ExprHasProperty(p, EP_Reduced)==0 );
813         memcpy(zAlloc, p, nNewSize);
814       }else{
815         int nSize = exprStructSize(p);
816         memcpy(zAlloc, p, nSize);
817         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
818       }
819 
820       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
821       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
822       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
823       pNew->flags |= staticFlag;
824 
825       /* Copy the p->u.zToken string, if any. */
826       if( nToken ){
827         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
828         memcpy(zToken, p->u.zToken, nToken);
829       }
830 
831       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
832         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
833         if( ExprHasProperty(p, EP_xIsSelect) ){
834           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
835         }else{
836           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
837         }
838       }
839 
840       /* Fill in pNew->pLeft and pNew->pRight. */
841       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
842         zAlloc += dupedExprNodeSize(p, flags);
843         if( ExprHasProperty(pNew, EP_Reduced) ){
844           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
845           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
846         }
847         if( pzBuffer ){
848           *pzBuffer = zAlloc;
849         }
850       }else{
851         pNew->flags2 = 0;
852         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
853           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
854           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
855         }
856       }
857 
858     }
859   }
860   return pNew;
861 }
862 
863 /*
864 ** The following group of routines make deep copies of expressions,
865 ** expression lists, ID lists, and select statements.  The copies can
866 ** be deleted (by being passed to their respective ...Delete() routines)
867 ** without effecting the originals.
868 **
869 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
870 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
871 ** by subsequent calls to sqlite*ListAppend() routines.
872 **
873 ** Any tables that the SrcList might point to are not duplicated.
874 **
875 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
876 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
877 ** truncated version of the usual Expr structure that will be stored as
878 ** part of the in-memory representation of the database schema.
879 */
880 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
881   return exprDup(db, p, flags, 0);
882 }
883 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
884   ExprList *pNew;
885   struct ExprList_item *pItem, *pOldItem;
886   int i;
887   if( p==0 ) return 0;
888   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
889   if( pNew==0 ) return 0;
890   pNew->iECursor = 0;
891   pNew->nExpr = i = p->nExpr;
892   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
893   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
894   if( pItem==0 ){
895     sqlite3DbFree(db, pNew);
896     return 0;
897   }
898   pOldItem = p->a;
899   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
900     Expr *pOldExpr = pOldItem->pExpr;
901     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
902     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
903     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
904     pItem->sortOrder = pOldItem->sortOrder;
905     pItem->done = 0;
906     pItem->iOrderByCol = pOldItem->iOrderByCol;
907     pItem->iAlias = pOldItem->iAlias;
908   }
909   return pNew;
910 }
911 
912 /*
913 ** If cursors, triggers, views and subqueries are all omitted from
914 ** the build, then none of the following routines, except for
915 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
916 ** called with a NULL argument.
917 */
918 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
919  || !defined(SQLITE_OMIT_SUBQUERY)
920 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
921   SrcList *pNew;
922   int i;
923   int nByte;
924   if( p==0 ) return 0;
925   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
926   pNew = sqlite3DbMallocRaw(db, nByte );
927   if( pNew==0 ) return 0;
928   pNew->nSrc = pNew->nAlloc = p->nSrc;
929   for(i=0; i<p->nSrc; i++){
930     struct SrcList_item *pNewItem = &pNew->a[i];
931     struct SrcList_item *pOldItem = &p->a[i];
932     Table *pTab;
933     pNewItem->pSchema = pOldItem->pSchema;
934     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
935     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
936     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
937     pNewItem->jointype = pOldItem->jointype;
938     pNewItem->iCursor = pOldItem->iCursor;
939     pNewItem->addrFillSub = pOldItem->addrFillSub;
940     pNewItem->regReturn = pOldItem->regReturn;
941     pNewItem->isCorrelated = pOldItem->isCorrelated;
942     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
943     pNewItem->notIndexed = pOldItem->notIndexed;
944     pNewItem->pIndex = pOldItem->pIndex;
945     pTab = pNewItem->pTab = pOldItem->pTab;
946     if( pTab ){
947       pTab->nRef++;
948     }
949     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
950     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
951     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
952     pNewItem->colUsed = pOldItem->colUsed;
953   }
954   return pNew;
955 }
956 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
957   IdList *pNew;
958   int i;
959   if( p==0 ) return 0;
960   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
961   if( pNew==0 ) return 0;
962   pNew->nId = p->nId;
963   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
964   if( pNew->a==0 ){
965     sqlite3DbFree(db, pNew);
966     return 0;
967   }
968   /* Note that because the size of the allocation for p->a[] is not
969   ** necessarily a power of two, sqlite3IdListAppend() may not be called
970   ** on the duplicate created by this function. */
971   for(i=0; i<p->nId; i++){
972     struct IdList_item *pNewItem = &pNew->a[i];
973     struct IdList_item *pOldItem = &p->a[i];
974     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
975     pNewItem->idx = pOldItem->idx;
976   }
977   return pNew;
978 }
979 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
980   Select *pNew, *pPrior;
981   if( p==0 ) return 0;
982   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
983   if( pNew==0 ) return 0;
984   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
985   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
986   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
987   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
988   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
989   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
990   pNew->op = p->op;
991   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
992   if( pPrior ) pPrior->pNext = pNew;
993   pNew->pNext = 0;
994   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
995   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
996   pNew->iLimit = 0;
997   pNew->iOffset = 0;
998   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
999   pNew->pRightmost = 0;
1000   pNew->addrOpenEphm[0] = -1;
1001   pNew->addrOpenEphm[1] = -1;
1002   pNew->addrOpenEphm[2] = -1;
1003   return pNew;
1004 }
1005 #else
1006 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1007   assert( p==0 );
1008   return 0;
1009 }
1010 #endif
1011 
1012 
1013 /*
1014 ** Add a new element to the end of an expression list.  If pList is
1015 ** initially NULL, then create a new expression list.
1016 **
1017 ** If a memory allocation error occurs, the entire list is freed and
1018 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1019 ** that the new entry was successfully appended.
1020 */
1021 ExprList *sqlite3ExprListAppend(
1022   Parse *pParse,          /* Parsing context */
1023   ExprList *pList,        /* List to which to append. Might be NULL */
1024   Expr *pExpr             /* Expression to be appended. Might be NULL */
1025 ){
1026   sqlite3 *db = pParse->db;
1027   if( pList==0 ){
1028     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
1029     if( pList==0 ){
1030       goto no_mem;
1031     }
1032     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
1033     if( pList->a==0 ) goto no_mem;
1034   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1035     struct ExprList_item *a;
1036     assert( pList->nExpr>0 );
1037     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1038     if( a==0 ){
1039       goto no_mem;
1040     }
1041     pList->a = a;
1042   }
1043   assert( pList->a!=0 );
1044   if( 1 ){
1045     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1046     memset(pItem, 0, sizeof(*pItem));
1047     pItem->pExpr = pExpr;
1048   }
1049   return pList;
1050 
1051 no_mem:
1052   /* Avoid leaking memory if malloc has failed. */
1053   sqlite3ExprDelete(db, pExpr);
1054   sqlite3ExprListDelete(db, pList);
1055   return 0;
1056 }
1057 
1058 /*
1059 ** Set the ExprList.a[].zName element of the most recently added item
1060 ** on the expression list.
1061 **
1062 ** pList might be NULL following an OOM error.  But pName should never be
1063 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1064 ** is set.
1065 */
1066 void sqlite3ExprListSetName(
1067   Parse *pParse,          /* Parsing context */
1068   ExprList *pList,        /* List to which to add the span. */
1069   Token *pName,           /* Name to be added */
1070   int dequote             /* True to cause the name to be dequoted */
1071 ){
1072   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1073   if( pList ){
1074     struct ExprList_item *pItem;
1075     assert( pList->nExpr>0 );
1076     pItem = &pList->a[pList->nExpr-1];
1077     assert( pItem->zName==0 );
1078     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1079     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1080   }
1081 }
1082 
1083 /*
1084 ** Set the ExprList.a[].zSpan element of the most recently added item
1085 ** on the expression list.
1086 **
1087 ** pList might be NULL following an OOM error.  But pSpan should never be
1088 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1089 ** is set.
1090 */
1091 void sqlite3ExprListSetSpan(
1092   Parse *pParse,          /* Parsing context */
1093   ExprList *pList,        /* List to which to add the span. */
1094   ExprSpan *pSpan         /* The span to be added */
1095 ){
1096   sqlite3 *db = pParse->db;
1097   assert( pList!=0 || db->mallocFailed!=0 );
1098   if( pList ){
1099     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1100     assert( pList->nExpr>0 );
1101     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1102     sqlite3DbFree(db, pItem->zSpan);
1103     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1104                                     (int)(pSpan->zEnd - pSpan->zStart));
1105   }
1106 }
1107 
1108 /*
1109 ** If the expression list pEList contains more than iLimit elements,
1110 ** leave an error message in pParse.
1111 */
1112 void sqlite3ExprListCheckLength(
1113   Parse *pParse,
1114   ExprList *pEList,
1115   const char *zObject
1116 ){
1117   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1118   testcase( pEList && pEList->nExpr==mx );
1119   testcase( pEList && pEList->nExpr==mx+1 );
1120   if( pEList && pEList->nExpr>mx ){
1121     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1122   }
1123 }
1124 
1125 /*
1126 ** Delete an entire expression list.
1127 */
1128 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1129   int i;
1130   struct ExprList_item *pItem;
1131   if( pList==0 ) return;
1132   assert( pList->a!=0 || pList->nExpr==0 );
1133   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1134     sqlite3ExprDelete(db, pItem->pExpr);
1135     sqlite3DbFree(db, pItem->zName);
1136     sqlite3DbFree(db, pItem->zSpan);
1137   }
1138   sqlite3DbFree(db, pList->a);
1139   sqlite3DbFree(db, pList);
1140 }
1141 
1142 /*
1143 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
1144 ** to an integer.  These routines are checking an expression to see
1145 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
1146 ** not constant.
1147 **
1148 ** These callback routines are used to implement the following:
1149 **
1150 **     sqlite3ExprIsConstant()
1151 **     sqlite3ExprIsConstantNotJoin()
1152 **     sqlite3ExprIsConstantOrFunction()
1153 **
1154 */
1155 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1156 
1157   /* If pWalker->u.i is 3 then any term of the expression that comes from
1158   ** the ON or USING clauses of a join disqualifies the expression
1159   ** from being considered constant. */
1160   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
1161     pWalker->u.i = 0;
1162     return WRC_Abort;
1163   }
1164 
1165   switch( pExpr->op ){
1166     /* Consider functions to be constant if all their arguments are constant
1167     ** and pWalker->u.i==2 */
1168     case TK_FUNCTION:
1169       if( pWalker->u.i==2 ) return 0;
1170       /* Fall through */
1171     case TK_ID:
1172     case TK_COLUMN:
1173     case TK_AGG_FUNCTION:
1174     case TK_AGG_COLUMN:
1175       testcase( pExpr->op==TK_ID );
1176       testcase( pExpr->op==TK_COLUMN );
1177       testcase( pExpr->op==TK_AGG_FUNCTION );
1178       testcase( pExpr->op==TK_AGG_COLUMN );
1179       pWalker->u.i = 0;
1180       return WRC_Abort;
1181     default:
1182       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1183       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
1184       return WRC_Continue;
1185   }
1186 }
1187 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1188   UNUSED_PARAMETER(NotUsed);
1189   pWalker->u.i = 0;
1190   return WRC_Abort;
1191 }
1192 static int exprIsConst(Expr *p, int initFlag){
1193   Walker w;
1194   w.u.i = initFlag;
1195   w.xExprCallback = exprNodeIsConstant;
1196   w.xSelectCallback = selectNodeIsConstant;
1197   sqlite3WalkExpr(&w, p);
1198   return w.u.i;
1199 }
1200 
1201 /*
1202 ** Walk an expression tree.  Return 1 if the expression is constant
1203 ** and 0 if it involves variables or function calls.
1204 **
1205 ** For the purposes of this function, a double-quoted string (ex: "abc")
1206 ** is considered a variable but a single-quoted string (ex: 'abc') is
1207 ** a constant.
1208 */
1209 int sqlite3ExprIsConstant(Expr *p){
1210   return exprIsConst(p, 1);
1211 }
1212 
1213 /*
1214 ** Walk an expression tree.  Return 1 if the expression is constant
1215 ** that does no originate from the ON or USING clauses of a join.
1216 ** Return 0 if it involves variables or function calls or terms from
1217 ** an ON or USING clause.
1218 */
1219 int sqlite3ExprIsConstantNotJoin(Expr *p){
1220   return exprIsConst(p, 3);
1221 }
1222 
1223 /*
1224 ** Walk an expression tree.  Return 1 if the expression is constant
1225 ** or a function call with constant arguments.  Return and 0 if there
1226 ** are any variables.
1227 **
1228 ** For the purposes of this function, a double-quoted string (ex: "abc")
1229 ** is considered a variable but a single-quoted string (ex: 'abc') is
1230 ** a constant.
1231 */
1232 int sqlite3ExprIsConstantOrFunction(Expr *p){
1233   return exprIsConst(p, 2);
1234 }
1235 
1236 /*
1237 ** If the expression p codes a constant integer that is small enough
1238 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1239 ** in *pValue.  If the expression is not an integer or if it is too big
1240 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1241 */
1242 int sqlite3ExprIsInteger(Expr *p, int *pValue){
1243   int rc = 0;
1244 
1245   /* If an expression is an integer literal that fits in a signed 32-bit
1246   ** integer, then the EP_IntValue flag will have already been set */
1247   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1248            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1249 
1250   if( p->flags & EP_IntValue ){
1251     *pValue = p->u.iValue;
1252     return 1;
1253   }
1254   switch( p->op ){
1255     case TK_UPLUS: {
1256       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1257       break;
1258     }
1259     case TK_UMINUS: {
1260       int v;
1261       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1262         *pValue = -v;
1263         rc = 1;
1264       }
1265       break;
1266     }
1267     default: break;
1268   }
1269   return rc;
1270 }
1271 
1272 /*
1273 ** Return FALSE if there is no chance that the expression can be NULL.
1274 **
1275 ** If the expression might be NULL or if the expression is too complex
1276 ** to tell return TRUE.
1277 **
1278 ** This routine is used as an optimization, to skip OP_IsNull opcodes
1279 ** when we know that a value cannot be NULL.  Hence, a false positive
1280 ** (returning TRUE when in fact the expression can never be NULL) might
1281 ** be a small performance hit but is otherwise harmless.  On the other
1282 ** hand, a false negative (returning FALSE when the result could be NULL)
1283 ** will likely result in an incorrect answer.  So when in doubt, return
1284 ** TRUE.
1285 */
1286 int sqlite3ExprCanBeNull(const Expr *p){
1287   u8 op;
1288   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1289   op = p->op;
1290   if( op==TK_REGISTER ) op = p->op2;
1291   switch( op ){
1292     case TK_INTEGER:
1293     case TK_STRING:
1294     case TK_FLOAT:
1295     case TK_BLOB:
1296       return 0;
1297     default:
1298       return 1;
1299   }
1300 }
1301 
1302 /*
1303 ** Generate an OP_IsNull instruction that tests register iReg and jumps
1304 ** to location iDest if the value in iReg is NULL.  The value in iReg
1305 ** was computed by pExpr.  If we can look at pExpr at compile-time and
1306 ** determine that it can never generate a NULL, then the OP_IsNull operation
1307 ** can be omitted.
1308 */
1309 void sqlite3ExprCodeIsNullJump(
1310   Vdbe *v,            /* The VDBE under construction */
1311   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
1312   int iReg,           /* Test the value in this register for NULL */
1313   int iDest           /* Jump here if the value is null */
1314 ){
1315   if( sqlite3ExprCanBeNull(pExpr) ){
1316     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
1317   }
1318 }
1319 
1320 /*
1321 ** Return TRUE if the given expression is a constant which would be
1322 ** unchanged by OP_Affinity with the affinity given in the second
1323 ** argument.
1324 **
1325 ** This routine is used to determine if the OP_Affinity operation
1326 ** can be omitted.  When in doubt return FALSE.  A false negative
1327 ** is harmless.  A false positive, however, can result in the wrong
1328 ** answer.
1329 */
1330 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1331   u8 op;
1332   if( aff==SQLITE_AFF_NONE ) return 1;
1333   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1334   op = p->op;
1335   if( op==TK_REGISTER ) op = p->op2;
1336   switch( op ){
1337     case TK_INTEGER: {
1338       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1339     }
1340     case TK_FLOAT: {
1341       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1342     }
1343     case TK_STRING: {
1344       return aff==SQLITE_AFF_TEXT;
1345     }
1346     case TK_BLOB: {
1347       return 1;
1348     }
1349     case TK_COLUMN: {
1350       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
1351       return p->iColumn<0
1352           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
1353     }
1354     default: {
1355       return 0;
1356     }
1357   }
1358 }
1359 
1360 /*
1361 ** Return TRUE if the given string is a row-id column name.
1362 */
1363 int sqlite3IsRowid(const char *z){
1364   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1365   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1366   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1367   return 0;
1368 }
1369 
1370 /*
1371 ** Return true if we are able to the IN operator optimization on a
1372 ** query of the form
1373 **
1374 **       x IN (SELECT ...)
1375 **
1376 ** Where the SELECT... clause is as specified by the parameter to this
1377 ** routine.
1378 **
1379 ** The Select object passed in has already been preprocessed and no
1380 ** errors have been found.
1381 */
1382 #ifndef SQLITE_OMIT_SUBQUERY
1383 static int isCandidateForInOpt(Select *p){
1384   SrcList *pSrc;
1385   ExprList *pEList;
1386   Table *pTab;
1387   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1388   if( p->pPrior ) return 0;              /* Not a compound SELECT */
1389   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1390     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1391     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1392     return 0; /* No DISTINCT keyword and no aggregate functions */
1393   }
1394   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1395   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1396   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1397   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1398   pSrc = p->pSrc;
1399   assert( pSrc!=0 );
1400   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1401   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1402   pTab = pSrc->a[0].pTab;
1403   if( NEVER(pTab==0) ) return 0;
1404   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1405   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1406   pEList = p->pEList;
1407   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1408   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1409   return 1;
1410 }
1411 #endif /* SQLITE_OMIT_SUBQUERY */
1412 
1413 /*
1414 ** Code an OP_Once instruction and allocate space for its flag. Return the
1415 ** address of the new instruction.
1416 */
1417 int sqlite3CodeOnce(Parse *pParse){
1418   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
1419   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1420 }
1421 
1422 /*
1423 ** This function is used by the implementation of the IN (...) operator.
1424 ** The pX parameter is the expression on the RHS of the IN operator, which
1425 ** might be either a list of expressions or a subquery.
1426 **
1427 ** The job of this routine is to find or create a b-tree object that can
1428 ** be used either to test for membership in the RHS set or to iterate through
1429 ** all members of the RHS set, skipping duplicates.
1430 **
1431 ** A cursor is opened on the b-tree object that the RHS of the IN operator
1432 ** and pX->iTable is set to the index of that cursor.
1433 **
1434 ** The returned value of this function indicates the b-tree type, as follows:
1435 **
1436 **   IN_INDEX_ROWID - The cursor was opened on a database table.
1437 **   IN_INDEX_INDEX - The cursor was opened on a database index.
1438 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
1439 **                    populated epheremal table.
1440 **
1441 ** An existing b-tree might be used if the RHS expression pX is a simple
1442 ** subquery such as:
1443 **
1444 **     SELECT <column> FROM <table>
1445 **
1446 ** If the RHS of the IN operator is a list or a more complex subquery, then
1447 ** an ephemeral table might need to be generated from the RHS and then
1448 ** pX->iTable made to point to the ephermeral table instead of an
1449 ** existing table.
1450 **
1451 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
1452 ** through the set members, skipping any duplicates. In this case an
1453 ** epheremal table must be used unless the selected <column> is guaranteed
1454 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1455 ** has a UNIQUE constraint or UNIQUE index.
1456 **
1457 ** If the prNotFound parameter is not 0, then the b-tree will be used
1458 ** for fast set membership tests. In this case an epheremal table must
1459 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1460 ** be found with <column> as its left-most column.
1461 **
1462 ** When the b-tree is being used for membership tests, the calling function
1463 ** needs to know whether or not the structure contains an SQL NULL
1464 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1465 ** If there is any chance that the (...) might contain a NULL value at
1466 ** runtime, then a register is allocated and the register number written
1467 ** to *prNotFound. If there is no chance that the (...) contains a
1468 ** NULL value, then *prNotFound is left unchanged.
1469 **
1470 ** If a register is allocated and its location stored in *prNotFound, then
1471 ** its initial value is NULL.  If the (...) does not remain constant
1472 ** for the duration of the query (i.e. the SELECT within the (...)
1473 ** is a correlated subquery) then the value of the allocated register is
1474 ** reset to NULL each time the subquery is rerun. This allows the
1475 ** caller to use vdbe code equivalent to the following:
1476 **
1477 **   if( register==NULL ){
1478 **     has_null = <test if data structure contains null>
1479 **     register = 1
1480 **   }
1481 **
1482 ** in order to avoid running the <test if data structure contains null>
1483 ** test more often than is necessary.
1484 */
1485 #ifndef SQLITE_OMIT_SUBQUERY
1486 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1487   Select *p;                            /* SELECT to the right of IN operator */
1488   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1489   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
1490   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
1491   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
1492 
1493   assert( pX->op==TK_IN );
1494 
1495   /* Check to see if an existing table or index can be used to
1496   ** satisfy the query.  This is preferable to generating a new
1497   ** ephemeral table.
1498   */
1499   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1500   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
1501     sqlite3 *db = pParse->db;              /* Database connection */
1502     Table *pTab;                           /* Table <table>. */
1503     Expr *pExpr;                           /* Expression <column> */
1504     int iCol;                              /* Index of column <column> */
1505     int iDb;                               /* Database idx for pTab */
1506 
1507     assert( p );                        /* Because of isCandidateForInOpt(p) */
1508     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
1509     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1510     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
1511     pTab = p->pSrc->a[0].pTab;
1512     pExpr = p->pEList->a[0].pExpr;
1513     iCol = pExpr->iColumn;
1514 
1515     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
1516     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1517     sqlite3CodeVerifySchema(pParse, iDb);
1518     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1519 
1520     /* This function is only called from two places. In both cases the vdbe
1521     ** has already been allocated. So assume sqlite3GetVdbe() is always
1522     ** successful here.
1523     */
1524     assert(v);
1525     if( iCol<0 ){
1526       int iAddr;
1527 
1528       iAddr = sqlite3CodeOnce(pParse);
1529 
1530       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1531       eType = IN_INDEX_ROWID;
1532 
1533       sqlite3VdbeJumpHere(v, iAddr);
1534     }else{
1535       Index *pIdx;                         /* Iterator variable */
1536 
1537       /* The collation sequence used by the comparison. If an index is to
1538       ** be used in place of a temp-table, it must be ordered according
1539       ** to this collation sequence.  */
1540       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1541 
1542       /* Check that the affinity that will be used to perform the
1543       ** comparison is the same as the affinity of the column. If
1544       ** it is not, it is not possible to use any index.
1545       */
1546       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
1547 
1548       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1549         if( (pIdx->aiColumn[0]==iCol)
1550          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
1551          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1552         ){
1553           int iAddr;
1554           char *pKey;
1555 
1556           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1557           iAddr = sqlite3CodeOnce(pParse);
1558 
1559           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
1560                                pKey,P4_KEYINFO_HANDOFF);
1561           VdbeComment((v, "%s", pIdx->zName));
1562           eType = IN_INDEX_INDEX;
1563 
1564           sqlite3VdbeJumpHere(v, iAddr);
1565           if( prNotFound && !pTab->aCol[iCol].notNull ){
1566             *prNotFound = ++pParse->nMem;
1567             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
1568           }
1569         }
1570       }
1571     }
1572   }
1573 
1574   if( eType==0 ){
1575     /* Could not found an existing table or index to use as the RHS b-tree.
1576     ** We will have to generate an ephemeral table to do the job.
1577     */
1578     double savedNQueryLoop = pParse->nQueryLoop;
1579     int rMayHaveNull = 0;
1580     eType = IN_INDEX_EPH;
1581     if( prNotFound ){
1582       *prNotFound = rMayHaveNull = ++pParse->nMem;
1583       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
1584     }else{
1585       testcase( pParse->nQueryLoop>(double)1 );
1586       pParse->nQueryLoop = (double)1;
1587       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
1588         eType = IN_INDEX_ROWID;
1589       }
1590     }
1591     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1592     pParse->nQueryLoop = savedNQueryLoop;
1593   }else{
1594     pX->iTable = iTab;
1595   }
1596   return eType;
1597 }
1598 #endif
1599 
1600 /*
1601 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1602 ** or IN operators.  Examples:
1603 **
1604 **     (SELECT a FROM b)          -- subquery
1605 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
1606 **     x IN (4,5,11)              -- IN operator with list on right-hand side
1607 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1608 **
1609 ** The pExpr parameter describes the expression that contains the IN
1610 ** operator or subquery.
1611 **
1612 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1613 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1614 ** to some integer key column of a table B-Tree. In this case, use an
1615 ** intkey B-Tree to store the set of IN(...) values instead of the usual
1616 ** (slower) variable length keys B-Tree.
1617 **
1618 ** If rMayHaveNull is non-zero, that means that the operation is an IN
1619 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
1620 ** Furthermore, the IN is in a WHERE clause and that we really want
1621 ** to iterate over the RHS of the IN operator in order to quickly locate
1622 ** all corresponding LHS elements.  All this routine does is initialize
1623 ** the register given by rMayHaveNull to NULL.  Calling routines will take
1624 ** care of changing this register value to non-NULL if the RHS is NULL-free.
1625 **
1626 ** If rMayHaveNull is zero, that means that the subquery is being used
1627 ** for membership testing only.  There is no need to initialize any
1628 ** registers to indicate the presense or absence of NULLs on the RHS.
1629 **
1630 ** For a SELECT or EXISTS operator, return the register that holds the
1631 ** result.  For IN operators or if an error occurs, the return value is 0.
1632 */
1633 #ifndef SQLITE_OMIT_SUBQUERY
1634 int sqlite3CodeSubselect(
1635   Parse *pParse,          /* Parsing context */
1636   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
1637   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
1638   int isRowid             /* If true, LHS of IN operator is a rowid */
1639 ){
1640   int testAddr = -1;                      /* One-time test address */
1641   int rReg = 0;                           /* Register storing resulting */
1642   Vdbe *v = sqlite3GetVdbe(pParse);
1643   if( NEVER(v==0) ) return 0;
1644   sqlite3ExprCachePush(pParse);
1645 
1646   /* This code must be run in its entirety every time it is encountered
1647   ** if any of the following is true:
1648   **
1649   **    *  The right-hand side is a correlated subquery
1650   **    *  The right-hand side is an expression list containing variables
1651   **    *  We are inside a trigger
1652   **
1653   ** If all of the above are false, then we can run this code just once
1654   ** save the results, and reuse the same result on subsequent invocations.
1655   */
1656   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
1657     testAddr = sqlite3CodeOnce(pParse);
1658   }
1659 
1660 #ifndef SQLITE_OMIT_EXPLAIN
1661   if( pParse->explain==2 ){
1662     char *zMsg = sqlite3MPrintf(
1663         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
1664         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
1665     );
1666     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
1667   }
1668 #endif
1669 
1670   switch( pExpr->op ){
1671     case TK_IN: {
1672       char affinity;              /* Affinity of the LHS of the IN */
1673       KeyInfo keyInfo;            /* Keyinfo for the generated table */
1674       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
1675       int addr;                   /* Address of OP_OpenEphemeral instruction */
1676       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
1677 
1678       if( rMayHaveNull ){
1679         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
1680       }
1681 
1682       affinity = sqlite3ExprAffinity(pLeft);
1683 
1684       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1685       ** expression it is handled the same way.  An ephemeral table is
1686       ** filled with single-field index keys representing the results
1687       ** from the SELECT or the <exprlist>.
1688       **
1689       ** If the 'x' expression is a column value, or the SELECT...
1690       ** statement returns a column value, then the affinity of that
1691       ** column is used to build the index keys. If both 'x' and the
1692       ** SELECT... statement are columns, then numeric affinity is used
1693       ** if either column has NUMERIC or INTEGER affinity. If neither
1694       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1695       ** is used.
1696       */
1697       pExpr->iTable = pParse->nTab++;
1698       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1699       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1700       memset(&keyInfo, 0, sizeof(keyInfo));
1701       keyInfo.nField = 1;
1702       keyInfo.aSortOrder = &sortOrder;
1703 
1704       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1705         /* Case 1:     expr IN (SELECT ...)
1706         **
1707         ** Generate code to write the results of the select into the temporary
1708         ** table allocated and opened above.
1709         */
1710         SelectDest dest;
1711         ExprList *pEList;
1712 
1713         assert( !isRowid );
1714         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1715         dest.affSdst = (u8)affinity;
1716         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1717         pExpr->x.pSelect->iLimit = 0;
1718         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
1719           return 0;
1720         }
1721         pEList = pExpr->x.pSelect->pEList;
1722         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
1723           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1724               pEList->a[0].pExpr);
1725         }
1726       }else if( ALWAYS(pExpr->x.pList!=0) ){
1727         /* Case 2:     expr IN (exprlist)
1728         **
1729         ** For each expression, build an index key from the evaluation and
1730         ** store it in the temporary table. If <expr> is a column, then use
1731         ** that columns affinity when building index keys. If <expr> is not
1732         ** a column, use numeric affinity.
1733         */
1734         int i;
1735         ExprList *pList = pExpr->x.pList;
1736         struct ExprList_item *pItem;
1737         int r1, r2, r3;
1738 
1739         if( !affinity ){
1740           affinity = SQLITE_AFF_NONE;
1741         }
1742         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1743         keyInfo.aSortOrder = &sortOrder;
1744 
1745         /* Loop through each expression in <exprlist>. */
1746         r1 = sqlite3GetTempReg(pParse);
1747         r2 = sqlite3GetTempReg(pParse);
1748         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
1749         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1750           Expr *pE2 = pItem->pExpr;
1751           int iValToIns;
1752 
1753           /* If the expression is not constant then we will need to
1754           ** disable the test that was generated above that makes sure
1755           ** this code only executes once.  Because for a non-constant
1756           ** expression we need to rerun this code each time.
1757           */
1758           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
1759             sqlite3VdbeChangeToNoop(v, testAddr);
1760             testAddr = -1;
1761           }
1762 
1763           /* Evaluate the expression and insert it into the temp table */
1764           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
1765             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
1766           }else{
1767             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
1768             if( isRowid ){
1769               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
1770                                 sqlite3VdbeCurrentAddr(v)+2);
1771               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
1772             }else{
1773               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
1774               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
1775               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1776             }
1777           }
1778         }
1779         sqlite3ReleaseTempReg(pParse, r1);
1780         sqlite3ReleaseTempReg(pParse, r2);
1781       }
1782       if( !isRowid ){
1783         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1784       }
1785       break;
1786     }
1787 
1788     case TK_EXISTS:
1789     case TK_SELECT:
1790     default: {
1791       /* If this has to be a scalar SELECT.  Generate code to put the
1792       ** value of this select in a memory cell and record the number
1793       ** of the memory cell in iColumn.  If this is an EXISTS, write
1794       ** an integer 0 (not exists) or 1 (exists) into a memory cell
1795       ** and record that memory cell in iColumn.
1796       */
1797       Select *pSel;                         /* SELECT statement to encode */
1798       SelectDest dest;                      /* How to deal with SELECt result */
1799 
1800       testcase( pExpr->op==TK_EXISTS );
1801       testcase( pExpr->op==TK_SELECT );
1802       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
1803 
1804       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1805       pSel = pExpr->x.pSelect;
1806       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
1807       if( pExpr->op==TK_SELECT ){
1808         dest.eDest = SRT_Mem;
1809         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
1810         VdbeComment((v, "Init subquery result"));
1811       }else{
1812         dest.eDest = SRT_Exists;
1813         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
1814         VdbeComment((v, "Init EXISTS result"));
1815       }
1816       sqlite3ExprDelete(pParse->db, pSel->pLimit);
1817       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
1818                                   &sqlite3IntTokens[1]);
1819       pSel->iLimit = 0;
1820       if( sqlite3Select(pParse, pSel, &dest) ){
1821         return 0;
1822       }
1823       rReg = dest.iSDParm;
1824       ExprSetIrreducible(pExpr);
1825       break;
1826     }
1827   }
1828 
1829   if( testAddr>=0 ){
1830     sqlite3VdbeJumpHere(v, testAddr);
1831   }
1832   sqlite3ExprCachePop(pParse, 1);
1833 
1834   return rReg;
1835 }
1836 #endif /* SQLITE_OMIT_SUBQUERY */
1837 
1838 #ifndef SQLITE_OMIT_SUBQUERY
1839 /*
1840 ** Generate code for an IN expression.
1841 **
1842 **      x IN (SELECT ...)
1843 **      x IN (value, value, ...)
1844 **
1845 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
1846 ** is an array of zero or more values.  The expression is true if the LHS is
1847 ** contained within the RHS.  The value of the expression is unknown (NULL)
1848 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
1849 ** RHS contains one or more NULL values.
1850 **
1851 ** This routine generates code will jump to destIfFalse if the LHS is not
1852 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
1853 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
1854 ** within the RHS then fall through.
1855 */
1856 static void sqlite3ExprCodeIN(
1857   Parse *pParse,        /* Parsing and code generating context */
1858   Expr *pExpr,          /* The IN expression */
1859   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
1860   int destIfNull        /* Jump here if the results are unknown due to NULLs */
1861 ){
1862   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
1863   char affinity;        /* Comparison affinity to use */
1864   int eType;            /* Type of the RHS */
1865   int r1;               /* Temporary use register */
1866   Vdbe *v;              /* Statement under construction */
1867 
1868   /* Compute the RHS.   After this step, the table with cursor
1869   ** pExpr->iTable will contains the values that make up the RHS.
1870   */
1871   v = pParse->pVdbe;
1872   assert( v!=0 );       /* OOM detected prior to this routine */
1873   VdbeNoopComment((v, "begin IN expr"));
1874   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
1875 
1876   /* Figure out the affinity to use to create a key from the results
1877   ** of the expression. affinityStr stores a static string suitable for
1878   ** P4 of OP_MakeRecord.
1879   */
1880   affinity = comparisonAffinity(pExpr);
1881 
1882   /* Code the LHS, the <expr> from "<expr> IN (...)".
1883   */
1884   sqlite3ExprCachePush(pParse);
1885   r1 = sqlite3GetTempReg(pParse);
1886   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
1887 
1888   /* If the LHS is NULL, then the result is either false or NULL depending
1889   ** on whether the RHS is empty or not, respectively.
1890   */
1891   if( destIfNull==destIfFalse ){
1892     /* Shortcut for the common case where the false and NULL outcomes are
1893     ** the same. */
1894     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
1895   }else{
1896     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
1897     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
1898     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
1899     sqlite3VdbeJumpHere(v, addr1);
1900   }
1901 
1902   if( eType==IN_INDEX_ROWID ){
1903     /* In this case, the RHS is the ROWID of table b-tree
1904     */
1905     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
1906     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
1907   }else{
1908     /* In this case, the RHS is an index b-tree.
1909     */
1910     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
1911 
1912     /* If the set membership test fails, then the result of the
1913     ** "x IN (...)" expression must be either 0 or NULL. If the set
1914     ** contains no NULL values, then the result is 0. If the set
1915     ** contains one or more NULL values, then the result of the
1916     ** expression is also NULL.
1917     */
1918     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
1919       /* This branch runs if it is known at compile time that the RHS
1920       ** cannot contain NULL values. This happens as the result
1921       ** of a "NOT NULL" constraint in the database schema.
1922       **
1923       ** Also run this branch if NULL is equivalent to FALSE
1924       ** for this particular IN operator.
1925       */
1926       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
1927 
1928     }else{
1929       /* In this branch, the RHS of the IN might contain a NULL and
1930       ** the presence of a NULL on the RHS makes a difference in the
1931       ** outcome.
1932       */
1933       int j1, j2, j3;
1934 
1935       /* First check to see if the LHS is contained in the RHS.  If so,
1936       ** then the presence of NULLs in the RHS does not matter, so jump
1937       ** over all of the code that follows.
1938       */
1939       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
1940 
1941       /* Here we begin generating code that runs if the LHS is not
1942       ** contained within the RHS.  Generate additional code that
1943       ** tests the RHS for NULLs.  If the RHS contains a NULL then
1944       ** jump to destIfNull.  If there are no NULLs in the RHS then
1945       ** jump to destIfFalse.
1946       */
1947       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
1948       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
1949       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
1950       sqlite3VdbeJumpHere(v, j3);
1951       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
1952       sqlite3VdbeJumpHere(v, j2);
1953 
1954       /* Jump to the appropriate target depending on whether or not
1955       ** the RHS contains a NULL
1956       */
1957       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
1958       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
1959 
1960       /* The OP_Found at the top of this branch jumps here when true,
1961       ** causing the overall IN expression evaluation to fall through.
1962       */
1963       sqlite3VdbeJumpHere(v, j1);
1964     }
1965   }
1966   sqlite3ReleaseTempReg(pParse, r1);
1967   sqlite3ExprCachePop(pParse, 1);
1968   VdbeComment((v, "end IN expr"));
1969 }
1970 #endif /* SQLITE_OMIT_SUBQUERY */
1971 
1972 /*
1973 ** Duplicate an 8-byte value
1974 */
1975 static char *dup8bytes(Vdbe *v, const char *in){
1976   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1977   if( out ){
1978     memcpy(out, in, 8);
1979   }
1980   return out;
1981 }
1982 
1983 #ifndef SQLITE_OMIT_FLOATING_POINT
1984 /*
1985 ** Generate an instruction that will put the floating point
1986 ** value described by z[0..n-1] into register iMem.
1987 **
1988 ** The z[] string will probably not be zero-terminated.  But the
1989 ** z[n] character is guaranteed to be something that does not look
1990 ** like the continuation of the number.
1991 */
1992 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
1993   if( ALWAYS(z!=0) ){
1994     double value;
1995     char *zV;
1996     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
1997     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
1998     if( negateFlag ) value = -value;
1999     zV = dup8bytes(v, (char*)&value);
2000     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
2001   }
2002 }
2003 #endif
2004 
2005 
2006 /*
2007 ** Generate an instruction that will put the integer describe by
2008 ** text z[0..n-1] into register iMem.
2009 **
2010 ** Expr.u.zToken is always UTF8 and zero-terminated.
2011 */
2012 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2013   Vdbe *v = pParse->pVdbe;
2014   if( pExpr->flags & EP_IntValue ){
2015     int i = pExpr->u.iValue;
2016     assert( i>=0 );
2017     if( negFlag ) i = -i;
2018     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
2019   }else{
2020     int c;
2021     i64 value;
2022     const char *z = pExpr->u.zToken;
2023     assert( z!=0 );
2024     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2025     if( c==0 || (c==2 && negFlag) ){
2026       char *zV;
2027       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
2028       zV = dup8bytes(v, (char*)&value);
2029       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
2030     }else{
2031 #ifdef SQLITE_OMIT_FLOATING_POINT
2032       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2033 #else
2034       codeReal(v, z, negFlag, iMem);
2035 #endif
2036     }
2037   }
2038 }
2039 
2040 /*
2041 ** Clear a cache entry.
2042 */
2043 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2044   if( p->tempReg ){
2045     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2046       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2047     }
2048     p->tempReg = 0;
2049   }
2050 }
2051 
2052 
2053 /*
2054 ** Record in the column cache that a particular column from a
2055 ** particular table is stored in a particular register.
2056 */
2057 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2058   int i;
2059   int minLru;
2060   int idxLru;
2061   struct yColCache *p;
2062 
2063   assert( iReg>0 );  /* Register numbers are always positive */
2064   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
2065 
2066   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
2067   ** for testing only - to verify that SQLite always gets the same answer
2068   ** with and without the column cache.
2069   */
2070   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
2071 
2072   /* First replace any existing entry.
2073   **
2074   ** Actually, the way the column cache is currently used, we are guaranteed
2075   ** that the object will never already be in cache.  Verify this guarantee.
2076   */
2077 #ifndef NDEBUG
2078   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2079     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2080   }
2081 #endif
2082 
2083   /* Find an empty slot and replace it */
2084   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2085     if( p->iReg==0 ){
2086       p->iLevel = pParse->iCacheLevel;
2087       p->iTable = iTab;
2088       p->iColumn = iCol;
2089       p->iReg = iReg;
2090       p->tempReg = 0;
2091       p->lru = pParse->iCacheCnt++;
2092       return;
2093     }
2094   }
2095 
2096   /* Replace the last recently used */
2097   minLru = 0x7fffffff;
2098   idxLru = -1;
2099   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2100     if( p->lru<minLru ){
2101       idxLru = i;
2102       minLru = p->lru;
2103     }
2104   }
2105   if( ALWAYS(idxLru>=0) ){
2106     p = &pParse->aColCache[idxLru];
2107     p->iLevel = pParse->iCacheLevel;
2108     p->iTable = iTab;
2109     p->iColumn = iCol;
2110     p->iReg = iReg;
2111     p->tempReg = 0;
2112     p->lru = pParse->iCacheCnt++;
2113     return;
2114   }
2115 }
2116 
2117 /*
2118 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2119 ** Purge the range of registers from the column cache.
2120 */
2121 void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2122   int i;
2123   int iLast = iReg + nReg - 1;
2124   struct yColCache *p;
2125   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2126     int r = p->iReg;
2127     if( r>=iReg && r<=iLast ){
2128       cacheEntryClear(pParse, p);
2129       p->iReg = 0;
2130     }
2131   }
2132 }
2133 
2134 /*
2135 ** Remember the current column cache context.  Any new entries added
2136 ** added to the column cache after this call are removed when the
2137 ** corresponding pop occurs.
2138 */
2139 void sqlite3ExprCachePush(Parse *pParse){
2140   pParse->iCacheLevel++;
2141 }
2142 
2143 /*
2144 ** Remove from the column cache any entries that were added since the
2145 ** the previous N Push operations.  In other words, restore the cache
2146 ** to the state it was in N Pushes ago.
2147 */
2148 void sqlite3ExprCachePop(Parse *pParse, int N){
2149   int i;
2150   struct yColCache *p;
2151   assert( N>0 );
2152   assert( pParse->iCacheLevel>=N );
2153   pParse->iCacheLevel -= N;
2154   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2155     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2156       cacheEntryClear(pParse, p);
2157       p->iReg = 0;
2158     }
2159   }
2160 }
2161 
2162 /*
2163 ** When a cached column is reused, make sure that its register is
2164 ** no longer available as a temp register.  ticket #3879:  that same
2165 ** register might be in the cache in multiple places, so be sure to
2166 ** get them all.
2167 */
2168 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
2169   int i;
2170   struct yColCache *p;
2171   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2172     if( p->iReg==iReg ){
2173       p->tempReg = 0;
2174     }
2175   }
2176 }
2177 
2178 /*
2179 ** Generate code to extract the value of the iCol-th column of a table.
2180 */
2181 void sqlite3ExprCodeGetColumnOfTable(
2182   Vdbe *v,        /* The VDBE under construction */
2183   Table *pTab,    /* The table containing the value */
2184   int iTabCur,    /* The cursor for this table */
2185   int iCol,       /* Index of the column to extract */
2186   int regOut      /* Extract the valud into this register */
2187 ){
2188   if( iCol<0 || iCol==pTab->iPKey ){
2189     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
2190   }else{
2191     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2192     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
2193   }
2194   if( iCol>=0 ){
2195     sqlite3ColumnDefault(v, pTab, iCol, regOut);
2196   }
2197 }
2198 
2199 /*
2200 ** Generate code that will extract the iColumn-th column from
2201 ** table pTab and store the column value in a register.  An effort
2202 ** is made to store the column value in register iReg, but this is
2203 ** not guaranteed.  The location of the column value is returned.
2204 **
2205 ** There must be an open cursor to pTab in iTable when this routine
2206 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2207 */
2208 int sqlite3ExprCodeGetColumn(
2209   Parse *pParse,   /* Parsing and code generating context */
2210   Table *pTab,     /* Description of the table we are reading from */
2211   int iColumn,     /* Index of the table column */
2212   int iTable,      /* The cursor pointing to the table */
2213   int iReg,        /* Store results here */
2214   u8 p5            /* P5 value for OP_Column */
2215 ){
2216   Vdbe *v = pParse->pVdbe;
2217   int i;
2218   struct yColCache *p;
2219 
2220   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2221     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2222       p->lru = pParse->iCacheCnt++;
2223       sqlite3ExprCachePinRegister(pParse, p->iReg);
2224       return p->iReg;
2225     }
2226   }
2227   assert( v!=0 );
2228   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2229   if( p5 ){
2230     sqlite3VdbeChangeP5(v, p5);
2231   }else{
2232     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2233   }
2234   return iReg;
2235 }
2236 
2237 /*
2238 ** Clear all column cache entries.
2239 */
2240 void sqlite3ExprCacheClear(Parse *pParse){
2241   int i;
2242   struct yColCache *p;
2243 
2244   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2245     if( p->iReg ){
2246       cacheEntryClear(pParse, p);
2247       p->iReg = 0;
2248     }
2249   }
2250 }
2251 
2252 /*
2253 ** Record the fact that an affinity change has occurred on iCount
2254 ** registers starting with iStart.
2255 */
2256 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2257   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2258 }
2259 
2260 /*
2261 ** Generate code to move content from registers iFrom...iFrom+nReg-1
2262 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2263 */
2264 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2265   int i;
2266   struct yColCache *p;
2267   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
2268   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
2269   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2270     int x = p->iReg;
2271     if( x>=iFrom && x<iFrom+nReg ){
2272       p->iReg += iTo-iFrom;
2273     }
2274   }
2275 }
2276 
2277 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
2278 /*
2279 ** Return true if any register in the range iFrom..iTo (inclusive)
2280 ** is used as part of the column cache.
2281 **
2282 ** This routine is used within assert() and testcase() macros only
2283 ** and does not appear in a normal build.
2284 */
2285 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2286   int i;
2287   struct yColCache *p;
2288   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2289     int r = p->iReg;
2290     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2291   }
2292   return 0;
2293 }
2294 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2295 
2296 /*
2297 ** Generate code into the current Vdbe to evaluate the given
2298 ** expression.  Attempt to store the results in register "target".
2299 ** Return the register where results are stored.
2300 **
2301 ** With this routine, there is no guarantee that results will
2302 ** be stored in target.  The result might be stored in some other
2303 ** register if it is convenient to do so.  The calling function
2304 ** must check the return code and move the results to the desired
2305 ** register.
2306 */
2307 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
2308   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
2309   int op;                   /* The opcode being coded */
2310   int inReg = target;       /* Results stored in register inReg */
2311   int regFree1 = 0;         /* If non-zero free this temporary register */
2312   int regFree2 = 0;         /* If non-zero free this temporary register */
2313   int r1, r2, r3, r4;       /* Various register numbers */
2314   sqlite3 *db = pParse->db; /* The database connection */
2315 
2316   assert( target>0 && target<=pParse->nMem );
2317   if( v==0 ){
2318     assert( pParse->db->mallocFailed );
2319     return 0;
2320   }
2321 
2322   if( pExpr==0 ){
2323     op = TK_NULL;
2324   }else{
2325     op = pExpr->op;
2326   }
2327   switch( op ){
2328     case TK_AGG_COLUMN: {
2329       AggInfo *pAggInfo = pExpr->pAggInfo;
2330       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2331       if( !pAggInfo->directMode ){
2332         assert( pCol->iMem>0 );
2333         inReg = pCol->iMem;
2334         break;
2335       }else if( pAggInfo->useSortingIdx ){
2336         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
2337                               pCol->iSorterColumn, target);
2338         break;
2339       }
2340       /* Otherwise, fall thru into the TK_COLUMN case */
2341     }
2342     case TK_COLUMN: {
2343       if( pExpr->iTable<0 ){
2344         /* This only happens when coding check constraints */
2345         assert( pParse->ckBase>0 );
2346         inReg = pExpr->iColumn + pParse->ckBase;
2347       }else{
2348         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2349                                  pExpr->iColumn, pExpr->iTable, target,
2350                                  pExpr->op2);
2351       }
2352       break;
2353     }
2354     case TK_INTEGER: {
2355       codeInteger(pParse, pExpr, 0, target);
2356       break;
2357     }
2358 #ifndef SQLITE_OMIT_FLOATING_POINT
2359     case TK_FLOAT: {
2360       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2361       codeReal(v, pExpr->u.zToken, 0, target);
2362       break;
2363     }
2364 #endif
2365     case TK_STRING: {
2366       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2367       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
2368       break;
2369     }
2370     case TK_NULL: {
2371       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2372       break;
2373     }
2374 #ifndef SQLITE_OMIT_BLOB_LITERAL
2375     case TK_BLOB: {
2376       int n;
2377       const char *z;
2378       char *zBlob;
2379       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2380       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
2381       assert( pExpr->u.zToken[1]=='\'' );
2382       z = &pExpr->u.zToken[2];
2383       n = sqlite3Strlen30(z) - 1;
2384       assert( z[n]=='\'' );
2385       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2386       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2387       break;
2388     }
2389 #endif
2390     case TK_VARIABLE: {
2391       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2392       assert( pExpr->u.zToken!=0 );
2393       assert( pExpr->u.zToken[0]!=0 );
2394       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
2395       if( pExpr->u.zToken[1]!=0 ){
2396         assert( pExpr->u.zToken[0]=='?'
2397              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
2398         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
2399       }
2400       break;
2401     }
2402     case TK_REGISTER: {
2403       inReg = pExpr->iTable;
2404       break;
2405     }
2406     case TK_AS: {
2407       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2408       break;
2409     }
2410 #ifndef SQLITE_OMIT_CAST
2411     case TK_CAST: {
2412       /* Expressions of the form:   CAST(pLeft AS token) */
2413       int aff, to_op;
2414       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2415       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2416       aff = sqlite3AffinityType(pExpr->u.zToken);
2417       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2418       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
2419       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
2420       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2421       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
2422       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
2423       testcase( to_op==OP_ToText );
2424       testcase( to_op==OP_ToBlob );
2425       testcase( to_op==OP_ToNumeric );
2426       testcase( to_op==OP_ToInt );
2427       testcase( to_op==OP_ToReal );
2428       if( inReg!=target ){
2429         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
2430         inReg = target;
2431       }
2432       sqlite3VdbeAddOp1(v, to_op, inReg);
2433       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2434       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2435       break;
2436     }
2437 #endif /* SQLITE_OMIT_CAST */
2438     case TK_LT:
2439     case TK_LE:
2440     case TK_GT:
2441     case TK_GE:
2442     case TK_NE:
2443     case TK_EQ: {
2444       assert( TK_LT==OP_Lt );
2445       assert( TK_LE==OP_Le );
2446       assert( TK_GT==OP_Gt );
2447       assert( TK_GE==OP_Ge );
2448       assert( TK_EQ==OP_Eq );
2449       assert( TK_NE==OP_Ne );
2450       testcase( op==TK_LT );
2451       testcase( op==TK_LE );
2452       testcase( op==TK_GT );
2453       testcase( op==TK_GE );
2454       testcase( op==TK_EQ );
2455       testcase( op==TK_NE );
2456       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2457       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2458       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2459                   r1, r2, inReg, SQLITE_STOREP2);
2460       testcase( regFree1==0 );
2461       testcase( regFree2==0 );
2462       break;
2463     }
2464     case TK_IS:
2465     case TK_ISNOT: {
2466       testcase( op==TK_IS );
2467       testcase( op==TK_ISNOT );
2468       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2469       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2470       op = (op==TK_IS) ? TK_EQ : TK_NE;
2471       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2472                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
2473       testcase( regFree1==0 );
2474       testcase( regFree2==0 );
2475       break;
2476     }
2477     case TK_AND:
2478     case TK_OR:
2479     case TK_PLUS:
2480     case TK_STAR:
2481     case TK_MINUS:
2482     case TK_REM:
2483     case TK_BITAND:
2484     case TK_BITOR:
2485     case TK_SLASH:
2486     case TK_LSHIFT:
2487     case TK_RSHIFT:
2488     case TK_CONCAT: {
2489       assert( TK_AND==OP_And );
2490       assert( TK_OR==OP_Or );
2491       assert( TK_PLUS==OP_Add );
2492       assert( TK_MINUS==OP_Subtract );
2493       assert( TK_REM==OP_Remainder );
2494       assert( TK_BITAND==OP_BitAnd );
2495       assert( TK_BITOR==OP_BitOr );
2496       assert( TK_SLASH==OP_Divide );
2497       assert( TK_LSHIFT==OP_ShiftLeft );
2498       assert( TK_RSHIFT==OP_ShiftRight );
2499       assert( TK_CONCAT==OP_Concat );
2500       testcase( op==TK_AND );
2501       testcase( op==TK_OR );
2502       testcase( op==TK_PLUS );
2503       testcase( op==TK_MINUS );
2504       testcase( op==TK_REM );
2505       testcase( op==TK_BITAND );
2506       testcase( op==TK_BITOR );
2507       testcase( op==TK_SLASH );
2508       testcase( op==TK_LSHIFT );
2509       testcase( op==TK_RSHIFT );
2510       testcase( op==TK_CONCAT );
2511       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2512       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2513       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2514       testcase( regFree1==0 );
2515       testcase( regFree2==0 );
2516       break;
2517     }
2518     case TK_UMINUS: {
2519       Expr *pLeft = pExpr->pLeft;
2520       assert( pLeft );
2521       if( pLeft->op==TK_INTEGER ){
2522         codeInteger(pParse, pLeft, 1, target);
2523 #ifndef SQLITE_OMIT_FLOATING_POINT
2524       }else if( pLeft->op==TK_FLOAT ){
2525         assert( !ExprHasProperty(pExpr, EP_IntValue) );
2526         codeReal(v, pLeft->u.zToken, 1, target);
2527 #endif
2528       }else{
2529         regFree1 = r1 = sqlite3GetTempReg(pParse);
2530         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2531         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
2532         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2533         testcase( regFree2==0 );
2534       }
2535       inReg = target;
2536       break;
2537     }
2538     case TK_BITNOT:
2539     case TK_NOT: {
2540       assert( TK_BITNOT==OP_BitNot );
2541       assert( TK_NOT==OP_Not );
2542       testcase( op==TK_BITNOT );
2543       testcase( op==TK_NOT );
2544       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2545       testcase( regFree1==0 );
2546       inReg = target;
2547       sqlite3VdbeAddOp2(v, op, r1, inReg);
2548       break;
2549     }
2550     case TK_ISNULL:
2551     case TK_NOTNULL: {
2552       int addr;
2553       assert( TK_ISNULL==OP_IsNull );
2554       assert( TK_NOTNULL==OP_NotNull );
2555       testcase( op==TK_ISNULL );
2556       testcase( op==TK_NOTNULL );
2557       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2558       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2559       testcase( regFree1==0 );
2560       addr = sqlite3VdbeAddOp1(v, op, r1);
2561       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
2562       sqlite3VdbeJumpHere(v, addr);
2563       break;
2564     }
2565     case TK_AGG_FUNCTION: {
2566       AggInfo *pInfo = pExpr->pAggInfo;
2567       if( pInfo==0 ){
2568         assert( !ExprHasProperty(pExpr, EP_IntValue) );
2569         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
2570       }else{
2571         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
2572       }
2573       break;
2574     }
2575     case TK_CONST_FUNC:
2576     case TK_FUNCTION: {
2577       ExprList *pFarg;       /* List of function arguments */
2578       int nFarg;             /* Number of function arguments */
2579       FuncDef *pDef;         /* The function definition object */
2580       int nId;               /* Length of the function name in bytes */
2581       const char *zId;       /* The function name */
2582       int constMask = 0;     /* Mask of function arguments that are constant */
2583       int i;                 /* Loop counter */
2584       u8 enc = ENC(db);      /* The text encoding used by this database */
2585       CollSeq *pColl = 0;    /* A collating sequence */
2586 
2587       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2588       testcase( op==TK_CONST_FUNC );
2589       testcase( op==TK_FUNCTION );
2590       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
2591         pFarg = 0;
2592       }else{
2593         pFarg = pExpr->x.pList;
2594       }
2595       nFarg = pFarg ? pFarg->nExpr : 0;
2596       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2597       zId = pExpr->u.zToken;
2598       nId = sqlite3Strlen30(zId);
2599       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
2600       if( pDef==0 ){
2601         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
2602         break;
2603       }
2604 
2605       /* Attempt a direct implementation of the built-in COALESCE() and
2606       ** IFNULL() functions.  This avoids unnecessary evalation of
2607       ** arguments past the first non-NULL argument.
2608       */
2609       if( pDef->flags & SQLITE_FUNC_COALESCE ){
2610         int endCoalesce = sqlite3VdbeMakeLabel(v);
2611         assert( nFarg>=2 );
2612         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2613         for(i=1; i<nFarg; i++){
2614           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2615           sqlite3ExprCacheRemove(pParse, target, 1);
2616           sqlite3ExprCachePush(pParse);
2617           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2618           sqlite3ExprCachePop(pParse, 1);
2619         }
2620         sqlite3VdbeResolveLabel(v, endCoalesce);
2621         break;
2622       }
2623 
2624 
2625       if( pFarg ){
2626         r1 = sqlite3GetTempRange(pParse, nFarg);
2627 
2628         /* For length() and typeof() functions with a column argument,
2629         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2630         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2631         ** loading.
2632         */
2633         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
2634           u8 exprOp;
2635           assert( nFarg==1 );
2636           assert( pFarg->a[0].pExpr!=0 );
2637           exprOp = pFarg->a[0].pExpr->op;
2638           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
2639             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
2640             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
2641             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
2642             pFarg->a[0].pExpr->op2 = pDef->flags;
2643           }
2644         }
2645 
2646         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
2647         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
2648         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
2649       }else{
2650         r1 = 0;
2651       }
2652 #ifndef SQLITE_OMIT_VIRTUALTABLE
2653       /* Possibly overload the function if the first argument is
2654       ** a virtual table column.
2655       **
2656       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2657       ** second argument, not the first, as the argument to test to
2658       ** see if it is a column in a virtual table.  This is done because
2659       ** the left operand of infix functions (the operand we want to
2660       ** control overloading) ends up as the second argument to the
2661       ** function.  The expression "A glob B" is equivalent to
2662       ** "glob(B,A).  We want to use the A in "A glob B" to test
2663       ** for function overloading.  But we use the B term in "glob(B,A)".
2664       */
2665       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
2666         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
2667       }else if( nFarg>0 ){
2668         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2669       }
2670 #endif
2671       for(i=0; i<nFarg; i++){
2672         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2673           constMask |= (1<<i);
2674         }
2675         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2676           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2677         }
2678       }
2679       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
2680         if( !pColl ) pColl = db->pDfltColl;
2681         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2682       }
2683       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
2684                         (char*)pDef, P4_FUNCDEF);
2685       sqlite3VdbeChangeP5(v, (u8)nFarg);
2686       if( nFarg ){
2687         sqlite3ReleaseTempRange(pParse, r1, nFarg);
2688       }
2689       break;
2690     }
2691 #ifndef SQLITE_OMIT_SUBQUERY
2692     case TK_EXISTS:
2693     case TK_SELECT: {
2694       testcase( op==TK_EXISTS );
2695       testcase( op==TK_SELECT );
2696       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
2697       break;
2698     }
2699     case TK_IN: {
2700       int destIfFalse = sqlite3VdbeMakeLabel(v);
2701       int destIfNull = sqlite3VdbeMakeLabel(v);
2702       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2703       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
2704       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2705       sqlite3VdbeResolveLabel(v, destIfFalse);
2706       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
2707       sqlite3VdbeResolveLabel(v, destIfNull);
2708       break;
2709     }
2710 #endif /* SQLITE_OMIT_SUBQUERY */
2711 
2712 
2713     /*
2714     **    x BETWEEN y AND z
2715     **
2716     ** This is equivalent to
2717     **
2718     **    x>=y AND x<=z
2719     **
2720     ** X is stored in pExpr->pLeft.
2721     ** Y is stored in pExpr->pList->a[0].pExpr.
2722     ** Z is stored in pExpr->pList->a[1].pExpr.
2723     */
2724     case TK_BETWEEN: {
2725       Expr *pLeft = pExpr->pLeft;
2726       struct ExprList_item *pLItem = pExpr->x.pList->a;
2727       Expr *pRight = pLItem->pExpr;
2728 
2729       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
2730       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2731       testcase( regFree1==0 );
2732       testcase( regFree2==0 );
2733       r3 = sqlite3GetTempReg(pParse);
2734       r4 = sqlite3GetTempReg(pParse);
2735       codeCompare(pParse, pLeft, pRight, OP_Ge,
2736                   r1, r2, r3, SQLITE_STOREP2);
2737       pLItem++;
2738       pRight = pLItem->pExpr;
2739       sqlite3ReleaseTempReg(pParse, regFree2);
2740       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2741       testcase( regFree2==0 );
2742       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2743       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
2744       sqlite3ReleaseTempReg(pParse, r3);
2745       sqlite3ReleaseTempReg(pParse, r4);
2746       break;
2747     }
2748     case TK_UPLUS: {
2749       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2750       break;
2751     }
2752 
2753     case TK_TRIGGER: {
2754       /* If the opcode is TK_TRIGGER, then the expression is a reference
2755       ** to a column in the new.* or old.* pseudo-tables available to
2756       ** trigger programs. In this case Expr.iTable is set to 1 for the
2757       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
2758       ** is set to the column of the pseudo-table to read, or to -1 to
2759       ** read the rowid field.
2760       **
2761       ** The expression is implemented using an OP_Param opcode. The p1
2762       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
2763       ** to reference another column of the old.* pseudo-table, where
2764       ** i is the index of the column. For a new.rowid reference, p1 is
2765       ** set to (n+1), where n is the number of columns in each pseudo-table.
2766       ** For a reference to any other column in the new.* pseudo-table, p1
2767       ** is set to (n+2+i), where n and i are as defined previously. For
2768       ** example, if the table on which triggers are being fired is
2769       ** declared as:
2770       **
2771       **   CREATE TABLE t1(a, b);
2772       **
2773       ** Then p1 is interpreted as follows:
2774       **
2775       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
2776       **   p1==1   ->    old.a         p1==4   ->    new.a
2777       **   p1==2   ->    old.b         p1==5   ->    new.b
2778       */
2779       Table *pTab = pExpr->pTab;
2780       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
2781 
2782       assert( pExpr->iTable==0 || pExpr->iTable==1 );
2783       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
2784       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
2785       assert( p1>=0 && p1<(pTab->nCol*2+2) );
2786 
2787       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
2788       VdbeComment((v, "%s.%s -> $%d",
2789         (pExpr->iTable ? "new" : "old"),
2790         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
2791         target
2792       ));
2793 
2794 #ifndef SQLITE_OMIT_FLOATING_POINT
2795       /* If the column has REAL affinity, it may currently be stored as an
2796       ** integer. Use OP_RealAffinity to make sure it is really real.  */
2797       if( pExpr->iColumn>=0
2798        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
2799       ){
2800         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
2801       }
2802 #endif
2803       break;
2804     }
2805 
2806 
2807     /*
2808     ** Form A:
2809     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2810     **
2811     ** Form B:
2812     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2813     **
2814     ** Form A is can be transformed into the equivalent form B as follows:
2815     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
2816     **        WHEN x=eN THEN rN ELSE y END
2817     **
2818     ** X (if it exists) is in pExpr->pLeft.
2819     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
2820     ** ELSE clause and no other term matches, then the result of the
2821     ** exprssion is NULL.
2822     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
2823     **
2824     ** The result of the expression is the Ri for the first matching Ei,
2825     ** or if there is no matching Ei, the ELSE term Y, or if there is
2826     ** no ELSE term, NULL.
2827     */
2828     default: assert( op==TK_CASE ); {
2829       int endLabel;                     /* GOTO label for end of CASE stmt */
2830       int nextCase;                     /* GOTO label for next WHEN clause */
2831       int nExpr;                        /* 2x number of WHEN terms */
2832       int i;                            /* Loop counter */
2833       ExprList *pEList;                 /* List of WHEN terms */
2834       struct ExprList_item *aListelem;  /* Array of WHEN terms */
2835       Expr opCompare;                   /* The X==Ei expression */
2836       Expr cacheX;                      /* Cached expression X */
2837       Expr *pX;                         /* The X expression */
2838       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
2839       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
2840 
2841       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
2842       assert((pExpr->x.pList->nExpr % 2) == 0);
2843       assert(pExpr->x.pList->nExpr > 0);
2844       pEList = pExpr->x.pList;
2845       aListelem = pEList->a;
2846       nExpr = pEList->nExpr;
2847       endLabel = sqlite3VdbeMakeLabel(v);
2848       if( (pX = pExpr->pLeft)!=0 ){
2849         cacheX = *pX;
2850         testcase( pX->op==TK_COLUMN );
2851         testcase( pX->op==TK_REGISTER );
2852         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
2853         testcase( regFree1==0 );
2854         cacheX.op = TK_REGISTER;
2855         opCompare.op = TK_EQ;
2856         opCompare.pLeft = &cacheX;
2857         pTest = &opCompare;
2858         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
2859         ** The value in regFree1 might get SCopy-ed into the file result.
2860         ** So make sure that the regFree1 register is not reused for other
2861         ** purposes and possibly overwritten.  */
2862         regFree1 = 0;
2863       }
2864       for(i=0; i<nExpr; i=i+2){
2865         sqlite3ExprCachePush(pParse);
2866         if( pX ){
2867           assert( pTest!=0 );
2868           opCompare.pRight = aListelem[i].pExpr;
2869         }else{
2870           pTest = aListelem[i].pExpr;
2871         }
2872         nextCase = sqlite3VdbeMakeLabel(v);
2873         testcase( pTest->op==TK_COLUMN );
2874         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2875         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2876         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
2877         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
2878         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2879         sqlite3ExprCachePop(pParse, 1);
2880         sqlite3VdbeResolveLabel(v, nextCase);
2881       }
2882       if( pExpr->pRight ){
2883         sqlite3ExprCachePush(pParse);
2884         sqlite3ExprCode(pParse, pExpr->pRight, target);
2885         sqlite3ExprCachePop(pParse, 1);
2886       }else{
2887         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2888       }
2889       assert( db->mallocFailed || pParse->nErr>0
2890            || pParse->iCacheLevel==iCacheLevel );
2891       sqlite3VdbeResolveLabel(v, endLabel);
2892       break;
2893     }
2894 #ifndef SQLITE_OMIT_TRIGGER
2895     case TK_RAISE: {
2896       assert( pExpr->affinity==OE_Rollback
2897            || pExpr->affinity==OE_Abort
2898            || pExpr->affinity==OE_Fail
2899            || pExpr->affinity==OE_Ignore
2900       );
2901       if( !pParse->pTriggerTab ){
2902         sqlite3ErrorMsg(pParse,
2903                        "RAISE() may only be used within a trigger-program");
2904         return 0;
2905       }
2906       if( pExpr->affinity==OE_Abort ){
2907         sqlite3MayAbort(pParse);
2908       }
2909       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2910       if( pExpr->affinity==OE_Ignore ){
2911         sqlite3VdbeAddOp4(
2912             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
2913       }else{
2914         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
2915       }
2916 
2917       break;
2918     }
2919 #endif
2920   }
2921   sqlite3ReleaseTempReg(pParse, regFree1);
2922   sqlite3ReleaseTempReg(pParse, regFree2);
2923   return inReg;
2924 }
2925 
2926 /*
2927 ** Generate code to evaluate an expression and store the results
2928 ** into a register.  Return the register number where the results
2929 ** are stored.
2930 **
2931 ** If the register is a temporary register that can be deallocated,
2932 ** then write its number into *pReg.  If the result register is not
2933 ** a temporary, then set *pReg to zero.
2934 */
2935 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
2936   int r1 = sqlite3GetTempReg(pParse);
2937   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2938   if( r2==r1 ){
2939     *pReg = r1;
2940   }else{
2941     sqlite3ReleaseTempReg(pParse, r1);
2942     *pReg = 0;
2943   }
2944   return r2;
2945 }
2946 
2947 /*
2948 ** Generate code that will evaluate expression pExpr and store the
2949 ** results in register target.  The results are guaranteed to appear
2950 ** in register target.
2951 */
2952 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
2953   int inReg;
2954 
2955   assert( target>0 && target<=pParse->nMem );
2956   if( pExpr && pExpr->op==TK_REGISTER ){
2957     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
2958   }else{
2959     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2960     assert( pParse->pVdbe || pParse->db->mallocFailed );
2961     if( inReg!=target && pParse->pVdbe ){
2962       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
2963     }
2964   }
2965   return target;
2966 }
2967 
2968 /*
2969 ** Generate code that evalutes the given expression and puts the result
2970 ** in register target.
2971 **
2972 ** Also make a copy of the expression results into another "cache" register
2973 ** and modify the expression so that the next time it is evaluated,
2974 ** the result is a copy of the cache register.
2975 **
2976 ** This routine is used for expressions that are used multiple
2977 ** times.  They are evaluated once and the results of the expression
2978 ** are reused.
2979 */
2980 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
2981   Vdbe *v = pParse->pVdbe;
2982   int inReg;
2983   inReg = sqlite3ExprCode(pParse, pExpr, target);
2984   assert( target>0 );
2985   /* This routine is called for terms to INSERT or UPDATE.  And the only
2986   ** other place where expressions can be converted into TK_REGISTER is
2987   ** in WHERE clause processing.  So as currently implemented, there is
2988   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
2989   ** keep the ALWAYS() in case the conditions above change with future
2990   ** modifications or enhancements. */
2991   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
2992     int iMem;
2993     iMem = ++pParse->nMem;
2994     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
2995     pExpr->iTable = iMem;
2996     pExpr->op2 = pExpr->op;
2997     pExpr->op = TK_REGISTER;
2998   }
2999   return inReg;
3000 }
3001 
3002 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
3003 /*
3004 ** Generate a human-readable explanation of an expression tree.
3005 */
3006 void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
3007   int op;                   /* The opcode being coded */
3008   const char *zBinOp = 0;   /* Binary operator */
3009   const char *zUniOp = 0;   /* Unary operator */
3010   if( pExpr==0 ){
3011     op = TK_NULL;
3012   }else{
3013     op = pExpr->op;
3014   }
3015   switch( op ){
3016     case TK_AGG_COLUMN: {
3017       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
3018             pExpr->iTable, pExpr->iColumn);
3019       break;
3020     }
3021     case TK_COLUMN: {
3022       if( pExpr->iTable<0 ){
3023         /* This only happens when coding check constraints */
3024         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
3025       }else{
3026         sqlite3ExplainPrintf(pOut, "{%d:%d}",
3027                              pExpr->iTable, pExpr->iColumn);
3028       }
3029       break;
3030     }
3031     case TK_INTEGER: {
3032       if( pExpr->flags & EP_IntValue ){
3033         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
3034       }else{
3035         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
3036       }
3037       break;
3038     }
3039 #ifndef SQLITE_OMIT_FLOATING_POINT
3040     case TK_FLOAT: {
3041       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
3042       break;
3043     }
3044 #endif
3045     case TK_STRING: {
3046       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
3047       break;
3048     }
3049     case TK_NULL: {
3050       sqlite3ExplainPrintf(pOut,"NULL");
3051       break;
3052     }
3053 #ifndef SQLITE_OMIT_BLOB_LITERAL
3054     case TK_BLOB: {
3055       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
3056       break;
3057     }
3058 #endif
3059     case TK_VARIABLE: {
3060       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
3061                            pExpr->u.zToken, pExpr->iColumn);
3062       break;
3063     }
3064     case TK_REGISTER: {
3065       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
3066       break;
3067     }
3068     case TK_AS: {
3069       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3070       break;
3071     }
3072 #ifndef SQLITE_OMIT_CAST
3073     case TK_CAST: {
3074       /* Expressions of the form:   CAST(pLeft AS token) */
3075       const char *zAff = "unk";
3076       switch( sqlite3AffinityType(pExpr->u.zToken) ){
3077         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
3078         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
3079         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
3080         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
3081         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
3082       }
3083       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
3084       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3085       sqlite3ExplainPrintf(pOut, ")");
3086       break;
3087     }
3088 #endif /* SQLITE_OMIT_CAST */
3089     case TK_LT:      zBinOp = "LT";     break;
3090     case TK_LE:      zBinOp = "LE";     break;
3091     case TK_GT:      zBinOp = "GT";     break;
3092     case TK_GE:      zBinOp = "GE";     break;
3093     case TK_NE:      zBinOp = "NE";     break;
3094     case TK_EQ:      zBinOp = "EQ";     break;
3095     case TK_IS:      zBinOp = "IS";     break;
3096     case TK_ISNOT:   zBinOp = "ISNOT";  break;
3097     case TK_AND:     zBinOp = "AND";    break;
3098     case TK_OR:      zBinOp = "OR";     break;
3099     case TK_PLUS:    zBinOp = "ADD";    break;
3100     case TK_STAR:    zBinOp = "MUL";    break;
3101     case TK_MINUS:   zBinOp = "SUB";    break;
3102     case TK_REM:     zBinOp = "REM";    break;
3103     case TK_BITAND:  zBinOp = "BITAND"; break;
3104     case TK_BITOR:   zBinOp = "BITOR";  break;
3105     case TK_SLASH:   zBinOp = "DIV";    break;
3106     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
3107     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
3108     case TK_CONCAT:  zBinOp = "CONCAT"; break;
3109 
3110     case TK_UMINUS:  zUniOp = "UMINUS"; break;
3111     case TK_UPLUS:   zUniOp = "UPLUS";  break;
3112     case TK_BITNOT:  zUniOp = "BITNOT"; break;
3113     case TK_NOT:     zUniOp = "NOT";    break;
3114     case TK_ISNULL:  zUniOp = "ISNULL"; break;
3115     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
3116 
3117     case TK_AGG_FUNCTION:
3118     case TK_CONST_FUNC:
3119     case TK_FUNCTION: {
3120       ExprList *pFarg;       /* List of function arguments */
3121       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
3122         pFarg = 0;
3123       }else{
3124         pFarg = pExpr->x.pList;
3125       }
3126       if( op==TK_AGG_FUNCTION ){
3127         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
3128                              pExpr->op2, pExpr->u.zToken);
3129       }else{
3130         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
3131       }
3132       if( pFarg ){
3133         sqlite3ExplainExprList(pOut, pFarg);
3134       }
3135       sqlite3ExplainPrintf(pOut, ")");
3136       break;
3137     }
3138 #ifndef SQLITE_OMIT_SUBQUERY
3139     case TK_EXISTS: {
3140       sqlite3ExplainPrintf(pOut, "EXISTS(");
3141       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3142       sqlite3ExplainPrintf(pOut,")");
3143       break;
3144     }
3145     case TK_SELECT: {
3146       sqlite3ExplainPrintf(pOut, "(");
3147       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3148       sqlite3ExplainPrintf(pOut, ")");
3149       break;
3150     }
3151     case TK_IN: {
3152       sqlite3ExplainPrintf(pOut, "IN(");
3153       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3154       sqlite3ExplainPrintf(pOut, ",");
3155       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3156         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3157       }else{
3158         sqlite3ExplainExprList(pOut, pExpr->x.pList);
3159       }
3160       sqlite3ExplainPrintf(pOut, ")");
3161       break;
3162     }
3163 #endif /* SQLITE_OMIT_SUBQUERY */
3164 
3165     /*
3166     **    x BETWEEN y AND z
3167     **
3168     ** This is equivalent to
3169     **
3170     **    x>=y AND x<=z
3171     **
3172     ** X is stored in pExpr->pLeft.
3173     ** Y is stored in pExpr->pList->a[0].pExpr.
3174     ** Z is stored in pExpr->pList->a[1].pExpr.
3175     */
3176     case TK_BETWEEN: {
3177       Expr *pX = pExpr->pLeft;
3178       Expr *pY = pExpr->x.pList->a[0].pExpr;
3179       Expr *pZ = pExpr->x.pList->a[1].pExpr;
3180       sqlite3ExplainPrintf(pOut, "BETWEEN(");
3181       sqlite3ExplainExpr(pOut, pX);
3182       sqlite3ExplainPrintf(pOut, ",");
3183       sqlite3ExplainExpr(pOut, pY);
3184       sqlite3ExplainPrintf(pOut, ",");
3185       sqlite3ExplainExpr(pOut, pZ);
3186       sqlite3ExplainPrintf(pOut, ")");
3187       break;
3188     }
3189     case TK_TRIGGER: {
3190       /* If the opcode is TK_TRIGGER, then the expression is a reference
3191       ** to a column in the new.* or old.* pseudo-tables available to
3192       ** trigger programs. In this case Expr.iTable is set to 1 for the
3193       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3194       ** is set to the column of the pseudo-table to read, or to -1 to
3195       ** read the rowid field.
3196       */
3197       sqlite3ExplainPrintf(pOut, "%s(%d)",
3198           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
3199       break;
3200     }
3201     case TK_CASE: {
3202       sqlite3ExplainPrintf(pOut, "CASE(");
3203       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3204       sqlite3ExplainPrintf(pOut, ",");
3205       sqlite3ExplainExprList(pOut, pExpr->x.pList);
3206       break;
3207     }
3208 #ifndef SQLITE_OMIT_TRIGGER
3209     case TK_RAISE: {
3210       const char *zType = "unk";
3211       switch( pExpr->affinity ){
3212         case OE_Rollback:   zType = "rollback";  break;
3213         case OE_Abort:      zType = "abort";     break;
3214         case OE_Fail:       zType = "fail";      break;
3215         case OE_Ignore:     zType = "ignore";    break;
3216       }
3217       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
3218       break;
3219     }
3220 #endif
3221   }
3222   if( zBinOp ){
3223     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
3224     sqlite3ExplainExpr(pOut, pExpr->pLeft);
3225     sqlite3ExplainPrintf(pOut,",");
3226     sqlite3ExplainExpr(pOut, pExpr->pRight);
3227     sqlite3ExplainPrintf(pOut,")");
3228   }else if( zUniOp ){
3229     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
3230     sqlite3ExplainExpr(pOut, pExpr->pLeft);
3231     sqlite3ExplainPrintf(pOut,")");
3232   }
3233 }
3234 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
3235 
3236 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
3237 /*
3238 ** Generate a human-readable explanation of an expression list.
3239 */
3240 void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
3241   int i;
3242   if( pList==0 || pList->nExpr==0 ){
3243     sqlite3ExplainPrintf(pOut, "(empty-list)");
3244     return;
3245   }else if( pList->nExpr==1 ){
3246     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
3247   }else{
3248     sqlite3ExplainPush(pOut);
3249     for(i=0; i<pList->nExpr; i++){
3250       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
3251       sqlite3ExplainPush(pOut);
3252       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
3253       sqlite3ExplainPop(pOut);
3254       if( i<pList->nExpr-1 ){
3255         sqlite3ExplainNL(pOut);
3256       }
3257     }
3258     sqlite3ExplainPop(pOut);
3259   }
3260 }
3261 #endif /* SQLITE_DEBUG */
3262 
3263 /*
3264 ** Return TRUE if pExpr is an constant expression that is appropriate
3265 ** for factoring out of a loop.  Appropriate expressions are:
3266 **
3267 **    *  Any expression that evaluates to two or more opcodes.
3268 **
3269 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
3270 **       or OP_Variable that does not need to be placed in a
3271 **       specific register.
3272 **
3273 ** There is no point in factoring out single-instruction constant
3274 ** expressions that need to be placed in a particular register.
3275 ** We could factor them out, but then we would end up adding an
3276 ** OP_SCopy instruction to move the value into the correct register
3277 ** later.  We might as well just use the original instruction and
3278 ** avoid the OP_SCopy.
3279 */
3280 static int isAppropriateForFactoring(Expr *p){
3281   if( !sqlite3ExprIsConstantNotJoin(p) ){
3282     return 0;  /* Only constant expressions are appropriate for factoring */
3283   }
3284   if( (p->flags & EP_FixedDest)==0 ){
3285     return 1;  /* Any constant without a fixed destination is appropriate */
3286   }
3287   while( p->op==TK_UPLUS ) p = p->pLeft;
3288   switch( p->op ){
3289 #ifndef SQLITE_OMIT_BLOB_LITERAL
3290     case TK_BLOB:
3291 #endif
3292     case TK_VARIABLE:
3293     case TK_INTEGER:
3294     case TK_FLOAT:
3295     case TK_NULL:
3296     case TK_STRING: {
3297       testcase( p->op==TK_BLOB );
3298       testcase( p->op==TK_VARIABLE );
3299       testcase( p->op==TK_INTEGER );
3300       testcase( p->op==TK_FLOAT );
3301       testcase( p->op==TK_NULL );
3302       testcase( p->op==TK_STRING );
3303       /* Single-instruction constants with a fixed destination are
3304       ** better done in-line.  If we factor them, they will just end
3305       ** up generating an OP_SCopy to move the value to the destination
3306       ** register. */
3307       return 0;
3308     }
3309     case TK_UMINUS: {
3310       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
3311         return 0;
3312       }
3313       break;
3314     }
3315     default: {
3316       break;
3317     }
3318   }
3319   return 1;
3320 }
3321 
3322 /*
3323 ** If pExpr is a constant expression that is appropriate for
3324 ** factoring out of a loop, then evaluate the expression
3325 ** into a register and convert the expression into a TK_REGISTER
3326 ** expression.
3327 */
3328 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
3329   Parse *pParse = pWalker->pParse;
3330   switch( pExpr->op ){
3331     case TK_IN:
3332     case TK_REGISTER: {
3333       return WRC_Prune;
3334     }
3335     case TK_FUNCTION:
3336     case TK_AGG_FUNCTION:
3337     case TK_CONST_FUNC: {
3338       /* The arguments to a function have a fixed destination.
3339       ** Mark them this way to avoid generated unneeded OP_SCopy
3340       ** instructions.
3341       */
3342       ExprList *pList = pExpr->x.pList;
3343       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3344       if( pList ){
3345         int i = pList->nExpr;
3346         struct ExprList_item *pItem = pList->a;
3347         for(; i>0; i--, pItem++){
3348           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
3349         }
3350       }
3351       break;
3352     }
3353   }
3354   if( isAppropriateForFactoring(pExpr) ){
3355     int r1 = ++pParse->nMem;
3356     int r2;
3357     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3358     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
3359     pExpr->op2 = pExpr->op;
3360     pExpr->op = TK_REGISTER;
3361     pExpr->iTable = r2;
3362     return WRC_Prune;
3363   }
3364   return WRC_Continue;
3365 }
3366 
3367 /*
3368 ** Preevaluate constant subexpressions within pExpr and store the
3369 ** results in registers.  Modify pExpr so that the constant subexpresions
3370 ** are TK_REGISTER opcodes that refer to the precomputed values.
3371 **
3372 ** This routine is a no-op if the jump to the cookie-check code has
3373 ** already occur.  Since the cookie-check jump is generated prior to
3374 ** any other serious processing, this check ensures that there is no
3375 ** way to accidently bypass the constant initializations.
3376 **
3377 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
3378 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
3379 ** interface.  This allows test logic to verify that the same answer is
3380 ** obtained for queries regardless of whether or not constants are
3381 ** precomputed into registers or if they are inserted in-line.
3382 */
3383 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
3384   Walker w;
3385   if( pParse->cookieGoto ) return;
3386   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
3387   w.xExprCallback = evalConstExpr;
3388   w.xSelectCallback = 0;
3389   w.pParse = pParse;
3390   sqlite3WalkExpr(&w, pExpr);
3391 }
3392 
3393 
3394 /*
3395 ** Generate code that pushes the value of every element of the given
3396 ** expression list into a sequence of registers beginning at target.
3397 **
3398 ** Return the number of elements evaluated.
3399 */
3400 int sqlite3ExprCodeExprList(
3401   Parse *pParse,     /* Parsing context */
3402   ExprList *pList,   /* The expression list to be coded */
3403   int target,        /* Where to write results */
3404   int doHardCopy     /* Make a hard copy of every element */
3405 ){
3406   struct ExprList_item *pItem;
3407   int i, n;
3408   assert( pList!=0 );
3409   assert( target>0 );
3410   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
3411   n = pList->nExpr;
3412   for(pItem=pList->a, i=0; i<n; i++, pItem++){
3413     Expr *pExpr = pItem->pExpr;
3414     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3415     if( inReg!=target+i ){
3416       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
3417                         inReg, target+i);
3418     }
3419   }
3420   return n;
3421 }
3422 
3423 /*
3424 ** Generate code for a BETWEEN operator.
3425 **
3426 **    x BETWEEN y AND z
3427 **
3428 ** The above is equivalent to
3429 **
3430 **    x>=y AND x<=z
3431 **
3432 ** Code it as such, taking care to do the common subexpression
3433 ** elementation of x.
3434 */
3435 static void exprCodeBetween(
3436   Parse *pParse,    /* Parsing and code generating context */
3437   Expr *pExpr,      /* The BETWEEN expression */
3438   int dest,         /* Jump here if the jump is taken */
3439   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
3440   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
3441 ){
3442   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
3443   Expr compLeft;    /* The  x>=y  term */
3444   Expr compRight;   /* The  x<=z  term */
3445   Expr exprX;       /* The  x  subexpression */
3446   int regFree1 = 0; /* Temporary use register */
3447 
3448   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3449   exprX = *pExpr->pLeft;
3450   exprAnd.op = TK_AND;
3451   exprAnd.pLeft = &compLeft;
3452   exprAnd.pRight = &compRight;
3453   compLeft.op = TK_GE;
3454   compLeft.pLeft = &exprX;
3455   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3456   compRight.op = TK_LE;
3457   compRight.pLeft = &exprX;
3458   compRight.pRight = pExpr->x.pList->a[1].pExpr;
3459   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
3460   exprX.op = TK_REGISTER;
3461   if( jumpIfTrue ){
3462     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
3463   }else{
3464     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3465   }
3466   sqlite3ReleaseTempReg(pParse, regFree1);
3467 
3468   /* Ensure adequate test coverage */
3469   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
3470   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
3471   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
3472   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
3473   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
3474   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
3475   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
3476   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
3477 }
3478 
3479 /*
3480 ** Generate code for a boolean expression such that a jump is made
3481 ** to the label "dest" if the expression is true but execution
3482 ** continues straight thru if the expression is false.
3483 **
3484 ** If the expression evaluates to NULL (neither true nor false), then
3485 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3486 **
3487 ** This code depends on the fact that certain token values (ex: TK_EQ)
3488 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3489 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3490 ** the make process cause these values to align.  Assert()s in the code
3491 ** below verify that the numbers are aligned correctly.
3492 */
3493 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3494   Vdbe *v = pParse->pVdbe;
3495   int op = 0;
3496   int regFree1 = 0;
3497   int regFree2 = 0;
3498   int r1, r2;
3499 
3500   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3501   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
3502   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3503   op = pExpr->op;
3504   switch( op ){
3505     case TK_AND: {
3506       int d2 = sqlite3VdbeMakeLabel(v);
3507       testcase( jumpIfNull==0 );
3508       sqlite3ExprCachePush(pParse);
3509       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
3510       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3511       sqlite3VdbeResolveLabel(v, d2);
3512       sqlite3ExprCachePop(pParse, 1);
3513       break;
3514     }
3515     case TK_OR: {
3516       testcase( jumpIfNull==0 );
3517       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3518       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3519       break;
3520     }
3521     case TK_NOT: {
3522       testcase( jumpIfNull==0 );
3523       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3524       break;
3525     }
3526     case TK_LT:
3527     case TK_LE:
3528     case TK_GT:
3529     case TK_GE:
3530     case TK_NE:
3531     case TK_EQ: {
3532       assert( TK_LT==OP_Lt );
3533       assert( TK_LE==OP_Le );
3534       assert( TK_GT==OP_Gt );
3535       assert( TK_GE==OP_Ge );
3536       assert( TK_EQ==OP_Eq );
3537       assert( TK_NE==OP_Ne );
3538       testcase( op==TK_LT );
3539       testcase( op==TK_LE );
3540       testcase( op==TK_GT );
3541       testcase( op==TK_GE );
3542       testcase( op==TK_EQ );
3543       testcase( op==TK_NE );
3544       testcase( jumpIfNull==0 );
3545       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3546       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3547       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3548                   r1, r2, dest, jumpIfNull);
3549       testcase( regFree1==0 );
3550       testcase( regFree2==0 );
3551       break;
3552     }
3553     case TK_IS:
3554     case TK_ISNOT: {
3555       testcase( op==TK_IS );
3556       testcase( op==TK_ISNOT );
3557       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3558       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3559       op = (op==TK_IS) ? TK_EQ : TK_NE;
3560       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3561                   r1, r2, dest, SQLITE_NULLEQ);
3562       testcase( regFree1==0 );
3563       testcase( regFree2==0 );
3564       break;
3565     }
3566     case TK_ISNULL:
3567     case TK_NOTNULL: {
3568       assert( TK_ISNULL==OP_IsNull );
3569       assert( TK_NOTNULL==OP_NotNull );
3570       testcase( op==TK_ISNULL );
3571       testcase( op==TK_NOTNULL );
3572       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3573       sqlite3VdbeAddOp2(v, op, r1, dest);
3574       testcase( regFree1==0 );
3575       break;
3576     }
3577     case TK_BETWEEN: {
3578       testcase( jumpIfNull==0 );
3579       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3580       break;
3581     }
3582 #ifndef SQLITE_OMIT_SUBQUERY
3583     case TK_IN: {
3584       int destIfFalse = sqlite3VdbeMakeLabel(v);
3585       int destIfNull = jumpIfNull ? dest : destIfFalse;
3586       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3587       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
3588       sqlite3VdbeResolveLabel(v, destIfFalse);
3589       break;
3590     }
3591 #endif
3592     default: {
3593       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3594       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3595       testcase( regFree1==0 );
3596       testcase( jumpIfNull==0 );
3597       break;
3598     }
3599   }
3600   sqlite3ReleaseTempReg(pParse, regFree1);
3601   sqlite3ReleaseTempReg(pParse, regFree2);
3602 }
3603 
3604 /*
3605 ** Generate code for a boolean expression such that a jump is made
3606 ** to the label "dest" if the expression is false but execution
3607 ** continues straight thru if the expression is true.
3608 **
3609 ** If the expression evaluates to NULL (neither true nor false) then
3610 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3611 ** is 0.
3612 */
3613 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3614   Vdbe *v = pParse->pVdbe;
3615   int op = 0;
3616   int regFree1 = 0;
3617   int regFree2 = 0;
3618   int r1, r2;
3619 
3620   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3621   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
3622   if( pExpr==0 )    return;
3623 
3624   /* The value of pExpr->op and op are related as follows:
3625   **
3626   **       pExpr->op            op
3627   **       ---------          ----------
3628   **       TK_ISNULL          OP_NotNull
3629   **       TK_NOTNULL         OP_IsNull
3630   **       TK_NE              OP_Eq
3631   **       TK_EQ              OP_Ne
3632   **       TK_GT              OP_Le
3633   **       TK_LE              OP_Gt
3634   **       TK_GE              OP_Lt
3635   **       TK_LT              OP_Ge
3636   **
3637   ** For other values of pExpr->op, op is undefined and unused.
3638   ** The value of TK_ and OP_ constants are arranged such that we
3639   ** can compute the mapping above using the following expression.
3640   ** Assert()s verify that the computation is correct.
3641   */
3642   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3643 
3644   /* Verify correct alignment of TK_ and OP_ constants
3645   */
3646   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3647   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3648   assert( pExpr->op!=TK_NE || op==OP_Eq );
3649   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3650   assert( pExpr->op!=TK_LT || op==OP_Ge );
3651   assert( pExpr->op!=TK_LE || op==OP_Gt );
3652   assert( pExpr->op!=TK_GT || op==OP_Le );
3653   assert( pExpr->op!=TK_GE || op==OP_Lt );
3654 
3655   switch( pExpr->op ){
3656     case TK_AND: {
3657       testcase( jumpIfNull==0 );
3658       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3659       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3660       break;
3661     }
3662     case TK_OR: {
3663       int d2 = sqlite3VdbeMakeLabel(v);
3664       testcase( jumpIfNull==0 );
3665       sqlite3ExprCachePush(pParse);
3666       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
3667       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3668       sqlite3VdbeResolveLabel(v, d2);
3669       sqlite3ExprCachePop(pParse, 1);
3670       break;
3671     }
3672     case TK_NOT: {
3673       testcase( jumpIfNull==0 );
3674       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3675       break;
3676     }
3677     case TK_LT:
3678     case TK_LE:
3679     case TK_GT:
3680     case TK_GE:
3681     case TK_NE:
3682     case TK_EQ: {
3683       testcase( op==TK_LT );
3684       testcase( op==TK_LE );
3685       testcase( op==TK_GT );
3686       testcase( op==TK_GE );
3687       testcase( op==TK_EQ );
3688       testcase( op==TK_NE );
3689       testcase( jumpIfNull==0 );
3690       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3691       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3692       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3693                   r1, r2, dest, jumpIfNull);
3694       testcase( regFree1==0 );
3695       testcase( regFree2==0 );
3696       break;
3697     }
3698     case TK_IS:
3699     case TK_ISNOT: {
3700       testcase( pExpr->op==TK_IS );
3701       testcase( pExpr->op==TK_ISNOT );
3702       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3703       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3704       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3705       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3706                   r1, r2, dest, SQLITE_NULLEQ);
3707       testcase( regFree1==0 );
3708       testcase( regFree2==0 );
3709       break;
3710     }
3711     case TK_ISNULL:
3712     case TK_NOTNULL: {
3713       testcase( op==TK_ISNULL );
3714       testcase( op==TK_NOTNULL );
3715       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3716       sqlite3VdbeAddOp2(v, op, r1, dest);
3717       testcase( regFree1==0 );
3718       break;
3719     }
3720     case TK_BETWEEN: {
3721       testcase( jumpIfNull==0 );
3722       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3723       break;
3724     }
3725 #ifndef SQLITE_OMIT_SUBQUERY
3726     case TK_IN: {
3727       if( jumpIfNull ){
3728         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3729       }else{
3730         int destIfNull = sqlite3VdbeMakeLabel(v);
3731         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3732         sqlite3VdbeResolveLabel(v, destIfNull);
3733       }
3734       break;
3735     }
3736 #endif
3737     default: {
3738       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3739       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3740       testcase( regFree1==0 );
3741       testcase( jumpIfNull==0 );
3742       break;
3743     }
3744   }
3745   sqlite3ReleaseTempReg(pParse, regFree1);
3746   sqlite3ReleaseTempReg(pParse, regFree2);
3747 }
3748 
3749 /*
3750 ** Do a deep comparison of two expression trees.  Return 0 if the two
3751 ** expressions are completely identical.  Return 1 if they differ only
3752 ** by a COLLATE operator at the top level.  Return 2 if there are differences
3753 ** other than the top-level COLLATE operator.
3754 **
3755 ** Sometimes this routine will return 2 even if the two expressions
3756 ** really are equivalent.  If we cannot prove that the expressions are
3757 ** identical, we return 2 just to be safe.  So if this routine
3758 ** returns 2, then you do not really know for certain if the two
3759 ** expressions are the same.  But if you get a 0 or 1 return, then you
3760 ** can be sure the expressions are the same.  In the places where
3761 ** this routine is used, it does not hurt to get an extra 2 - that
3762 ** just might result in some slightly slower code.  But returning
3763 ** an incorrect 0 or 1 could lead to a malfunction.
3764 */
3765 int sqlite3ExprCompare(Expr *pA, Expr *pB){
3766   if( pA==0||pB==0 ){
3767     return pB==pA ? 0 : 2;
3768   }
3769   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
3770   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
3771   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
3772     return 2;
3773   }
3774   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
3775   if( pA->op!=pB->op ) return 2;
3776   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
3777   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
3778   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
3779   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
3780   if( ExprHasProperty(pA, EP_IntValue) ){
3781     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
3782       return 2;
3783     }
3784   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
3785     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
3786     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
3787       return 2;
3788     }
3789   }
3790   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
3791   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
3792   return 0;
3793 }
3794 
3795 /*
3796 ** Compare two ExprList objects.  Return 0 if they are identical and
3797 ** non-zero if they differ in any way.
3798 **
3799 ** This routine might return non-zero for equivalent ExprLists.  The
3800 ** only consequence will be disabled optimizations.  But this routine
3801 ** must never return 0 if the two ExprList objects are different, or
3802 ** a malfunction will result.
3803 **
3804 ** Two NULL pointers are considered to be the same.  But a NULL pointer
3805 ** always differs from a non-NULL pointer.
3806 */
3807 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
3808   int i;
3809   if( pA==0 && pB==0 ) return 0;
3810   if( pA==0 || pB==0 ) return 1;
3811   if( pA->nExpr!=pB->nExpr ) return 1;
3812   for(i=0; i<pA->nExpr; i++){
3813     Expr *pExprA = pA->a[i].pExpr;
3814     Expr *pExprB = pB->a[i].pExpr;
3815     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
3816     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
3817   }
3818   return 0;
3819 }
3820 
3821 /*
3822 ** An instance of the following structure is used by the tree walker
3823 ** to count references to table columns in the arguments of an
3824 ** aggregate function, in order to implement the
3825 ** sqlite3FunctionThisSrc() routine.
3826 */
3827 struct SrcCount {
3828   SrcList *pSrc;   /* One particular FROM clause in a nested query */
3829   int nThis;       /* Number of references to columns in pSrcList */
3830   int nOther;      /* Number of references to columns in other FROM clauses */
3831 };
3832 
3833 /*
3834 ** Count the number of references to columns.
3835 */
3836 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
3837   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
3838   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
3839   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
3840   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
3841   ** NEVER() will need to be removed. */
3842   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
3843     int i;
3844     struct SrcCount *p = pWalker->u.pSrcCount;
3845     SrcList *pSrc = p->pSrc;
3846     for(i=0; i<pSrc->nSrc; i++){
3847       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
3848     }
3849     if( i<pSrc->nSrc ){
3850       p->nThis++;
3851     }else{
3852       p->nOther++;
3853     }
3854   }
3855   return WRC_Continue;
3856 }
3857 
3858 /*
3859 ** Determine if any of the arguments to the pExpr Function reference
3860 ** pSrcList.  Return true if they do.  Also return true if the function
3861 ** has no arguments or has only constant arguments.  Return false if pExpr
3862 ** references columns but not columns of tables found in pSrcList.
3863 */
3864 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
3865   Walker w;
3866   struct SrcCount cnt;
3867   assert( pExpr->op==TK_AGG_FUNCTION );
3868   memset(&w, 0, sizeof(w));
3869   w.xExprCallback = exprSrcCount;
3870   w.u.pSrcCount = &cnt;
3871   cnt.pSrc = pSrcList;
3872   cnt.nThis = 0;
3873   cnt.nOther = 0;
3874   sqlite3WalkExprList(&w, pExpr->x.pList);
3875   return cnt.nThis>0 || cnt.nOther==0;
3876 }
3877 
3878 /*
3879 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
3880 ** the new element.  Return a negative number if malloc fails.
3881 */
3882 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
3883   int i;
3884   pInfo->aCol = sqlite3ArrayAllocate(
3885        db,
3886        pInfo->aCol,
3887        sizeof(pInfo->aCol[0]),
3888        &pInfo->nColumn,
3889        &i
3890   );
3891   return i;
3892 }
3893 
3894 /*
3895 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
3896 ** the new element.  Return a negative number if malloc fails.
3897 */
3898 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
3899   int i;
3900   pInfo->aFunc = sqlite3ArrayAllocate(
3901        db,
3902        pInfo->aFunc,
3903        sizeof(pInfo->aFunc[0]),
3904        &pInfo->nFunc,
3905        &i
3906   );
3907   return i;
3908 }
3909 
3910 /*
3911 ** This is the xExprCallback for a tree walker.  It is used to
3912 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
3913 ** for additional information.
3914 */
3915 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
3916   int i;
3917   NameContext *pNC = pWalker->u.pNC;
3918   Parse *pParse = pNC->pParse;
3919   SrcList *pSrcList = pNC->pSrcList;
3920   AggInfo *pAggInfo = pNC->pAggInfo;
3921 
3922   switch( pExpr->op ){
3923     case TK_AGG_COLUMN:
3924     case TK_COLUMN: {
3925       testcase( pExpr->op==TK_AGG_COLUMN );
3926       testcase( pExpr->op==TK_COLUMN );
3927       /* Check to see if the column is in one of the tables in the FROM
3928       ** clause of the aggregate query */
3929       if( ALWAYS(pSrcList!=0) ){
3930         struct SrcList_item *pItem = pSrcList->a;
3931         for(i=0; i<pSrcList->nSrc; i++, pItem++){
3932           struct AggInfo_col *pCol;
3933           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3934           if( pExpr->iTable==pItem->iCursor ){
3935             /* If we reach this point, it means that pExpr refers to a table
3936             ** that is in the FROM clause of the aggregate query.
3937             **
3938             ** Make an entry for the column in pAggInfo->aCol[] if there
3939             ** is not an entry there already.
3940             */
3941             int k;
3942             pCol = pAggInfo->aCol;
3943             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
3944               if( pCol->iTable==pExpr->iTable &&
3945                   pCol->iColumn==pExpr->iColumn ){
3946                 break;
3947               }
3948             }
3949             if( (k>=pAggInfo->nColumn)
3950              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
3951             ){
3952               pCol = &pAggInfo->aCol[k];
3953               pCol->pTab = pExpr->pTab;
3954               pCol->iTable = pExpr->iTable;
3955               pCol->iColumn = pExpr->iColumn;
3956               pCol->iMem = ++pParse->nMem;
3957               pCol->iSorterColumn = -1;
3958               pCol->pExpr = pExpr;
3959               if( pAggInfo->pGroupBy ){
3960                 int j, n;
3961                 ExprList *pGB = pAggInfo->pGroupBy;
3962                 struct ExprList_item *pTerm = pGB->a;
3963                 n = pGB->nExpr;
3964                 for(j=0; j<n; j++, pTerm++){
3965                   Expr *pE = pTerm->pExpr;
3966                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
3967                       pE->iColumn==pExpr->iColumn ){
3968                     pCol->iSorterColumn = j;
3969                     break;
3970                   }
3971                 }
3972               }
3973               if( pCol->iSorterColumn<0 ){
3974                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
3975               }
3976             }
3977             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
3978             ** because it was there before or because we just created it).
3979             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
3980             ** pAggInfo->aCol[] entry.
3981             */
3982             ExprSetIrreducible(pExpr);
3983             pExpr->pAggInfo = pAggInfo;
3984             pExpr->op = TK_AGG_COLUMN;
3985             pExpr->iAgg = (i16)k;
3986             break;
3987           } /* endif pExpr->iTable==pItem->iCursor */
3988         } /* end loop over pSrcList */
3989       }
3990       return WRC_Prune;
3991     }
3992     case TK_AGG_FUNCTION: {
3993       if( (pNC->ncFlags & NC_InAggFunc)==0
3994        && pWalker->walkerDepth==pExpr->op2
3995       ){
3996         /* Check to see if pExpr is a duplicate of another aggregate
3997         ** function that is already in the pAggInfo structure
3998         */
3999         struct AggInfo_func *pItem = pAggInfo->aFunc;
4000         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
4001           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
4002             break;
4003           }
4004         }
4005         if( i>=pAggInfo->nFunc ){
4006           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
4007           */
4008           u8 enc = ENC(pParse->db);
4009           i = addAggInfoFunc(pParse->db, pAggInfo);
4010           if( i>=0 ){
4011             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4012             pItem = &pAggInfo->aFunc[i];
4013             pItem->pExpr = pExpr;
4014             pItem->iMem = ++pParse->nMem;
4015             assert( !ExprHasProperty(pExpr, EP_IntValue) );
4016             pItem->pFunc = sqlite3FindFunction(pParse->db,
4017                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
4018                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4019             if( pExpr->flags & EP_Distinct ){
4020               pItem->iDistinct = pParse->nTab++;
4021             }else{
4022               pItem->iDistinct = -1;
4023             }
4024           }
4025         }
4026         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4027         */
4028         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4029         ExprSetIrreducible(pExpr);
4030         pExpr->iAgg = (i16)i;
4031         pExpr->pAggInfo = pAggInfo;
4032       }
4033       return WRC_Prune;
4034     }
4035   }
4036   return WRC_Continue;
4037 }
4038 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4039   UNUSED_PARAMETER(pWalker);
4040   UNUSED_PARAMETER(pSelect);
4041   return WRC_Continue;
4042 }
4043 
4044 /*
4045 ** Analyze the given expression looking for aggregate functions and
4046 ** for variables that need to be added to the pParse->aAgg[] array.
4047 ** Make additional entries to the pParse->aAgg[] array as necessary.
4048 **
4049 ** This routine should only be called after the expression has been
4050 ** analyzed by sqlite3ResolveExprNames().
4051 */
4052 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
4053   Walker w;
4054   memset(&w, 0, sizeof(w));
4055   w.xExprCallback = analyzeAggregate;
4056   w.xSelectCallback = analyzeAggregatesInSelect;
4057   w.u.pNC = pNC;
4058   assert( pNC->pSrcList!=0 );
4059   sqlite3WalkExpr(&w, pExpr);
4060 }
4061 
4062 /*
4063 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4064 ** expression list.  Return the number of errors.
4065 **
4066 ** If an error is found, the analysis is cut short.
4067 */
4068 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
4069   struct ExprList_item *pItem;
4070   int i;
4071   if( pList ){
4072     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4073       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
4074     }
4075   }
4076 }
4077 
4078 /*
4079 ** Allocate a single new register for use to hold some intermediate result.
4080 */
4081 int sqlite3GetTempReg(Parse *pParse){
4082   if( pParse->nTempReg==0 ){
4083     return ++pParse->nMem;
4084   }
4085   return pParse->aTempReg[--pParse->nTempReg];
4086 }
4087 
4088 /*
4089 ** Deallocate a register, making available for reuse for some other
4090 ** purpose.
4091 **
4092 ** If a register is currently being used by the column cache, then
4093 ** the dallocation is deferred until the column cache line that uses
4094 ** the register becomes stale.
4095 */
4096 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
4097   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
4098     int i;
4099     struct yColCache *p;
4100     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4101       if( p->iReg==iReg ){
4102         p->tempReg = 1;
4103         return;
4104       }
4105     }
4106     pParse->aTempReg[pParse->nTempReg++] = iReg;
4107   }
4108 }
4109 
4110 /*
4111 ** Allocate or deallocate a block of nReg consecutive registers
4112 */
4113 int sqlite3GetTempRange(Parse *pParse, int nReg){
4114   int i, n;
4115   i = pParse->iRangeReg;
4116   n = pParse->nRangeReg;
4117   if( nReg<=n ){
4118     assert( !usedAsColumnCache(pParse, i, i+n-1) );
4119     pParse->iRangeReg += nReg;
4120     pParse->nRangeReg -= nReg;
4121   }else{
4122     i = pParse->nMem+1;
4123     pParse->nMem += nReg;
4124   }
4125   return i;
4126 }
4127 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
4128   sqlite3ExprCacheRemove(pParse, iReg, nReg);
4129   if( nReg>pParse->nRangeReg ){
4130     pParse->nRangeReg = nReg;
4131     pParse->iRangeReg = iReg;
4132   }
4133 }
4134 
4135 /*
4136 ** Mark all temporary registers as being unavailable for reuse.
4137 */
4138 void sqlite3ClearTempRegCache(Parse *pParse){
4139   pParse->nTempReg = 0;
4140   pParse->nRangeReg = 0;
4141 }
4142