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