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