xref: /sqlite-3.40.0/src/expr.c (revision a3628d14)
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 ** $Id: expr.c,v 1.430 2009/04/28 12:08:15 danielk1977 Exp $
16 */
17 #include "sqliteInt.h"
18 
19 /*
20 ** Return the 'affinity' of the expression pExpr if any.
21 **
22 ** If pExpr is a column, a reference to a column via an 'AS' alias,
23 ** or a sub-select with a column as the return value, then the
24 ** affinity of that column is returned. Otherwise, 0x00 is returned,
25 ** indicating no affinity for the expression.
26 **
27 ** i.e. the WHERE clause expresssions in the following statements all
28 ** have an affinity:
29 **
30 ** CREATE TABLE t1(a);
31 ** SELECT * FROM t1 WHERE a;
32 ** SELECT a AS b FROM t1 WHERE b;
33 ** SELECT * FROM t1 WHERE (select a from t1);
34 */
35 char sqlite3ExprAffinity(Expr *pExpr){
36   int op = pExpr->op;
37   if( op==TK_SELECT ){
38     assert( pExpr->flags&EP_xIsSelect );
39     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
40   }
41 #ifndef SQLITE_OMIT_CAST
42   if( op==TK_CAST ){
43     return sqlite3AffinityType(&pExpr->token);
44   }
45 #endif
46   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
47    && pExpr->pTab!=0
48   ){
49     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
50     ** a TK_COLUMN but was previously evaluated and cached in a register */
51     int j = pExpr->iColumn;
52     if( j<0 ) return SQLITE_AFF_INTEGER;
53     assert( pExpr->pTab && j<pExpr->pTab->nCol );
54     return pExpr->pTab->aCol[j].affinity;
55   }
56   return pExpr->affinity;
57 }
58 
59 /*
60 ** Set the collating sequence for expression pExpr to be the collating
61 ** sequence named by pToken.   Return a pointer to the revised expression.
62 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
63 ** flag.  An explicit collating sequence will override implicit
64 ** collating sequences.
65 */
66 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
67   char *zColl = 0;            /* Dequoted name of collation sequence */
68   CollSeq *pColl;
69   sqlite3 *db = pParse->db;
70   zColl = sqlite3NameFromToken(db, pCollName);
71   if( pExpr && zColl ){
72     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
73     if( pColl ){
74       pExpr->pColl = pColl;
75       pExpr->flags |= EP_ExpCollate;
76     }
77   }
78   sqlite3DbFree(db, zColl);
79   return pExpr;
80 }
81 
82 /*
83 ** Return the default collation sequence for the expression pExpr. If
84 ** there is no default collation type, return 0.
85 */
86 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
87   CollSeq *pColl = 0;
88   Expr *p = pExpr;
89   while( p ){
90     int op;
91     pColl = p->pColl;
92     if( pColl ) break;
93     op = p->op;
94     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
95       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
96       ** a TK_COLUMN but was previously evaluated and cached in a register */
97       const char *zColl;
98       int j = p->iColumn;
99       if( j>=0 ){
100         sqlite3 *db = pParse->db;
101         zColl = p->pTab->aCol[j].zColl;
102         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
103         pExpr->pColl = pColl;
104       }
105       break;
106     }
107     if( op!=TK_CAST && op!=TK_UPLUS ){
108       break;
109     }
110     p = p->pLeft;
111   }
112   if( sqlite3CheckCollSeq(pParse, pColl) ){
113     pColl = 0;
114   }
115   return pColl;
116 }
117 
118 /*
119 ** pExpr is an operand of a comparison operator.  aff2 is the
120 ** type affinity of the other operand.  This routine returns the
121 ** type affinity that should be used for the comparison operator.
122 */
123 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
124   char aff1 = sqlite3ExprAffinity(pExpr);
125   if( aff1 && aff2 ){
126     /* Both sides of the comparison are columns. If one has numeric
127     ** affinity, use that. Otherwise use no affinity.
128     */
129     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
130       return SQLITE_AFF_NUMERIC;
131     }else{
132       return SQLITE_AFF_NONE;
133     }
134   }else if( !aff1 && !aff2 ){
135     /* Neither side of the comparison is a column.  Compare the
136     ** results directly.
137     */
138     return SQLITE_AFF_NONE;
139   }else{
140     /* One side is a column, the other is not. Use the columns affinity. */
141     assert( aff1==0 || aff2==0 );
142     return (aff1 + aff2);
143   }
144 }
145 
146 /*
147 ** pExpr is a comparison operator.  Return the type affinity that should
148 ** be applied to both operands prior to doing the comparison.
149 */
150 static char comparisonAffinity(Expr *pExpr){
151   char aff;
152   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
153           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
154           pExpr->op==TK_NE );
155   assert( pExpr->pLeft );
156   aff = sqlite3ExprAffinity(pExpr->pLeft);
157   if( pExpr->pRight ){
158     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
159   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
160     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
161   }else if( !aff ){
162     aff = SQLITE_AFF_NONE;
163   }
164   return aff;
165 }
166 
167 /*
168 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
169 ** idx_affinity is the affinity of an indexed column. Return true
170 ** if the index with affinity idx_affinity may be used to implement
171 ** the comparison in pExpr.
172 */
173 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
174   char aff = comparisonAffinity(pExpr);
175   switch( aff ){
176     case SQLITE_AFF_NONE:
177       return 1;
178     case SQLITE_AFF_TEXT:
179       return idx_affinity==SQLITE_AFF_TEXT;
180     default:
181       return sqlite3IsNumericAffinity(idx_affinity);
182   }
183 }
184 
185 /*
186 ** Return the P5 value that should be used for a binary comparison
187 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
188 */
189 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
190   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
191   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
192   return aff;
193 }
194 
195 /*
196 ** Return a pointer to the collation sequence that should be used by
197 ** a binary comparison operator comparing pLeft and pRight.
198 **
199 ** If the left hand expression has a collating sequence type, then it is
200 ** used. Otherwise the collation sequence for the right hand expression
201 ** is used, or the default (BINARY) if neither expression has a collating
202 ** type.
203 **
204 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
205 ** it is not considered.
206 */
207 CollSeq *sqlite3BinaryCompareCollSeq(
208   Parse *pParse,
209   Expr *pLeft,
210   Expr *pRight
211 ){
212   CollSeq *pColl;
213   assert( pLeft );
214   if( pLeft->flags & EP_ExpCollate ){
215     assert( pLeft->pColl );
216     pColl = pLeft->pColl;
217   }else if( pRight && pRight->flags & EP_ExpCollate ){
218     assert( pRight->pColl );
219     pColl = pRight->pColl;
220   }else{
221     pColl = sqlite3ExprCollSeq(pParse, pLeft);
222     if( !pColl ){
223       pColl = sqlite3ExprCollSeq(pParse, pRight);
224     }
225   }
226   return pColl;
227 }
228 
229 /*
230 ** Generate the operands for a comparison operation.  Before
231 ** generating the code for each operand, set the EP_AnyAff
232 ** flag on the expression so that it will be able to used a
233 ** cached column value that has previously undergone an
234 ** affinity change.
235 */
236 static void codeCompareOperands(
237   Parse *pParse,    /* Parsing and code generating context */
238   Expr *pLeft,      /* The left operand */
239   int *pRegLeft,    /* Register where left operand is stored */
240   int *pFreeLeft,   /* Free this register when done */
241   Expr *pRight,     /* The right operand */
242   int *pRegRight,   /* Register where right operand is stored */
243   int *pFreeRight   /* Write temp register for right operand there */
244 ){
245   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
246   pLeft->flags |= EP_AnyAff;
247   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
248   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
249   pRight->flags |= EP_AnyAff;
250   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
251 }
252 
253 /*
254 ** Generate code for a comparison operator.
255 */
256 static int codeCompare(
257   Parse *pParse,    /* The parsing (and code generating) context */
258   Expr *pLeft,      /* The left operand */
259   Expr *pRight,     /* The right operand */
260   int opcode,       /* The comparison opcode */
261   int in1, int in2, /* Register holding operands */
262   int dest,         /* Jump here if true.  */
263   int jumpIfNull    /* If true, jump if either operand is NULL */
264 ){
265   int p5;
266   int addr;
267   CollSeq *p4;
268 
269   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
270   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
271   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
272                            (void*)p4, P4_COLLSEQ);
273   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
274   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
275     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
276     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
277   }
278   return addr;
279 }
280 
281 #if SQLITE_MAX_EXPR_DEPTH>0
282 /*
283 ** Check that argument nHeight is less than or equal to the maximum
284 ** expression depth allowed. If it is not, leave an error message in
285 ** pParse.
286 */
287 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
288   int rc = SQLITE_OK;
289   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
290   if( nHeight>mxHeight ){
291     sqlite3ErrorMsg(pParse,
292        "Expression tree is too large (maximum depth %d)", mxHeight
293     );
294     rc = SQLITE_ERROR;
295   }
296   return rc;
297 }
298 
299 /* The following three functions, heightOfExpr(), heightOfExprList()
300 ** and heightOfSelect(), are used to determine the maximum height
301 ** of any expression tree referenced by the structure passed as the
302 ** first argument.
303 **
304 ** If this maximum height is greater than the current value pointed
305 ** to by pnHeight, the second parameter, then set *pnHeight to that
306 ** value.
307 */
308 static void heightOfExpr(Expr *p, int *pnHeight){
309   if( p ){
310     if( p->nHeight>*pnHeight ){
311       *pnHeight = p->nHeight;
312     }
313   }
314 }
315 static void heightOfExprList(ExprList *p, int *pnHeight){
316   if( p ){
317     int i;
318     for(i=0; i<p->nExpr; i++){
319       heightOfExpr(p->a[i].pExpr, pnHeight);
320     }
321   }
322 }
323 static void heightOfSelect(Select *p, int *pnHeight){
324   if( p ){
325     heightOfExpr(p->pWhere, pnHeight);
326     heightOfExpr(p->pHaving, pnHeight);
327     heightOfExpr(p->pLimit, pnHeight);
328     heightOfExpr(p->pOffset, pnHeight);
329     heightOfExprList(p->pEList, pnHeight);
330     heightOfExprList(p->pGroupBy, pnHeight);
331     heightOfExprList(p->pOrderBy, pnHeight);
332     heightOfSelect(p->pPrior, pnHeight);
333   }
334 }
335 
336 /*
337 ** Set the Expr.nHeight variable in the structure passed as an
338 ** argument. An expression with no children, Expr.pList or
339 ** Expr.pSelect member has a height of 1. Any other expression
340 ** has a height equal to the maximum height of any other
341 ** referenced Expr plus one.
342 */
343 static void exprSetHeight(Expr *p){
344   int nHeight = 0;
345   heightOfExpr(p->pLeft, &nHeight);
346   heightOfExpr(p->pRight, &nHeight);
347   if( ExprHasProperty(p, EP_xIsSelect) ){
348     heightOfSelect(p->x.pSelect, &nHeight);
349   }else{
350     heightOfExprList(p->x.pList, &nHeight);
351   }
352   p->nHeight = nHeight + 1;
353 }
354 
355 /*
356 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
357 ** the height is greater than the maximum allowed expression depth,
358 ** leave an error in pParse.
359 */
360 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
361   exprSetHeight(p);
362   sqlite3ExprCheckHeight(pParse, p->nHeight);
363 }
364 
365 /*
366 ** Return the maximum height of any expression tree referenced
367 ** by the select statement passed as an argument.
368 */
369 int sqlite3SelectExprHeight(Select *p){
370   int nHeight = 0;
371   heightOfSelect(p, &nHeight);
372   return nHeight;
373 }
374 #else
375   #define exprSetHeight(y)
376 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
377 
378 /*
379 ** Construct a new expression node and return a pointer to it.  Memory
380 ** for this node is obtained from sqlite3_malloc().  The calling function
381 ** is responsible for making sure the node eventually gets freed.
382 */
383 Expr *sqlite3Expr(
384   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
385   int op,                 /* Expression opcode */
386   Expr *pLeft,            /* Left operand */
387   Expr *pRight,           /* Right operand */
388   const Token *pToken     /* Argument token */
389 ){
390   Expr *pNew;
391   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
392   if( pNew==0 ){
393     /* When malloc fails, delete pLeft and pRight. Expressions passed to
394     ** this function must always be allocated with sqlite3Expr() for this
395     ** reason.
396     */
397     sqlite3ExprDelete(db, pLeft);
398     sqlite3ExprDelete(db, pRight);
399     return 0;
400   }
401   pNew->op = (u8)op;
402   pNew->pLeft = pLeft;
403   pNew->pRight = pRight;
404   pNew->iAgg = -1;
405   pNew->span.z = (u8*)"";
406   if( pToken ){
407     int c;
408     assert( pToken->dyn==0 );
409     pNew->span = *pToken;
410 
411     /* The pToken->z value is read-only.  But the new expression
412     ** node created here might be passed to sqlite3DequoteExpr() which
413     ** will attempt to modify pNew->token.z.  Hence, if the token
414     ** is quoted, make a copy now so that DequoteExpr() will change
415     ** the copy rather than the original text.
416     */
417     if( pToken->n>=2
418          && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
419       sqlite3TokenCopy(db, &pNew->token, pToken);
420     }else{
421       pNew->token = *pToken;
422       pNew->flags |= EP_Dequoted;
423       VVA_ONLY( pNew->vvaFlags |= EVVA_ReadOnlyToken; )
424     }
425   }else if( pLeft ){
426     if( pRight ){
427       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
428         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
429       }
430       if( pRight->flags & EP_ExpCollate ){
431         pNew->flags |= EP_ExpCollate;
432         pNew->pColl = pRight->pColl;
433       }
434     }
435     if( pLeft->flags & EP_ExpCollate ){
436       pNew->flags |= EP_ExpCollate;
437       pNew->pColl = pLeft->pColl;
438     }
439   }
440 
441   exprSetHeight(pNew);
442   return pNew;
443 }
444 
445 /*
446 ** Works like sqlite3Expr() except that it takes an extra Parse*
447 ** argument and notifies the associated connection object if malloc fails.
448 */
449 Expr *sqlite3PExpr(
450   Parse *pParse,          /* Parsing context */
451   int op,                 /* Expression opcode */
452   Expr *pLeft,            /* Left operand */
453   Expr *pRight,           /* Right operand */
454   const Token *pToken     /* Argument token */
455 ){
456   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
457   if( p ){
458     sqlite3ExprCheckHeight(pParse, p->nHeight);
459   }
460   return p;
461 }
462 
463 /*
464 ** When doing a nested parse, you can include terms in an expression
465 ** that look like this:   #1 #2 ...  These terms refer to registers
466 ** in the virtual machine.  #N is the N-th register.
467 **
468 ** This routine is called by the parser to deal with on of those terms.
469 ** It immediately generates code to store the value in a memory location.
470 ** The returns an expression that will code to extract the value from
471 ** that memory location as needed.
472 */
473 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
474   Vdbe *v = pParse->pVdbe;
475   Expr *p;
476   if( pParse->nested==0 ){
477     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
478     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
479   }
480   if( v==0 ) return 0;
481   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
482   if( p==0 ){
483     return 0;  /* Malloc failed */
484   }
485   p->iTable = atoi((char*)&pToken->z[1]);
486   return p;
487 }
488 
489 /*
490 ** Join two expressions using an AND operator.  If either expression is
491 ** NULL, then just return the other expression.
492 */
493 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
494   if( pLeft==0 ){
495     return pRight;
496   }else if( pRight==0 ){
497     return pLeft;
498   }else{
499     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
500   }
501 }
502 
503 /*
504 ** Set the Expr.span field of the given expression to span all
505 ** text between the two given tokens.  Both tokens must be pointing
506 ** at the same string.
507 */
508 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
509   assert( pRight!=0 );
510   assert( pLeft!=0 );
511   if( pExpr ){
512     pExpr->span.z = pLeft->z;
513     /* The following assert() may fail when this is called
514     ** via sqlite3PExpr()/sqlite3Expr() from addWhereTerm(). */
515     /* assert(pRight->z >= pLeft->z); */
516     pExpr->span.n = pRight->n + (unsigned)(pRight->z - pLeft->z);
517   }
518 }
519 
520 /*
521 ** Construct a new expression node for a function with multiple
522 ** arguments.
523 */
524 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
525   Expr *pNew;
526   sqlite3 *db = pParse->db;
527   assert( pToken );
528   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
529   if( pNew==0 ){
530     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
531     return 0;
532   }
533   pNew->op = TK_FUNCTION;
534   pNew->x.pList = pList;
535   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
536   assert( pToken->dyn==0 );
537   pNew->span = *pToken;
538   sqlite3TokenCopy(db, &pNew->token, pToken);
539   sqlite3ExprSetHeight(pParse, pNew);
540   return pNew;
541 }
542 
543 /*
544 ** Assign a variable number to an expression that encodes a wildcard
545 ** in the original SQL statement.
546 **
547 ** Wildcards consisting of a single "?" are assigned the next sequential
548 ** variable number.
549 **
550 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
551 ** sure "nnn" is not too be to avoid a denial of service attack when
552 ** the SQL statement comes from an external source.
553 **
554 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
555 ** as the previous instance of the same wildcard.  Or if this is the first
556 ** instance of the wildcard, the next sequenial variable number is
557 ** assigned.
558 */
559 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
560   Token *pToken;
561   sqlite3 *db = pParse->db;
562 
563   if( pExpr==0 ) return;
564   pToken = &pExpr->token;
565   assert( pToken->n>=1 );
566   assert( pToken->z!=0 );
567   assert( pToken->z[0]!=0 );
568   if( pToken->n==1 ){
569     /* Wildcard of the form "?".  Assign the next variable number */
570     pExpr->iTable = ++pParse->nVar;
571   }else if( pToken->z[0]=='?' ){
572     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
573     ** use it as the variable number */
574     int i;
575     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
576     testcase( i==0 );
577     testcase( i==1 );
578     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
579     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
580     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
581       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
582           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
583     }
584     if( i>pParse->nVar ){
585       pParse->nVar = i;
586     }
587   }else{
588     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
589     ** number as the prior appearance of the same name, or if the name
590     ** has never appeared before, reuse the same variable number
591     */
592     int i;
593     u32 n;
594     n = pToken->n;
595     for(i=0; i<pParse->nVarExpr; i++){
596       Expr *pE;
597       if( (pE = pParse->apVarExpr[i])!=0
598           && pE->token.n==n
599           && memcmp(pE->token.z, pToken->z, n)==0 ){
600         pExpr->iTable = pE->iTable;
601         break;
602       }
603     }
604     if( i>=pParse->nVarExpr ){
605       pExpr->iTable = ++pParse->nVar;
606       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
607         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
608         pParse->apVarExpr =
609             sqlite3DbReallocOrFree(
610               db,
611               pParse->apVarExpr,
612               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
613             );
614       }
615       if( !db->mallocFailed ){
616         assert( pParse->apVarExpr!=0 );
617         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
618       }
619     }
620   }
621   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
622     sqlite3ErrorMsg(pParse, "too many SQL variables");
623   }
624 }
625 
626 /*
627 ** Clear an expression structure without deleting the structure itself.
628 ** Substructure is deleted.
629 */
630 void sqlite3ExprClear(sqlite3 *db, Expr *p){
631   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
632   if( !ExprHasAnyProperty(p, EP_TokenOnly|EP_SpanToken) ){
633     if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
634     if( ExprHasProperty(p, EP_Reduced) ){
635       /* Subtrees are part of the same memory allocation when EP_Reduced set */
636       if( p->pLeft ) sqlite3ExprClear(db, p->pLeft);
637       if( p->pRight ) sqlite3ExprClear(db, p->pRight);
638     }else{
639       /* Subtrees are separate allocations when EP_Reduced is clear */
640       sqlite3ExprDelete(db, p->pLeft);
641       sqlite3ExprDelete(db, p->pRight);
642     }
643     /* x.pSelect and x.pList are always separately allocated */
644     if( ExprHasProperty(p, EP_xIsSelect) ){
645       sqlite3SelectDelete(db, p->x.pSelect);
646     }else{
647       sqlite3ExprListDelete(db, p->x.pList);
648     }
649   }
650 }
651 
652 /*
653 ** Recursively delete an expression tree.
654 */
655 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
656   if( p==0 ) return;
657   sqlite3ExprClear(db, p);
658   sqlite3DbFree(db, p);
659 }
660 
661 /*
662 ** The Expr.token field might be a string literal that is quoted.
663 ** If so, remove the quotation marks.
664 */
665 void sqlite3DequoteExpr(Expr *p){
666   if( !ExprHasAnyProperty(p, EP_Dequoted) ){
667     ExprSetProperty(p, EP_Dequoted);
668     assert( (p->vvaFlags & EVVA_ReadOnlyToken)==0 );
669     sqlite3Dequote((char*)p->token.z);
670   }
671 }
672 
673 /*
674 ** Return the number of bytes allocated for the expression structure
675 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
676 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
677 */
678 static int exprStructSize(Expr *p){
679   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
680   if( ExprHasProperty(p, EP_SpanToken) ) return EXPR_SPANTOKENSIZE;
681   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
682   return EXPR_FULLSIZE;
683 }
684 
685 /*
686 ** sqlite3ExprDup() has been called to create a copy of expression p with
687 ** the EXPRDUP_XXX flags passed as the second argument. This function
688 ** returns the space required for the copy of the Expr structure only.
689 ** This is always one of EXPR_FULLSIZE, EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
690 */
691 static int dupedExprStructSize(Expr *p, int flags){
692   int nSize;
693   if( 0==(flags&EXPRDUP_REDUCE) ){
694     nSize = EXPR_FULLSIZE;
695   }else if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
696     nSize = EXPR_REDUCEDSIZE;
697   }else if( flags&EXPRDUP_SPAN ){
698     nSize = EXPR_SPANTOKENSIZE;
699   }else{
700     nSize = EXPR_TOKENONLYSIZE;
701   }
702   return nSize;
703 }
704 
705 /*
706 ** sqlite3ExprDup() has been called to create a copy of expression p with
707 ** the EXPRDUP_XXX passed as the second argument. This function returns
708 ** the space in bytes required to store the copy of the Expr structure
709 ** and the copies of the Expr.token.z and Expr.span.z (if applicable)
710 ** string buffers.
711 */
712 static int dupedExprNodeSize(Expr *p, int flags){
713   int nByte = dupedExprStructSize(p, flags) + (p->token.z ? p->token.n + 1 : 0);
714   if( (flags&EXPRDUP_SPAN)!=0
715    && (p->token.z!=p->span.z || p->token.n!=p->span.n)
716   ){
717     nByte += p->span.n;
718   }
719   return ROUND8(nByte);
720 }
721 
722 /*
723 ** Return the number of bytes required to create a duplicate of the
724 ** expression passed as the first argument. The second argument is a
725 ** mask containing EXPRDUP_XXX flags.
726 **
727 ** The value returned includes space to create a copy of the Expr struct
728 ** itself and the buffer referred to by Expr.token, if any. If the
729 ** EXPRDUP_SPAN flag is set, then space to create a copy of the buffer
730 ** refered to by Expr.span is also included.
731 **
732 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
733 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
734 ** and Expr.pRight variables (but not for any structures pointed to or
735 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
736 */
737 static int dupedExprSize(Expr *p, int flags){
738   int nByte = 0;
739   if( p ){
740     nByte = dupedExprNodeSize(p, flags);
741     if( flags&EXPRDUP_REDUCE ){
742       int f = flags&(~EXPRDUP_SPAN);
743       nByte += dupedExprSize(p->pLeft, f) + dupedExprSize(p->pRight, f);
744     }
745   }
746   return nByte;
747 }
748 
749 /*
750 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
751 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
752 ** to store the copy of expression p, the copies of p->token and p->span
753 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
754 ** if any. Before returning, *pzBuffer is set to the first byte passed the
755 ** portion of the buffer copied into by this function.
756 */
757 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
758   Expr *pNew = 0;                      /* Value to return */
759   if( p ){
760     const int isRequireSpan = (flags&EXPRDUP_SPAN);
761     const int isReduced = (flags&EXPRDUP_REDUCE);
762     u8 *zAlloc;
763 
764     assert( pzBuffer==0 || isReduced );
765 
766     /* Figure out where to write the new Expr structure. */
767     if( pzBuffer ){
768       zAlloc = *pzBuffer;
769     }else{
770       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
771     }
772     pNew = (Expr *)zAlloc;
773 
774     if( pNew ){
775       /* Set nNewSize to the size allocated for the structure pointed to
776       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
777       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
778       ** by the copy of the p->token.z string (if any).
779       */
780       const int nNewSize = dupedExprStructSize(p, flags);
781       const int nToken = (p->token.z ? p->token.n + 1 : 0);
782       if( isReduced ){
783         assert( ExprHasProperty(p, EP_Reduced)==0 );
784         memcpy(zAlloc, p, nNewSize);
785       }else{
786         int nSize = exprStructSize(p);
787         memcpy(zAlloc, p, nSize);
788         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
789       }
790 
791       /* Set the EP_Reduced and EP_TokenOnly flags appropriately. */
792       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_SpanToken);
793       switch( nNewSize ){
794         case EXPR_REDUCEDSIZE:   pNew->flags |= EP_Reduced; break;
795         case EXPR_TOKENONLYSIZE: pNew->flags |= EP_TokenOnly; break;
796         case EXPR_SPANTOKENSIZE: pNew->flags |= EP_SpanToken; break;
797       }
798 
799       /* Copy the p->token string, if any. */
800       if( nToken ){
801         unsigned char *zToken = &zAlloc[nNewSize];
802         memcpy(zToken, p->token.z, nToken-1);
803         zToken[nToken-1] = '\0';
804         pNew->token.dyn = 0;
805         pNew->token.z = zToken;
806       }
807 
808       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
809         /* Fill in the pNew->span token, if required. */
810         if( isRequireSpan ){
811           if( p->token.z!=p->span.z || p->token.n!=p->span.n ){
812             pNew->span.z = &zAlloc[nNewSize+nToken];
813             memcpy((char *)pNew->span.z, p->span.z, p->span.n);
814             pNew->span.dyn = 0;
815           }else{
816             pNew->span.z = pNew->token.z;
817             pNew->span.n = pNew->token.n;
818           }
819         }else{
820           pNew->span.z = 0;
821           pNew->span.n = 0;
822         }
823       }
824 
825       if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_SpanToken)) ){
826         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
827         if( ExprHasProperty(p, EP_xIsSelect) ){
828           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
829         }else{
830           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
831         }
832       }
833 
834       /* Fill in pNew->pLeft and pNew->pRight. */
835       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly|EP_SpanToken) ){
836         zAlloc += dupedExprNodeSize(p, flags);
837         if( ExprHasProperty(pNew, EP_Reduced) ){
838           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
839           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
840         }
841         if( pzBuffer ){
842           *pzBuffer = zAlloc;
843         }
844       }else if( !ExprHasAnyProperty(p, EP_TokenOnly|EP_SpanToken) ){
845         pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
846         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
847       }
848     }
849   }
850   return pNew;
851 }
852 
853 /*
854 ** The following group of routines make deep copies of expressions,
855 ** expression lists, ID lists, and select statements.  The copies can
856 ** be deleted (by being passed to their respective ...Delete() routines)
857 ** without effecting the originals.
858 **
859 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
860 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
861 ** by subsequent calls to sqlite*ListAppend() routines.
862 **
863 ** Any tables that the SrcList might point to are not duplicated.
864 **
865 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. If
866 ** the EXPRDUP_SPAN flag is set in the argument parameter, then the
867 ** Expr.span field of the input expression is copied. If EXPRDUP_SPAN is
868 ** clear, then the Expr.span field of the returned expression structure
869 ** is zeroed.
870 **
871 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
872 ** truncated version of the usual Expr structure that will be stored as
873 ** part of the in-memory representation of the database schema.
874 */
875 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
876   return exprDup(db, p, flags, 0);
877 }
878 void sqlite3TokenCopy(sqlite3 *db, Token *pTo, const Token *pFrom){
879   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
880   if( pFrom->z ){
881     pTo->n = pFrom->n;
882     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
883     pTo->dyn = 1;
884   }else{
885     pTo->z = 0;
886   }
887 }
888 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
889   ExprList *pNew;
890   struct ExprList_item *pItem, *pOldItem;
891   int i;
892   if( p==0 ) return 0;
893   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
894   if( pNew==0 ) return 0;
895   pNew->iECursor = 0;
896   pNew->nExpr = pNew->nAlloc = p->nExpr;
897   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
898   if( pItem==0 ){
899     sqlite3DbFree(db, pNew);
900     return 0;
901   }
902   pOldItem = p->a;
903   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
904     Expr *pNewExpr;
905     Expr *pOldExpr = pOldItem->pExpr;
906     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr, flags);
907     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
908     pItem->sortOrder = pOldItem->sortOrder;
909     pItem->done = 0;
910     pItem->iCol = pOldItem->iCol;
911     pItem->iAlias = pOldItem->iAlias;
912   }
913   return pNew;
914 }
915 
916 /*
917 ** If cursors, triggers, views and subqueries are all omitted from
918 ** the build, then none of the following routines, except for
919 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
920 ** called with a NULL argument.
921 */
922 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
923  || !defined(SQLITE_OMIT_SUBQUERY)
924 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
925   SrcList *pNew;
926   int i;
927   int nByte;
928   if( p==0 ) return 0;
929   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
930   pNew = sqlite3DbMallocRaw(db, nByte );
931   if( pNew==0 ) return 0;
932   pNew->nSrc = pNew->nAlloc = p->nSrc;
933   for(i=0; i<p->nSrc; i++){
934     struct SrcList_item *pNewItem = &pNew->a[i];
935     struct SrcList_item *pOldItem = &p->a[i];
936     Table *pTab;
937     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
938     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
939     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
940     pNewItem->jointype = pOldItem->jointype;
941     pNewItem->iCursor = pOldItem->iCursor;
942     pNewItem->isPopulated = pOldItem->isPopulated;
943     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
944     pNewItem->notIndexed = pOldItem->notIndexed;
945     pNewItem->pIndex = pOldItem->pIndex;
946     pTab = pNewItem->pTab = pOldItem->pTab;
947     if( pTab ){
948       pTab->nRef++;
949     }
950     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
951     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
952     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
953     pNewItem->colUsed = pOldItem->colUsed;
954   }
955   return pNew;
956 }
957 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
958   IdList *pNew;
959   int i;
960   if( p==0 ) return 0;
961   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
962   if( pNew==0 ) return 0;
963   pNew->nId = pNew->nAlloc = p->nId;
964   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
965   if( pNew->a==0 ){
966     sqlite3DbFree(db, pNew);
967     return 0;
968   }
969   for(i=0; i<p->nId; i++){
970     struct IdList_item *pNewItem = &pNew->a[i];
971     struct IdList_item *pOldItem = &p->a[i];
972     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
973     pNewItem->idx = pOldItem->idx;
974   }
975   return pNew;
976 }
977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
978   Select *pNew;
979   if( p==0 ) return 0;
980   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
981   if( pNew==0 ) return 0;
982   /* Always make a copy of the span for top-level expressions in the
983   ** expression list.  The logic in SELECT processing that determines
984   ** the names of columns in the result set needs this information */
985   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags|EXPRDUP_SPAN);
986   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
987   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
988   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
989   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
990   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
991   pNew->op = p->op;
992   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
993   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
994   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
995   pNew->iLimit = 0;
996   pNew->iOffset = 0;
997   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
998   pNew->pRightmost = 0;
999   pNew->addrOpenEphm[0] = -1;
1000   pNew->addrOpenEphm[1] = -1;
1001   pNew->addrOpenEphm[2] = -1;
1002   return pNew;
1003 }
1004 #else
1005 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1006   assert( p==0 );
1007   return 0;
1008 }
1009 #endif
1010 
1011 
1012 /*
1013 ** Add a new element to the end of an expression list.  If pList is
1014 ** initially NULL, then create a new expression list.
1015 */
1016 ExprList *sqlite3ExprListAppend(
1017   Parse *pParse,          /* Parsing context */
1018   ExprList *pList,        /* List to which to append. Might be NULL */
1019   Expr *pExpr,            /* Expression to be appended */
1020   Token *pName            /* AS keyword for the expression */
1021 ){
1022   sqlite3 *db = pParse->db;
1023   if( pList==0 ){
1024     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
1025     if( pList==0 ){
1026       goto no_mem;
1027     }
1028     assert( pList->nAlloc==0 );
1029   }
1030   if( pList->nAlloc<=pList->nExpr ){
1031     struct ExprList_item *a;
1032     int n = pList->nAlloc*2 + 4;
1033     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
1034     if( a==0 ){
1035       goto no_mem;
1036     }
1037     pList->a = a;
1038     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
1039   }
1040   assert( pList->a!=0 );
1041   if( pExpr || pName ){
1042     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1043     memset(pItem, 0, sizeof(*pItem));
1044     pItem->zName = sqlite3NameFromToken(db, pName);
1045     pItem->pExpr = pExpr;
1046     pItem->iAlias = 0;
1047   }
1048   return pList;
1049 
1050 no_mem:
1051   /* Avoid leaking memory if malloc has failed. */
1052   sqlite3ExprDelete(db, pExpr);
1053   sqlite3ExprListDelete(db, pList);
1054   return 0;
1055 }
1056 
1057 /*
1058 ** If the expression list pEList contains more than iLimit elements,
1059 ** leave an error message in pParse.
1060 */
1061 void sqlite3ExprListCheckLength(
1062   Parse *pParse,
1063   ExprList *pEList,
1064   const char *zObject
1065 ){
1066   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1067   testcase( pEList && pEList->nExpr==mx );
1068   testcase( pEList && pEList->nExpr==mx+1 );
1069   if( pEList && pEList->nExpr>mx ){
1070     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1071   }
1072 }
1073 
1074 /*
1075 ** Delete an entire expression list.
1076 */
1077 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1078   int i;
1079   struct ExprList_item *pItem;
1080   if( pList==0 ) return;
1081   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
1082   assert( pList->nExpr<=pList->nAlloc );
1083   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1084     sqlite3ExprDelete(db, pItem->pExpr);
1085     sqlite3DbFree(db, pItem->zName);
1086   }
1087   sqlite3DbFree(db, pList->a);
1088   sqlite3DbFree(db, pList);
1089 }
1090 
1091 /*
1092 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
1093 ** to an integer.  These routines are checking an expression to see
1094 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
1095 ** not constant.
1096 **
1097 ** These callback routines are used to implement the following:
1098 **
1099 **     sqlite3ExprIsConstant()
1100 **     sqlite3ExprIsConstantNotJoin()
1101 **     sqlite3ExprIsConstantOrFunction()
1102 **
1103 */
1104 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1105 
1106   /* If pWalker->u.i is 3 then any term of the expression that comes from
1107   ** the ON or USING clauses of a join disqualifies the expression
1108   ** from being considered constant. */
1109   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
1110     pWalker->u.i = 0;
1111     return WRC_Abort;
1112   }
1113 
1114   switch( pExpr->op ){
1115     /* Consider functions to be constant if all their arguments are constant
1116     ** and pWalker->u.i==2 */
1117     case TK_FUNCTION:
1118       if( pWalker->u.i==2 ) return 0;
1119       /* Fall through */
1120     case TK_ID:
1121     case TK_COLUMN:
1122     case TK_AGG_FUNCTION:
1123     case TK_AGG_COLUMN:
1124 #ifndef SQLITE_OMIT_SUBQUERY
1125     case TK_SELECT:
1126     case TK_EXISTS:
1127       testcase( pExpr->op==TK_SELECT );
1128       testcase( pExpr->op==TK_EXISTS );
1129 #endif
1130       testcase( pExpr->op==TK_ID );
1131       testcase( pExpr->op==TK_COLUMN );
1132       testcase( pExpr->op==TK_AGG_FUNCTION );
1133       testcase( pExpr->op==TK_AGG_COLUMN );
1134       pWalker->u.i = 0;
1135       return WRC_Abort;
1136     default:
1137       return WRC_Continue;
1138   }
1139 }
1140 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1141   UNUSED_PARAMETER(NotUsed);
1142   pWalker->u.i = 0;
1143   return WRC_Abort;
1144 }
1145 static int exprIsConst(Expr *p, int initFlag){
1146   Walker w;
1147   w.u.i = initFlag;
1148   w.xExprCallback = exprNodeIsConstant;
1149   w.xSelectCallback = selectNodeIsConstant;
1150   sqlite3WalkExpr(&w, p);
1151   return w.u.i;
1152 }
1153 
1154 /*
1155 ** Walk an expression tree.  Return 1 if the expression is constant
1156 ** and 0 if it involves variables or function calls.
1157 **
1158 ** For the purposes of this function, a double-quoted string (ex: "abc")
1159 ** is considered a variable but a single-quoted string (ex: 'abc') is
1160 ** a constant.
1161 */
1162 int sqlite3ExprIsConstant(Expr *p){
1163   return exprIsConst(p, 1);
1164 }
1165 
1166 /*
1167 ** Walk an expression tree.  Return 1 if the expression is constant
1168 ** that does no originate from the ON or USING clauses of a join.
1169 ** Return 0 if it involves variables or function calls or terms from
1170 ** an ON or USING clause.
1171 */
1172 int sqlite3ExprIsConstantNotJoin(Expr *p){
1173   return exprIsConst(p, 3);
1174 }
1175 
1176 /*
1177 ** Walk an expression tree.  Return 1 if the expression is constant
1178 ** or a function call with constant arguments.  Return and 0 if there
1179 ** are any variables.
1180 **
1181 ** For the purposes of this function, a double-quoted string (ex: "abc")
1182 ** is considered a variable but a single-quoted string (ex: 'abc') is
1183 ** a constant.
1184 */
1185 int sqlite3ExprIsConstantOrFunction(Expr *p){
1186   return exprIsConst(p, 2);
1187 }
1188 
1189 /*
1190 ** If the expression p codes a constant integer that is small enough
1191 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1192 ** in *pValue.  If the expression is not an integer or if it is too big
1193 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1194 */
1195 int sqlite3ExprIsInteger(Expr *p, int *pValue){
1196   int rc = 0;
1197   if( p->flags & EP_IntValue ){
1198     *pValue = p->iTable;
1199     return 1;
1200   }
1201   switch( p->op ){
1202     case TK_INTEGER: {
1203       rc = sqlite3GetInt32((char*)p->token.z, pValue);
1204       break;
1205     }
1206     case TK_UPLUS: {
1207       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1208       break;
1209     }
1210     case TK_UMINUS: {
1211       int v;
1212       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1213         *pValue = -v;
1214         rc = 1;
1215       }
1216       break;
1217     }
1218     default: break;
1219   }
1220   if( rc ){
1221     p->op = TK_INTEGER;
1222     p->flags |= EP_IntValue;
1223     p->iTable = *pValue;
1224   }
1225   return rc;
1226 }
1227 
1228 /*
1229 ** Return TRUE if the given string is a row-id column name.
1230 */
1231 int sqlite3IsRowid(const char *z){
1232   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1233   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1234   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1235   return 0;
1236 }
1237 
1238 /*
1239 ** Return true if the IN operator optimization is enabled and
1240 ** the SELECT statement p exists and is of the
1241 ** simple form:
1242 **
1243 **     SELECT <column> FROM <table>
1244 **
1245 ** If this is the case, it may be possible to use an existing table
1246 ** or index instead of generating an epheremal table.
1247 */
1248 #ifndef SQLITE_OMIT_SUBQUERY
1249 static int isCandidateForInOpt(Select *p){
1250   SrcList *pSrc;
1251   ExprList *pEList;
1252   Table *pTab;
1253   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1254   if( p->pPrior ) return 0;              /* Not a compound SELECT */
1255   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1256       return 0; /* No DISTINCT keyword and no aggregate functions */
1257   }
1258   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
1259   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1260   if( p->pOffset ) return 0;
1261   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1262   pSrc = p->pSrc;
1263   assert( pSrc!=0 );
1264   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1265   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
1266   pTab = pSrc->a[0].pTab;
1267   if( pTab==0 ) return 0;
1268   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
1269   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1270   pEList = p->pEList;
1271   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1272   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1273   return 1;
1274 }
1275 #endif /* SQLITE_OMIT_SUBQUERY */
1276 
1277 /*
1278 ** This function is used by the implementation of the IN (...) operator.
1279 ** It's job is to find or create a b-tree structure that may be used
1280 ** either to test for membership of the (...) set or to iterate through
1281 ** its members, skipping duplicates.
1282 **
1283 ** The cursor opened on the structure (database table, database index
1284 ** or ephermal table) is stored in pX->iTable before this function returns.
1285 ** The returned value indicates the structure type, as follows:
1286 **
1287 **   IN_INDEX_ROWID - The cursor was opened on a database table.
1288 **   IN_INDEX_INDEX - The cursor was opened on a database index.
1289 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
1290 **                    populated epheremal table.
1291 **
1292 ** An existing structure may only be used if the SELECT is of the simple
1293 ** form:
1294 **
1295 **     SELECT <column> FROM <table>
1296 **
1297 ** If prNotFound parameter is 0, then the structure will be used to iterate
1298 ** through the set members, skipping any duplicates. In this case an
1299 ** epheremal table must be used unless the selected <column> is guaranteed
1300 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1301 ** is unique by virtue of a constraint or implicit index.
1302 **
1303 ** If the prNotFound parameter is not 0, then the structure will be used
1304 ** for fast set membership tests. In this case an epheremal table must
1305 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1306 ** be found with <column> as its left-most column.
1307 **
1308 ** When the structure is being used for set membership tests, the user
1309 ** needs to know whether or not the structure contains an SQL NULL
1310 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1311 ** If there is a chance that the structure may contain a NULL value at
1312 ** runtime, then a register is allocated and the register number written
1313 ** to *prNotFound. If there is no chance that the structure contains a
1314 ** NULL value, then *prNotFound is left unchanged.
1315 **
1316 ** If a register is allocated and its location stored in *prNotFound, then
1317 ** its initial value is NULL. If the structure does not remain constant
1318 ** for the duration of the query (i.e. the set is a correlated sub-select),
1319 ** the value of the allocated register is reset to NULL each time the
1320 ** structure is repopulated. This allows the caller to use vdbe code
1321 ** equivalent to the following:
1322 **
1323 **   if( register==NULL ){
1324 **     has_null = <test if data structure contains null>
1325 **     register = 1
1326 **   }
1327 **
1328 ** in order to avoid running the <test if data structure contains null>
1329 ** test more often than is necessary.
1330 */
1331 #ifndef SQLITE_OMIT_SUBQUERY
1332 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1333   Select *p;
1334   int eType = 0;
1335   int iTab = pParse->nTab++;
1336   int mustBeUnique = !prNotFound;
1337 
1338   /* The follwing if(...) expression is true if the SELECT is of the
1339   ** simple form:
1340   **
1341   **     SELECT <column> FROM <table>
1342   **
1343   ** If this is the case, it may be possible to use an existing table
1344   ** or index instead of generating an epheremal table.
1345   */
1346   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1347   if( isCandidateForInOpt(p) ){
1348     sqlite3 *db = pParse->db;              /* Database connection */
1349     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
1350     int iCol = pExpr->iColumn;             /* Index of column <column> */
1351     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
1352     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
1353     int iDb;                               /* Database idx for pTab */
1354 
1355     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
1356     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1357     sqlite3CodeVerifySchema(pParse, iDb);
1358     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1359 
1360     /* This function is only called from two places. In both cases the vdbe
1361     ** has already been allocated. So assume sqlite3GetVdbe() is always
1362     ** successful here.
1363     */
1364     assert(v);
1365     if( iCol<0 ){
1366       int iMem = ++pParse->nMem;
1367       int iAddr;
1368       sqlite3VdbeUsesBtree(v, iDb);
1369 
1370       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1371       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1372 
1373       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1374       eType = IN_INDEX_ROWID;
1375 
1376       sqlite3VdbeJumpHere(v, iAddr);
1377     }else{
1378       Index *pIdx;                         /* Iterator variable */
1379 
1380       /* The collation sequence used by the comparison. If an index is to
1381       ** be used in place of a temp-table, it must be ordered according
1382       ** to this collation sequence.  */
1383       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1384 
1385       /* Check that the affinity that will be used to perform the
1386       ** comparison is the same as the affinity of the column. If
1387       ** it is not, it is not possible to use any index.
1388       */
1389       char aff = comparisonAffinity(pX);
1390       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
1391 
1392       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1393         if( (pIdx->aiColumn[0]==iCol)
1394          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
1395          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1396         ){
1397           int iMem = ++pParse->nMem;
1398           int iAddr;
1399           char *pKey;
1400 
1401           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1402           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1403           sqlite3VdbeUsesBtree(v, iDb);
1404 
1405           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1406           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1407 
1408           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
1409                                pKey,P4_KEYINFO_HANDOFF);
1410           VdbeComment((v, "%s", pIdx->zName));
1411           eType = IN_INDEX_INDEX;
1412 
1413           sqlite3VdbeJumpHere(v, iAddr);
1414           if( prNotFound && !pTab->aCol[iCol].notNull ){
1415             *prNotFound = ++pParse->nMem;
1416           }
1417         }
1418       }
1419     }
1420   }
1421 
1422   if( eType==0 ){
1423     int rMayHaveNull = 0;
1424     eType = IN_INDEX_EPH;
1425     if( prNotFound ){
1426       *prNotFound = rMayHaveNull = ++pParse->nMem;
1427     }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
1428       eType = IN_INDEX_ROWID;
1429     }
1430     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1431   }else{
1432     pX->iTable = iTab;
1433   }
1434   return eType;
1435 }
1436 #endif
1437 
1438 /*
1439 ** Generate code for scalar subqueries used as an expression
1440 ** and IN operators.  Examples:
1441 **
1442 **     (SELECT a FROM b)          -- subquery
1443 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
1444 **     x IN (4,5,11)              -- IN operator with list on right-hand side
1445 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1446 **
1447 ** The pExpr parameter describes the expression that contains the IN
1448 ** operator or subquery.
1449 **
1450 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1451 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1452 ** to some integer key column of a table B-Tree. In this case, use an
1453 ** intkey B-Tree to store the set of IN(...) values instead of the usual
1454 ** (slower) variable length keys B-Tree.
1455 */
1456 #ifndef SQLITE_OMIT_SUBQUERY
1457 void sqlite3CodeSubselect(
1458   Parse *pParse,
1459   Expr *pExpr,
1460   int rMayHaveNull,
1461   int isRowid
1462 ){
1463   int testAddr = 0;                       /* One-time test address */
1464   Vdbe *v = sqlite3GetVdbe(pParse);
1465   if( v==0 ) return;
1466   sqlite3ExprCachePush(pParse);
1467 
1468   /* This code must be run in its entirety every time it is encountered
1469   ** if any of the following is true:
1470   **
1471   **    *  The right-hand side is a correlated subquery
1472   **    *  The right-hand side is an expression list containing variables
1473   **    *  We are inside a trigger
1474   **
1475   ** If all of the above are false, then we can run this code just once
1476   ** save the results, and reuse the same result on subsequent invocations.
1477   */
1478   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1479     int mem = ++pParse->nMem;
1480     sqlite3VdbeAddOp1(v, OP_If, mem);
1481     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
1482     assert( testAddr>0 || pParse->db->mallocFailed );
1483   }
1484 
1485   switch( pExpr->op ){
1486     case TK_IN: {
1487       char affinity;
1488       KeyInfo keyInfo;
1489       int addr;        /* Address of OP_OpenEphemeral instruction */
1490       Expr *pLeft = pExpr->pLeft;
1491 
1492       if( rMayHaveNull ){
1493         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
1494       }
1495 
1496       affinity = sqlite3ExprAffinity(pLeft);
1497 
1498       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1499       ** expression it is handled the same way. A virtual table is
1500       ** filled with single-field index keys representing the results
1501       ** from the SELECT or the <exprlist>.
1502       **
1503       ** If the 'x' expression is a column value, or the SELECT...
1504       ** statement returns a column value, then the affinity of that
1505       ** column is used to build the index keys. If both 'x' and the
1506       ** SELECT... statement are columns, then numeric affinity is used
1507       ** if either column has NUMERIC or INTEGER affinity. If neither
1508       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1509       ** is used.
1510       */
1511       pExpr->iTable = pParse->nTab++;
1512       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1513       memset(&keyInfo, 0, sizeof(keyInfo));
1514       keyInfo.nField = 1;
1515 
1516       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1517         /* Case 1:     expr IN (SELECT ...)
1518         **
1519         ** Generate code to write the results of the select into the temporary
1520         ** table allocated and opened above.
1521         */
1522         SelectDest dest;
1523         ExprList *pEList;
1524 
1525         assert( !isRowid );
1526         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1527         dest.affinity = (u8)affinity;
1528         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1529         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
1530           return;
1531         }
1532         pEList = pExpr->x.pSelect->pEList;
1533         if( pEList && pEList->nExpr>0 ){
1534           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1535               pEList->a[0].pExpr);
1536         }
1537       }else if( pExpr->x.pList ){
1538         /* Case 2:     expr IN (exprlist)
1539         **
1540         ** For each expression, build an index key from the evaluation and
1541         ** store it in the temporary table. If <expr> is a column, then use
1542         ** that columns affinity when building index keys. If <expr> is not
1543         ** a column, use numeric affinity.
1544         */
1545         int i;
1546         ExprList *pList = pExpr->x.pList;
1547         struct ExprList_item *pItem;
1548         int r1, r2, r3;
1549 
1550         if( !affinity ){
1551           affinity = SQLITE_AFF_NONE;
1552         }
1553         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1554 
1555         /* Loop through each expression in <exprlist>. */
1556         r1 = sqlite3GetTempReg(pParse);
1557         r2 = sqlite3GetTempReg(pParse);
1558         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
1559         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1560           Expr *pE2 = pItem->pExpr;
1561 
1562           /* If the expression is not constant then we will need to
1563           ** disable the test that was generated above that makes sure
1564           ** this code only executes once.  Because for a non-constant
1565           ** expression we need to rerun this code each time.
1566           */
1567           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1568             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
1569             testAddr = 0;
1570           }
1571 
1572           /* Evaluate the expression and insert it into the temp table */
1573           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
1574           if( isRowid ){
1575             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
1576             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
1577           }else{
1578             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
1579             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
1580             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1581           }
1582         }
1583         sqlite3ReleaseTempReg(pParse, r1);
1584         sqlite3ReleaseTempReg(pParse, r2);
1585       }
1586       if( !isRowid ){
1587         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1588       }
1589       break;
1590     }
1591 
1592     case TK_EXISTS:
1593     case TK_SELECT: {
1594       /* This has to be a scalar SELECT.  Generate code to put the
1595       ** value of this select in a memory cell and record the number
1596       ** of the memory cell in iColumn.
1597       */
1598       static const Token one = { (u8*)"1", 0, 1 };
1599       Select *pSel;
1600       SelectDest dest;
1601 
1602       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1603       pSel = pExpr->x.pSelect;
1604       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
1605       if( pExpr->op==TK_SELECT ){
1606         dest.eDest = SRT_Mem;
1607         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
1608         VdbeComment((v, "Init subquery result"));
1609       }else{
1610         dest.eDest = SRT_Exists;
1611         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
1612         VdbeComment((v, "Init EXISTS result"));
1613       }
1614       sqlite3ExprDelete(pParse->db, pSel->pLimit);
1615       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
1616       if( sqlite3Select(pParse, pSel, &dest) ){
1617         return;
1618       }
1619       pExpr->iColumn = dest.iParm;
1620       break;
1621     }
1622   }
1623 
1624   if( testAddr ){
1625     sqlite3VdbeJumpHere(v, testAddr-1);
1626   }
1627   sqlite3ExprCachePop(pParse, 1);
1628 
1629   return;
1630 }
1631 #endif /* SQLITE_OMIT_SUBQUERY */
1632 
1633 /*
1634 ** Duplicate an 8-byte value
1635 */
1636 static char *dup8bytes(Vdbe *v, const char *in){
1637   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1638   if( out ){
1639     memcpy(out, in, 8);
1640   }
1641   return out;
1642 }
1643 
1644 /*
1645 ** Generate an instruction that will put the floating point
1646 ** value described by z[0..n-1] into register iMem.
1647 **
1648 ** The z[] string will probably not be zero-terminated.  But the
1649 ** z[n] character is guaranteed to be something that does not look
1650 ** like the continuation of the number.
1651 */
1652 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
1653   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1654   assert( !z || !sqlite3Isdigit(z[n]) );
1655   UNUSED_PARAMETER(n);
1656   if( z ){
1657     double value;
1658     char *zV;
1659     sqlite3AtoF(z, &value);
1660     if( sqlite3IsNaN(value) ){
1661       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
1662     }else{
1663       if( negateFlag ) value = -value;
1664       zV = dup8bytes(v, (char*)&value);
1665       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1666     }
1667   }
1668 }
1669 
1670 
1671 /*
1672 ** Generate an instruction that will put the integer describe by
1673 ** text z[0..n-1] into register iMem.
1674 **
1675 ** The z[] string will probably not be zero-terminated.  But the
1676 ** z[n] character is guaranteed to be something that does not look
1677 ** like the continuation of the number.
1678 */
1679 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
1680   const char *z;
1681   if( pExpr->flags & EP_IntValue ){
1682     int i = pExpr->iTable;
1683     if( negFlag ) i = -i;
1684     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1685   }else if( (z = (char*)pExpr->token.z)!=0 ){
1686     int i;
1687     int n = pExpr->token.n;
1688     assert( !sqlite3Isdigit(z[n]) );
1689     if( sqlite3GetInt32(z, &i) ){
1690       if( negFlag ) i = -i;
1691       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1692     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
1693       i64 value;
1694       char *zV;
1695       sqlite3Atoi64(z, &value);
1696       if( negFlag ) value = -value;
1697       zV = dup8bytes(v, (char*)&value);
1698       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
1699     }else{
1700       codeReal(v, z, n, negFlag, iMem);
1701     }
1702   }
1703 }
1704 
1705 /*
1706 ** Clear a cache entry.
1707 */
1708 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
1709   if( p->tempReg ){
1710     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
1711       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
1712     }
1713     p->tempReg = 0;
1714   }
1715 }
1716 
1717 
1718 /*
1719 ** Record in the column cache that a particular column from a
1720 ** particular table is stored in a particular register.
1721 */
1722 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
1723   int i;
1724   int minLru;
1725   int idxLru;
1726   struct yColCache *p;
1727 
1728   /* First replace any existing entry */
1729   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1730     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
1731       cacheEntryClear(pParse, p);
1732       p->iLevel = pParse->iCacheLevel;
1733       p->iReg = iReg;
1734       p->affChange = 0;
1735       p->lru = pParse->iCacheCnt++;
1736       return;
1737     }
1738   }
1739   if( iReg<=0 ) return;
1740 
1741   /* Find an empty slot and replace it */
1742   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1743     if( p->iReg==0 ){
1744       p->iLevel = pParse->iCacheLevel;
1745       p->iTable = iTab;
1746       p->iColumn = iCol;
1747       p->iReg = iReg;
1748       p->affChange = 0;
1749       p->tempReg = 0;
1750       p->lru = pParse->iCacheCnt++;
1751       return;
1752     }
1753   }
1754 
1755   /* Replace the last recently used */
1756   minLru = 0x7fffffff;
1757   idxLru = -1;
1758   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1759     if( p->lru<minLru ){
1760       idxLru = i;
1761       minLru = p->lru;
1762     }
1763   }
1764   if( idxLru>=0 ){
1765     p = &pParse->aColCache[idxLru];
1766     p->iLevel = pParse->iCacheLevel;
1767     p->iTable = iTab;
1768     p->iColumn = iCol;
1769     p->iReg = iReg;
1770     p->affChange = 0;
1771     p->tempReg = 0;
1772     p->lru = pParse->iCacheCnt++;
1773     return;
1774   }
1775 }
1776 
1777 /*
1778 ** Indicate that a register is being overwritten.  Purge the register
1779 ** from the column cache.
1780 */
1781 void sqlite3ExprCacheRemove(Parse *pParse, int iReg){
1782   int i;
1783   struct yColCache *p;
1784   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1785     if( p->iReg==iReg ){
1786       cacheEntryClear(pParse, p);
1787       p->iReg = 0;
1788     }
1789   }
1790 }
1791 
1792 /*
1793 ** Remember the current column cache context.  Any new entries added
1794 ** added to the column cache after this call are removed when the
1795 ** corresponding pop occurs.
1796 */
1797 void sqlite3ExprCachePush(Parse *pParse){
1798   pParse->iCacheLevel++;
1799 }
1800 
1801 /*
1802 ** Remove from the column cache any entries that were added since the
1803 ** the previous N Push operations.  In other words, restore the cache
1804 ** to the state it was in N Pushes ago.
1805 */
1806 void sqlite3ExprCachePop(Parse *pParse, int N){
1807   int i;
1808   struct yColCache *p;
1809   assert( N>0 );
1810   assert( pParse->iCacheLevel>=N );
1811   pParse->iCacheLevel -= N;
1812   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1813     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
1814       cacheEntryClear(pParse, p);
1815       p->iReg = 0;
1816     }
1817   }
1818 }
1819 
1820 /*
1821 ** Generate code that will extract the iColumn-th column from
1822 ** table pTab and store the column value in a register.  An effort
1823 ** is made to store the column value in register iReg, but this is
1824 ** not guaranteed.  The location of the column value is returned.
1825 **
1826 ** There must be an open cursor to pTab in iTable when this routine
1827 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
1828 **
1829 ** This routine might attempt to reuse the value of the column that
1830 ** has already been loaded into a register.  The value will always
1831 ** be used if it has not undergone any affinity changes.  But if
1832 ** an affinity change has occurred, then the cached value will only be
1833 ** used if allowAffChng is true.
1834 */
1835 int sqlite3ExprCodeGetColumn(
1836   Parse *pParse,   /* Parsing and code generating context */
1837   Table *pTab,     /* Description of the table we are reading from */
1838   int iColumn,     /* Index of the table column */
1839   int iTable,      /* The cursor pointing to the table */
1840   int iReg,        /* Store results here */
1841   int allowAffChng /* True if prior affinity changes are OK */
1842 ){
1843   Vdbe *v = pParse->pVdbe;
1844   int i;
1845   struct yColCache *p;
1846 
1847   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1848     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn
1849            && (!p->affChange || allowAffChng) ){
1850 #if 0
1851       sqlite3VdbeAddOp0(v, OP_Noop);
1852       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
1853 #endif
1854       p->lru = pParse->iCacheCnt++;
1855       p->tempReg = 0;  /* This pins the register, but also leaks it */
1856       return p->iReg;
1857     }
1858   }
1859   assert( v!=0 );
1860   if( iColumn<0 ){
1861     sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
1862   }else if( pTab==0 ){
1863     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
1864   }else{
1865     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1866     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
1867     sqlite3ColumnDefault(v, pTab, iColumn);
1868 #ifndef SQLITE_OMIT_FLOATING_POINT
1869     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1870       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
1871     }
1872 #endif
1873   }
1874   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
1875   return iReg;
1876 }
1877 
1878 /*
1879 ** Clear all column cache entries.
1880 */
1881 void sqlite3ExprCacheClear(Parse *pParse){
1882   int i;
1883   struct yColCache *p;
1884 
1885   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1886     if( p->iReg ){
1887       cacheEntryClear(pParse, p);
1888       p->iReg = 0;
1889     }
1890   }
1891 }
1892 
1893 /*
1894 ** Record the fact that an affinity change has occurred on iCount
1895 ** registers starting with iStart.
1896 */
1897 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
1898   int iEnd = iStart + iCount - 1;
1899   int i;
1900   struct yColCache *p;
1901   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1902     int r = p->iReg;
1903     if( r>=iStart && r<=iEnd ){
1904       p->affChange = 1;
1905     }
1906   }
1907 }
1908 
1909 /*
1910 ** Generate code to move content from registers iFrom...iFrom+nReg-1
1911 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
1912 */
1913 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
1914   int i;
1915   struct yColCache *p;
1916   if( iFrom==iTo ) return;
1917   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
1918   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1919     int x = p->iReg;
1920     if( x>=iFrom && x<iFrom+nReg ){
1921       p->iReg += iTo-iFrom;
1922     }
1923   }
1924 }
1925 
1926 /*
1927 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
1928 ** over to iTo..iTo+nReg-1.
1929 */
1930 void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
1931   int i;
1932   if( iFrom==iTo ) return;
1933   for(i=0; i<nReg; i++){
1934     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
1935   }
1936 }
1937 
1938 /*
1939 ** Return true if any register in the range iFrom..iTo (inclusive)
1940 ** is used as part of the column cache.
1941 */
1942 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
1943   int i;
1944   struct yColCache *p;
1945   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1946     int r = p->iReg;
1947     if( r>=iFrom && r<=iTo ) return 1;
1948   }
1949   return 0;
1950 }
1951 
1952 /*
1953 ** If the last instruction coded is an ephemeral copy of any of
1954 ** the registers in the nReg registers beginning with iReg, then
1955 ** convert the last instruction from OP_SCopy to OP_Copy.
1956 */
1957 void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
1958   int addr;
1959   VdbeOp *pOp;
1960   Vdbe *v;
1961 
1962   v = pParse->pVdbe;
1963   addr = sqlite3VdbeCurrentAddr(v);
1964   pOp = sqlite3VdbeGetOp(v, addr-1);
1965   assert( pOp || pParse->db->mallocFailed );
1966   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
1967     pOp->opcode = OP_Copy;
1968   }
1969 }
1970 
1971 /*
1972 ** Generate code to store the value of the iAlias-th alias in register
1973 ** target.  The first time this is called, pExpr is evaluated to compute
1974 ** the value of the alias.  The value is stored in an auxiliary register
1975 ** and the number of that register is returned.  On subsequent calls,
1976 ** the register number is returned without generating any code.
1977 **
1978 ** Note that in order for this to work, code must be generated in the
1979 ** same order that it is executed.
1980 **
1981 ** Aliases are numbered starting with 1.  So iAlias is in the range
1982 ** of 1 to pParse->nAlias inclusive.
1983 **
1984 ** pParse->aAlias[iAlias-1] records the register number where the value
1985 ** of the iAlias-th alias is stored.  If zero, that means that the
1986 ** alias has not yet been computed.
1987 */
1988 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
1989 #if 0
1990   sqlite3 *db = pParse->db;
1991   int iReg;
1992   if( pParse->nAliasAlloc<pParse->nAlias ){
1993     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
1994                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
1995     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
1996     if( db->mallocFailed ) return 0;
1997     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
1998            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
1999     pParse->nAliasAlloc = pParse->nAlias;
2000   }
2001   assert( iAlias>0 && iAlias<=pParse->nAlias );
2002   iReg = pParse->aAlias[iAlias-1];
2003   if( iReg==0 ){
2004     if( pParse->iCacheLevel>0 ){
2005       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2006     }else{
2007       iReg = ++pParse->nMem;
2008       sqlite3ExprCode(pParse, pExpr, iReg);
2009       pParse->aAlias[iAlias-1] = iReg;
2010     }
2011   }
2012   return iReg;
2013 #else
2014   return sqlite3ExprCodeTarget(pParse, pExpr, target);
2015 #endif
2016 }
2017 
2018 /*
2019 ** Generate code into the current Vdbe to evaluate the given
2020 ** expression.  Attempt to store the results in register "target".
2021 ** Return the register where results are stored.
2022 **
2023 ** With this routine, there is no guarantee that results will
2024 ** be stored in target.  The result might be stored in some other
2025 ** register if it is convenient to do so.  The calling function
2026 ** must check the return code and move the results to the desired
2027 ** register.
2028 */
2029 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
2030   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
2031   int op;                   /* The opcode being coded */
2032   int inReg = target;       /* Results stored in register inReg */
2033   int regFree1 = 0;         /* If non-zero free this temporary register */
2034   int regFree2 = 0;         /* If non-zero free this temporary register */
2035   int r1, r2, r3, r4;       /* Various register numbers */
2036   sqlite3 *db;
2037 
2038   db = pParse->db;
2039   assert( v!=0 || db->mallocFailed );
2040   assert( target>0 && target<=pParse->nMem );
2041   if( v==0 ) return 0;
2042 
2043   if( pExpr==0 ){
2044     op = TK_NULL;
2045   }else{
2046     op = pExpr->op;
2047   }
2048   switch( op ){
2049     case TK_AGG_COLUMN: {
2050       AggInfo *pAggInfo = pExpr->pAggInfo;
2051       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2052       if( !pAggInfo->directMode ){
2053         assert( pCol->iMem>0 );
2054         inReg = pCol->iMem;
2055         break;
2056       }else if( pAggInfo->useSortingIdx ){
2057         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
2058                               pCol->iSorterColumn, target);
2059         break;
2060       }
2061       /* Otherwise, fall thru into the TK_COLUMN case */
2062     }
2063     case TK_COLUMN: {
2064       if( pExpr->iTable<0 ){
2065         /* This only happens when coding check constraints */
2066         assert( pParse->ckBase>0 );
2067         inReg = pExpr->iColumn + pParse->ckBase;
2068       }else{
2069         testcase( (pExpr->flags & EP_AnyAff)!=0 );
2070         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2071                                  pExpr->iColumn, pExpr->iTable, target,
2072                                  pExpr->flags & EP_AnyAff);
2073       }
2074       break;
2075     }
2076     case TK_INTEGER: {
2077       codeInteger(v, pExpr, 0, target);
2078       break;
2079     }
2080     case TK_FLOAT: {
2081       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
2082       break;
2083     }
2084     case TK_STRING: {
2085       sqlite3DequoteExpr(pExpr);
2086       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
2087                         (char*)pExpr->token.z, pExpr->token.n);
2088       break;
2089     }
2090     case TK_NULL: {
2091       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2092       break;
2093     }
2094 #ifndef SQLITE_OMIT_BLOB_LITERAL
2095     case TK_BLOB: {
2096       int n;
2097       const char *z;
2098       char *zBlob;
2099       assert( pExpr->token.n>=3 );
2100       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
2101       assert( pExpr->token.z[1]=='\'' );
2102       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
2103       n = pExpr->token.n - 3;
2104       z = (char*)pExpr->token.z + 2;
2105       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2106       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2107       break;
2108     }
2109 #endif
2110     case TK_VARIABLE: {
2111       int iPrior;
2112       VdbeOp *pOp;
2113       if( pExpr->token.n<=1
2114          && (iPrior = sqlite3VdbeCurrentAddr(v)-1)>=0
2115          && (pOp = sqlite3VdbeGetOp(v, iPrior))->opcode==OP_Variable
2116          && pOp->p1+pOp->p3==pExpr->iTable
2117          && pOp->p2+pOp->p3==target
2118          && pOp->p4.z==0
2119       ){
2120         /* If the previous instruction was a copy of the previous unnamed
2121         ** parameter into the previous register, then simply increment the
2122         ** repeat count on the prior instruction rather than making a new
2123         ** instruction.
2124         */
2125         pOp->p3++;
2126       }else{
2127         sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iTable, target, 1);
2128         if( pExpr->token.n>1 ){
2129           sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
2130         }
2131       }
2132       break;
2133     }
2134     case TK_REGISTER: {
2135       inReg = pExpr->iTable;
2136       break;
2137     }
2138     case TK_AS: {
2139       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
2140       break;
2141     }
2142 #ifndef SQLITE_OMIT_CAST
2143     case TK_CAST: {
2144       /* Expressions of the form:   CAST(pLeft AS token) */
2145       int aff, to_op;
2146       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2147       aff = sqlite3AffinityType(&pExpr->token);
2148       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2149       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
2150       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
2151       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2152       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
2153       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
2154       testcase( to_op==OP_ToText );
2155       testcase( to_op==OP_ToBlob );
2156       testcase( to_op==OP_ToNumeric );
2157       testcase( to_op==OP_ToInt );
2158       testcase( to_op==OP_ToReal );
2159       if( inReg!=target ){
2160         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
2161         inReg = target;
2162       }
2163       sqlite3VdbeAddOp1(v, to_op, inReg);
2164       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2165       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2166       break;
2167     }
2168 #endif /* SQLITE_OMIT_CAST */
2169     case TK_LT:
2170     case TK_LE:
2171     case TK_GT:
2172     case TK_GE:
2173     case TK_NE:
2174     case TK_EQ: {
2175       assert( TK_LT==OP_Lt );
2176       assert( TK_LE==OP_Le );
2177       assert( TK_GT==OP_Gt );
2178       assert( TK_GE==OP_Ge );
2179       assert( TK_EQ==OP_Eq );
2180       assert( TK_NE==OP_Ne );
2181       testcase( op==TK_LT );
2182       testcase( op==TK_LE );
2183       testcase( op==TK_GT );
2184       testcase( op==TK_GE );
2185       testcase( op==TK_EQ );
2186       testcase( op==TK_NE );
2187       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2188                                   pExpr->pRight, &r2, &regFree2);
2189       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2190                   r1, r2, inReg, SQLITE_STOREP2);
2191       testcase( regFree1==0 );
2192       testcase( regFree2==0 );
2193       break;
2194     }
2195     case TK_AND:
2196     case TK_OR:
2197     case TK_PLUS:
2198     case TK_STAR:
2199     case TK_MINUS:
2200     case TK_REM:
2201     case TK_BITAND:
2202     case TK_BITOR:
2203     case TK_SLASH:
2204     case TK_LSHIFT:
2205     case TK_RSHIFT:
2206     case TK_CONCAT: {
2207       assert( TK_AND==OP_And );
2208       assert( TK_OR==OP_Or );
2209       assert( TK_PLUS==OP_Add );
2210       assert( TK_MINUS==OP_Subtract );
2211       assert( TK_REM==OP_Remainder );
2212       assert( TK_BITAND==OP_BitAnd );
2213       assert( TK_BITOR==OP_BitOr );
2214       assert( TK_SLASH==OP_Divide );
2215       assert( TK_LSHIFT==OP_ShiftLeft );
2216       assert( TK_RSHIFT==OP_ShiftRight );
2217       assert( TK_CONCAT==OP_Concat );
2218       testcase( op==TK_AND );
2219       testcase( op==TK_OR );
2220       testcase( op==TK_PLUS );
2221       testcase( op==TK_MINUS );
2222       testcase( op==TK_REM );
2223       testcase( op==TK_BITAND );
2224       testcase( op==TK_BITOR );
2225       testcase( op==TK_SLASH );
2226       testcase( op==TK_LSHIFT );
2227       testcase( op==TK_RSHIFT );
2228       testcase( op==TK_CONCAT );
2229       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2230       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2231       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2232       testcase( regFree1==0 );
2233       testcase( regFree2==0 );
2234       break;
2235     }
2236     case TK_UMINUS: {
2237       Expr *pLeft = pExpr->pLeft;
2238       assert( pLeft );
2239       if( pLeft->op==TK_FLOAT ){
2240         codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
2241       }else if( pLeft->op==TK_INTEGER ){
2242         codeInteger(v, pLeft, 1, target);
2243       }else{
2244         regFree1 = r1 = sqlite3GetTempReg(pParse);
2245         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2246         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
2247         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2248         testcase( regFree2==0 );
2249       }
2250       inReg = target;
2251       break;
2252     }
2253     case TK_BITNOT:
2254     case TK_NOT: {
2255       assert( TK_BITNOT==OP_BitNot );
2256       assert( TK_NOT==OP_Not );
2257       testcase( op==TK_BITNOT );
2258       testcase( op==TK_NOT );
2259       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2260       testcase( regFree1==0 );
2261       inReg = target;
2262       sqlite3VdbeAddOp2(v, op, r1, inReg);
2263       break;
2264     }
2265     case TK_ISNULL:
2266     case TK_NOTNULL: {
2267       int addr;
2268       assert( TK_ISNULL==OP_IsNull );
2269       assert( TK_NOTNULL==OP_NotNull );
2270       testcase( op==TK_ISNULL );
2271       testcase( op==TK_NOTNULL );
2272       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2273       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2274       testcase( regFree1==0 );
2275       addr = sqlite3VdbeAddOp1(v, op, r1);
2276       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
2277       sqlite3VdbeJumpHere(v, addr);
2278       break;
2279     }
2280     case TK_AGG_FUNCTION: {
2281       AggInfo *pInfo = pExpr->pAggInfo;
2282       if( pInfo==0 ){
2283         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
2284             &pExpr->span);
2285       }else{
2286         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
2287       }
2288       break;
2289     }
2290     case TK_CONST_FUNC:
2291     case TK_FUNCTION: {
2292       ExprList *pFarg;       /* List of function arguments */
2293       int nFarg;             /* Number of function arguments */
2294       FuncDef *pDef;         /* The function definition object */
2295       int nId;               /* Length of the function name in bytes */
2296       const char *zId;       /* The function name */
2297       int constMask = 0;     /* Mask of function arguments that are constant */
2298       int i;                 /* Loop counter */
2299       u8 enc = ENC(db);      /* The text encoding used by this database */
2300       CollSeq *pColl = 0;    /* A collating sequence */
2301 
2302       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2303       testcase( op==TK_CONST_FUNC );
2304       testcase( op==TK_FUNCTION );
2305       if( ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_SpanToken) ){
2306         pFarg = 0;
2307       }else{
2308         pFarg = pExpr->x.pList;
2309       }
2310       nFarg = pFarg ? pFarg->nExpr : 0;
2311       zId = (char*)pExpr->token.z;
2312       nId = pExpr->token.n;
2313       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
2314       assert( pDef!=0 );
2315       if( pFarg ){
2316         r1 = sqlite3GetTempRange(pParse, nFarg);
2317         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
2318       }else{
2319         r1 = 0;
2320       }
2321 #ifndef SQLITE_OMIT_VIRTUALTABLE
2322       /* Possibly overload the function if the first argument is
2323       ** a virtual table column.
2324       **
2325       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2326       ** second argument, not the first, as the argument to test to
2327       ** see if it is a column in a virtual table.  This is done because
2328       ** the left operand of infix functions (the operand we want to
2329       ** control overloading) ends up as the second argument to the
2330       ** function.  The expression "A glob B" is equivalent to
2331       ** "glob(B,A).  We want to use the A in "A glob B" to test
2332       ** for function overloading.  But we use the B term in "glob(B,A)".
2333       */
2334       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
2335         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
2336       }else if( nFarg>0 ){
2337         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2338       }
2339 #endif
2340       for(i=0; i<nFarg && i<32; i++){
2341         if( sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2342           constMask |= (1<<i);
2343         }
2344         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2345           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2346         }
2347       }
2348       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
2349         if( !pColl ) pColl = db->pDfltColl;
2350         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2351       }
2352       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
2353                         (char*)pDef, P4_FUNCDEF);
2354       sqlite3VdbeChangeP5(v, (u8)nFarg);
2355       if( nFarg ){
2356         sqlite3ReleaseTempRange(pParse, r1, nFarg);
2357       }
2358       sqlite3ExprCacheAffinityChange(pParse, r1, nFarg);
2359       break;
2360     }
2361 #ifndef SQLITE_OMIT_SUBQUERY
2362     case TK_EXISTS:
2363     case TK_SELECT: {
2364       testcase( op==TK_EXISTS );
2365       testcase( op==TK_SELECT );
2366       if( pExpr->iColumn==0 ){
2367         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
2368       }
2369       inReg = pExpr->iColumn;
2370       break;
2371     }
2372     case TK_IN: {
2373       int rNotFound = 0;
2374       int rMayHaveNull = 0;
2375       int j2, j3, j4, j5;
2376       char affinity;
2377       int eType;
2378 
2379       VdbeNoopComment((v, "begin IN expr r%d", target));
2380       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
2381       if( rMayHaveNull ){
2382         rNotFound = ++pParse->nMem;
2383       }
2384 
2385       /* Figure out the affinity to use to create a key from the results
2386       ** of the expression. affinityStr stores a static string suitable for
2387       ** P4 of OP_MakeRecord.
2388       */
2389       affinity = comparisonAffinity(pExpr);
2390 
2391 
2392       /* Code the <expr> from "<expr> IN (...)". The temporary table
2393       ** pExpr->iTable contains the values that make up the (...) set.
2394       */
2395       sqlite3ExprCachePush(pParse);
2396       sqlite3ExprCode(pParse, pExpr->pLeft, target);
2397       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
2398       if( eType==IN_INDEX_ROWID ){
2399         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
2400         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
2401         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2402         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
2403         sqlite3VdbeJumpHere(v, j3);
2404         sqlite3VdbeJumpHere(v, j4);
2405         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
2406       }else{
2407         r2 = regFree2 = sqlite3GetTempReg(pParse);
2408 
2409         /* Create a record and test for set membership. If the set contains
2410         ** the value, then jump to the end of the test code. The target
2411         ** register still contains the true (1) value written to it earlier.
2412         */
2413         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
2414         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2415         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
2416 
2417         /* If the set membership test fails, then the result of the
2418         ** "x IN (...)" expression must be either 0 or NULL. If the set
2419         ** contains no NULL values, then the result is 0. If the set
2420         ** contains one or more NULL values, then the result of the
2421         ** expression is also NULL.
2422         */
2423         if( rNotFound==0 ){
2424           /* This branch runs if it is known at compile time (now) that
2425           ** the set contains no NULL values. This happens as the result
2426           ** of a "NOT NULL" constraint in the database schema. No need
2427           ** to test the data structure at runtime in this case.
2428           */
2429           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
2430         }else{
2431           /* This block populates the rNotFound register with either NULL
2432           ** or 0 (an integer value). If the data structure contains one
2433           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
2434           ** to 0. If register rMayHaveNull is already set to some value
2435           ** other than NULL, then the test has already been run and
2436           ** rNotFound is already populated.
2437           */
2438           static const char nullRecord[] = { 0x02, 0x00 };
2439           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
2440           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
2441           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0,
2442                              nullRecord, P4_STATIC);
2443           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
2444           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
2445           sqlite3VdbeJumpHere(v, j4);
2446           sqlite3VdbeJumpHere(v, j3);
2447 
2448           /* Copy the value of register rNotFound (which is either NULL or 0)
2449           ** into the target register. This will be the result of the
2450           ** expression.
2451           */
2452           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
2453         }
2454       }
2455       sqlite3VdbeJumpHere(v, j2);
2456       sqlite3VdbeJumpHere(v, j5);
2457       sqlite3ExprCachePop(pParse, 1);
2458       VdbeComment((v, "end IN expr r%d", target));
2459       break;
2460     }
2461 #endif
2462     /*
2463     **    x BETWEEN y AND z
2464     **
2465     ** This is equivalent to
2466     **
2467     **    x>=y AND x<=z
2468     **
2469     ** X is stored in pExpr->pLeft.
2470     ** Y is stored in pExpr->pList->a[0].pExpr.
2471     ** Z is stored in pExpr->pList->a[1].pExpr.
2472     */
2473     case TK_BETWEEN: {
2474       Expr *pLeft = pExpr->pLeft;
2475       struct ExprList_item *pLItem = pExpr->x.pList->a;
2476       Expr *pRight = pLItem->pExpr;
2477 
2478       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
2479                                   pRight, &r2, &regFree2);
2480       testcase( regFree1==0 );
2481       testcase( regFree2==0 );
2482       r3 = sqlite3GetTempReg(pParse);
2483       r4 = sqlite3GetTempReg(pParse);
2484       codeCompare(pParse, pLeft, pRight, OP_Ge,
2485                   r1, r2, r3, SQLITE_STOREP2);
2486       pLItem++;
2487       pRight = pLItem->pExpr;
2488       sqlite3ReleaseTempReg(pParse, regFree2);
2489       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2490       testcase( regFree2==0 );
2491       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2492       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
2493       sqlite3ReleaseTempReg(pParse, r3);
2494       sqlite3ReleaseTempReg(pParse, r4);
2495       break;
2496     }
2497     case TK_UPLUS: {
2498       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2499       break;
2500     }
2501 
2502     /*
2503     ** Form A:
2504     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2505     **
2506     ** Form B:
2507     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2508     **
2509     ** Form A is can be transformed into the equivalent form B as follows:
2510     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
2511     **        WHEN x=eN THEN rN ELSE y END
2512     **
2513     ** X (if it exists) is in pExpr->pLeft.
2514     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
2515     ** ELSE clause and no other term matches, then the result of the
2516     ** exprssion is NULL.
2517     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
2518     **
2519     ** The result of the expression is the Ri for the first matching Ei,
2520     ** or if there is no matching Ei, the ELSE term Y, or if there is
2521     ** no ELSE term, NULL.
2522     */
2523     case TK_CASE: {
2524       int endLabel;                     /* GOTO label for end of CASE stmt */
2525       int nextCase;                     /* GOTO label for next WHEN clause */
2526       int nExpr;                        /* 2x number of WHEN terms */
2527       int i;                            /* Loop counter */
2528       ExprList *pEList;                 /* List of WHEN terms */
2529       struct ExprList_item *aListelem;  /* Array of WHEN terms */
2530       Expr opCompare;                   /* The X==Ei expression */
2531       Expr cacheX;                      /* Cached expression X */
2532       Expr *pX;                         /* The X expression */
2533       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
2534       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
2535 
2536       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
2537       assert((pExpr->x.pList->nExpr % 2) == 0);
2538       assert(pExpr->x.pList->nExpr > 0);
2539       pEList = pExpr->x.pList;
2540       aListelem = pEList->a;
2541       nExpr = pEList->nExpr;
2542       endLabel = sqlite3VdbeMakeLabel(v);
2543       if( (pX = pExpr->pLeft)!=0 ){
2544         cacheX = *pX;
2545         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
2546         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
2547         testcase( regFree1==0 );
2548         cacheX.op = TK_REGISTER;
2549         opCompare.op = TK_EQ;
2550         opCompare.pLeft = &cacheX;
2551         pTest = &opCompare;
2552       }
2553       for(i=0; i<nExpr; i=i+2){
2554         sqlite3ExprCachePush(pParse);
2555         if( pX ){
2556           assert( pTest!=0 );
2557           opCompare.pRight = aListelem[i].pExpr;
2558         }else{
2559           pTest = aListelem[i].pExpr;
2560         }
2561         nextCase = sqlite3VdbeMakeLabel(v);
2562         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
2563         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2564         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2565         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
2566         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
2567         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2568         sqlite3ExprCachePop(pParse, 1);
2569         sqlite3VdbeResolveLabel(v, nextCase);
2570       }
2571       if( pExpr->pRight ){
2572         sqlite3ExprCachePush(pParse);
2573         sqlite3ExprCode(pParse, pExpr->pRight, target);
2574         sqlite3ExprCachePop(pParse, 1);
2575       }else{
2576         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2577       }
2578       assert( db->mallocFailed || pParse->nErr>0
2579            || pParse->iCacheLevel==iCacheLevel );
2580       sqlite3VdbeResolveLabel(v, endLabel);
2581       break;
2582     }
2583 #ifndef SQLITE_OMIT_TRIGGER
2584     case TK_RAISE: {
2585       if( !pParse->trigStack ){
2586         sqlite3ErrorMsg(pParse,
2587                        "RAISE() may only be used within a trigger-program");
2588         return 0;
2589       }
2590       if( pExpr->affinity!=OE_Ignore ){
2591          assert( pExpr->affinity==OE_Rollback ||
2592                  pExpr->affinity == OE_Abort ||
2593                  pExpr->affinity == OE_Fail );
2594          sqlite3DequoteExpr(pExpr);
2595          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
2596                         (char*)pExpr->token.z, pExpr->token.n);
2597       } else {
2598          assert( pExpr->affinity == OE_Ignore );
2599          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
2600          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2601          VdbeComment((v, "raise(IGNORE)"));
2602       }
2603       break;
2604     }
2605 #endif
2606   }
2607   sqlite3ReleaseTempReg(pParse, regFree1);
2608   sqlite3ReleaseTempReg(pParse, regFree2);
2609   return inReg;
2610 }
2611 
2612 /*
2613 ** Generate code to evaluate an expression and store the results
2614 ** into a register.  Return the register number where the results
2615 ** are stored.
2616 **
2617 ** If the register is a temporary register that can be deallocated,
2618 ** then write its number into *pReg.  If the result register is not
2619 ** a temporary, then set *pReg to zero.
2620 */
2621 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
2622   int r1 = sqlite3GetTempReg(pParse);
2623   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2624   if( r2==r1 ){
2625     *pReg = r1;
2626   }else{
2627     sqlite3ReleaseTempReg(pParse, r1);
2628     *pReg = 0;
2629   }
2630   return r2;
2631 }
2632 
2633 /*
2634 ** Generate code that will evaluate expression pExpr and store the
2635 ** results in register target.  The results are guaranteed to appear
2636 ** in register target.
2637 */
2638 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
2639   int inReg;
2640 
2641   assert( target>0 && target<=pParse->nMem );
2642   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2643   assert( pParse->pVdbe || pParse->db->mallocFailed );
2644   if( inReg!=target && pParse->pVdbe ){
2645     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
2646   }
2647   return target;
2648 }
2649 
2650 /*
2651 ** Generate code that evalutes the given expression and puts the result
2652 ** in register target.
2653 **
2654 ** Also make a copy of the expression results into another "cache" register
2655 ** and modify the expression so that the next time it is evaluated,
2656 ** the result is a copy of the cache register.
2657 **
2658 ** This routine is used for expressions that are used multiple
2659 ** times.  They are evaluated once and the results of the expression
2660 ** are reused.
2661 */
2662 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
2663   Vdbe *v = pParse->pVdbe;
2664   int inReg;
2665   inReg = sqlite3ExprCode(pParse, pExpr, target);
2666   assert( target>0 );
2667   if( pExpr->op!=TK_REGISTER ){
2668     int iMem;
2669     iMem = ++pParse->nMem;
2670     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
2671     pExpr->iTable = iMem;
2672     pExpr->op = TK_REGISTER;
2673   }
2674   return inReg;
2675 }
2676 
2677 /*
2678 ** Return TRUE if pExpr is an constant expression that is appropriate
2679 ** for factoring out of a loop.  Appropriate expressions are:
2680 **
2681 **    *  Any expression that evaluates to two or more opcodes.
2682 **
2683 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
2684 **       or OP_Variable that does not need to be placed in a
2685 **       specific register.
2686 **
2687 ** There is no point in factoring out single-instruction constant
2688 ** expressions that need to be placed in a particular register.
2689 ** We could factor them out, but then we would end up adding an
2690 ** OP_SCopy instruction to move the value into the correct register
2691 ** later.  We might as well just use the original instruction and
2692 ** avoid the OP_SCopy.
2693 */
2694 static int isAppropriateForFactoring(Expr *p){
2695   if( !sqlite3ExprIsConstantNotJoin(p) ){
2696     return 0;  /* Only constant expressions are appropriate for factoring */
2697   }
2698   if( (p->flags & EP_FixedDest)==0 ){
2699     return 1;  /* Any constant without a fixed destination is appropriate */
2700   }
2701   while( p->op==TK_UPLUS ) p = p->pLeft;
2702   switch( p->op ){
2703 #ifndef SQLITE_OMIT_BLOB_LITERAL
2704     case TK_BLOB:
2705 #endif
2706     case TK_VARIABLE:
2707     case TK_INTEGER:
2708     case TK_FLOAT:
2709     case TK_NULL:
2710     case TK_STRING: {
2711       testcase( p->op==TK_BLOB );
2712       testcase( p->op==TK_VARIABLE );
2713       testcase( p->op==TK_INTEGER );
2714       testcase( p->op==TK_FLOAT );
2715       testcase( p->op==TK_NULL );
2716       testcase( p->op==TK_STRING );
2717       /* Single-instruction constants with a fixed destination are
2718       ** better done in-line.  If we factor them, they will just end
2719       ** up generating an OP_SCopy to move the value to the destination
2720       ** register. */
2721       return 0;
2722     }
2723     case TK_UMINUS: {
2724        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
2725          return 0;
2726        }
2727        break;
2728     }
2729     default: {
2730       break;
2731     }
2732   }
2733   return 1;
2734 }
2735 
2736 /*
2737 ** If pExpr is a constant expression that is appropriate for
2738 ** factoring out of a loop, then evaluate the expression
2739 ** into a register and convert the expression into a TK_REGISTER
2740 ** expression.
2741 */
2742 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
2743   Parse *pParse = pWalker->pParse;
2744   switch( pExpr->op ){
2745     case TK_REGISTER: {
2746       return 1;
2747     }
2748     case TK_FUNCTION:
2749     case TK_AGG_FUNCTION:
2750     case TK_CONST_FUNC: {
2751       /* The arguments to a function have a fixed destination.
2752       ** Mark them this way to avoid generated unneeded OP_SCopy
2753       ** instructions.
2754       */
2755       ExprList *pList = pExpr->x.pList;
2756       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2757       if( pList ){
2758         int i = pList->nExpr;
2759         struct ExprList_item *pItem = pList->a;
2760         for(; i>0; i--, pItem++){
2761           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
2762         }
2763       }
2764       break;
2765     }
2766   }
2767   if( isAppropriateForFactoring(pExpr) ){
2768     int r1 = ++pParse->nMem;
2769     int r2;
2770     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2771     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
2772     pExpr->op = TK_REGISTER;
2773     pExpr->iTable = r2;
2774     return WRC_Prune;
2775   }
2776   return WRC_Continue;
2777 }
2778 
2779 /*
2780 ** Preevaluate constant subexpressions within pExpr and store the
2781 ** results in registers.  Modify pExpr so that the constant subexpresions
2782 ** are TK_REGISTER opcodes that refer to the precomputed values.
2783 */
2784 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
2785   Walker w;
2786   w.xExprCallback = evalConstExpr;
2787   w.xSelectCallback = 0;
2788   w.pParse = pParse;
2789   sqlite3WalkExpr(&w, pExpr);
2790 }
2791 
2792 
2793 /*
2794 ** Generate code that pushes the value of every element of the given
2795 ** expression list into a sequence of registers beginning at target.
2796 **
2797 ** Return the number of elements evaluated.
2798 */
2799 int sqlite3ExprCodeExprList(
2800   Parse *pParse,     /* Parsing context */
2801   ExprList *pList,   /* The expression list to be coded */
2802   int target,        /* Where to write results */
2803   int doHardCopy     /* Make a hard copy of every element */
2804 ){
2805   struct ExprList_item *pItem;
2806   int i, n;
2807   assert( pList!=0 );
2808   assert( target>0 );
2809   n = pList->nExpr;
2810   for(pItem=pList->a, i=0; i<n; i++, pItem++){
2811     if( pItem->iAlias ){
2812       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
2813       Vdbe *v = sqlite3GetVdbe(pParse);
2814       if( iReg!=target+i ){
2815         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
2816       }
2817     }else{
2818       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
2819     }
2820     if( doHardCopy ){
2821       sqlite3ExprHardCopy(pParse, target, n);
2822     }
2823   }
2824   return n;
2825 }
2826 
2827 /*
2828 ** Generate code for a boolean expression such that a jump is made
2829 ** to the label "dest" if the expression is true but execution
2830 ** continues straight thru if the expression is false.
2831 **
2832 ** If the expression evaluates to NULL (neither true nor false), then
2833 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
2834 **
2835 ** This code depends on the fact that certain token values (ex: TK_EQ)
2836 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2837 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2838 ** the make process cause these values to align.  Assert()s in the code
2839 ** below verify that the numbers are aligned correctly.
2840 */
2841 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2842   Vdbe *v = pParse->pVdbe;
2843   int op = 0;
2844   int regFree1 = 0;
2845   int regFree2 = 0;
2846   int r1, r2;
2847 
2848   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
2849   if( v==0 || pExpr==0 ) return;
2850   op = pExpr->op;
2851   switch( op ){
2852     case TK_AND: {
2853       int d2 = sqlite3VdbeMakeLabel(v);
2854       testcase( jumpIfNull==0 );
2855       sqlite3ExprCachePush(pParse);
2856       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
2857       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2858       sqlite3VdbeResolveLabel(v, d2);
2859       sqlite3ExprCachePop(pParse, 1);
2860       break;
2861     }
2862     case TK_OR: {
2863       testcase( jumpIfNull==0 );
2864       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2865       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2866       break;
2867     }
2868     case TK_NOT: {
2869       testcase( jumpIfNull==0 );
2870       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2871       break;
2872     }
2873     case TK_LT:
2874     case TK_LE:
2875     case TK_GT:
2876     case TK_GE:
2877     case TK_NE:
2878     case TK_EQ: {
2879       assert( TK_LT==OP_Lt );
2880       assert( TK_LE==OP_Le );
2881       assert( TK_GT==OP_Gt );
2882       assert( TK_GE==OP_Ge );
2883       assert( TK_EQ==OP_Eq );
2884       assert( TK_NE==OP_Ne );
2885       testcase( op==TK_LT );
2886       testcase( op==TK_LE );
2887       testcase( op==TK_GT );
2888       testcase( op==TK_GE );
2889       testcase( op==TK_EQ );
2890       testcase( op==TK_NE );
2891       testcase( jumpIfNull==0 );
2892       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2893                                   pExpr->pRight, &r2, &regFree2);
2894       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2895                   r1, r2, dest, jumpIfNull);
2896       testcase( regFree1==0 );
2897       testcase( regFree2==0 );
2898       break;
2899     }
2900     case TK_ISNULL:
2901     case TK_NOTNULL: {
2902       assert( TK_ISNULL==OP_IsNull );
2903       assert( TK_NOTNULL==OP_NotNull );
2904       testcase( op==TK_ISNULL );
2905       testcase( op==TK_NOTNULL );
2906       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2907       sqlite3VdbeAddOp2(v, op, r1, dest);
2908       testcase( regFree1==0 );
2909       break;
2910     }
2911     case TK_BETWEEN: {
2912       /*    x BETWEEN y AND z
2913       **
2914       ** Is equivalent to
2915       **
2916       **    x>=y AND x<=z
2917       **
2918       ** Code it as such, taking care to do the common subexpression
2919       ** elementation of x.
2920       */
2921       Expr exprAnd;
2922       Expr compLeft;
2923       Expr compRight;
2924       Expr exprX;
2925 
2926       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2927       exprX = *pExpr->pLeft;
2928       exprAnd.op = TK_AND;
2929       exprAnd.pLeft = &compLeft;
2930       exprAnd.pRight = &compRight;
2931       compLeft.op = TK_GE;
2932       compLeft.pLeft = &exprX;
2933       compLeft.pRight = pExpr->x.pList->a[0].pExpr;
2934       compRight.op = TK_LE;
2935       compRight.pLeft = &exprX;
2936       compRight.pRight = pExpr->x.pList->a[1].pExpr;
2937       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
2938       testcase( regFree1==0 );
2939       exprX.op = TK_REGISTER;
2940       testcase( jumpIfNull==0 );
2941       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
2942       break;
2943     }
2944     default: {
2945       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
2946       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
2947       testcase( regFree1==0 );
2948       testcase( jumpIfNull==0 );
2949       break;
2950     }
2951   }
2952   sqlite3ReleaseTempReg(pParse, regFree1);
2953   sqlite3ReleaseTempReg(pParse, regFree2);
2954 }
2955 
2956 /*
2957 ** Generate code for a boolean expression such that a jump is made
2958 ** to the label "dest" if the expression is false but execution
2959 ** continues straight thru if the expression is true.
2960 **
2961 ** If the expression evaluates to NULL (neither true nor false) then
2962 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
2963 ** is 0.
2964 */
2965 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2966   Vdbe *v = pParse->pVdbe;
2967   int op = 0;
2968   int regFree1 = 0;
2969   int regFree2 = 0;
2970   int r1, r2;
2971 
2972   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
2973   if( v==0 || pExpr==0 ) return;
2974 
2975   /* The value of pExpr->op and op are related as follows:
2976   **
2977   **       pExpr->op            op
2978   **       ---------          ----------
2979   **       TK_ISNULL          OP_NotNull
2980   **       TK_NOTNULL         OP_IsNull
2981   **       TK_NE              OP_Eq
2982   **       TK_EQ              OP_Ne
2983   **       TK_GT              OP_Le
2984   **       TK_LE              OP_Gt
2985   **       TK_GE              OP_Lt
2986   **       TK_LT              OP_Ge
2987   **
2988   ** For other values of pExpr->op, op is undefined and unused.
2989   ** The value of TK_ and OP_ constants are arranged such that we
2990   ** can compute the mapping above using the following expression.
2991   ** Assert()s verify that the computation is correct.
2992   */
2993   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2994 
2995   /* Verify correct alignment of TK_ and OP_ constants
2996   */
2997   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2998   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2999   assert( pExpr->op!=TK_NE || op==OP_Eq );
3000   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3001   assert( pExpr->op!=TK_LT || op==OP_Ge );
3002   assert( pExpr->op!=TK_LE || op==OP_Gt );
3003   assert( pExpr->op!=TK_GT || op==OP_Le );
3004   assert( pExpr->op!=TK_GE || op==OP_Lt );
3005 
3006   switch( pExpr->op ){
3007     case TK_AND: {
3008       testcase( jumpIfNull==0 );
3009       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3010       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3011       break;
3012     }
3013     case TK_OR: {
3014       int d2 = sqlite3VdbeMakeLabel(v);
3015       testcase( jumpIfNull==0 );
3016       sqlite3ExprCachePush(pParse);
3017       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
3018       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3019       sqlite3VdbeResolveLabel(v, d2);
3020       sqlite3ExprCachePop(pParse, 1);
3021       break;
3022     }
3023     case TK_NOT: {
3024       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3025       break;
3026     }
3027     case TK_LT:
3028     case TK_LE:
3029     case TK_GT:
3030     case TK_GE:
3031     case TK_NE:
3032     case TK_EQ: {
3033       testcase( op==TK_LT );
3034       testcase( op==TK_LE );
3035       testcase( op==TK_GT );
3036       testcase( op==TK_GE );
3037       testcase( op==TK_EQ );
3038       testcase( op==TK_NE );
3039       testcase( jumpIfNull==0 );
3040       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
3041                                   pExpr->pRight, &r2, &regFree2);
3042       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3043                   r1, r2, dest, jumpIfNull);
3044       testcase( regFree1==0 );
3045       testcase( regFree2==0 );
3046       break;
3047     }
3048     case TK_ISNULL:
3049     case TK_NOTNULL: {
3050       testcase( op==TK_ISNULL );
3051       testcase( op==TK_NOTNULL );
3052       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3053       sqlite3VdbeAddOp2(v, op, r1, dest);
3054       testcase( regFree1==0 );
3055       break;
3056     }
3057     case TK_BETWEEN: {
3058       /*    x BETWEEN y AND z
3059       **
3060       ** Is equivalent to
3061       **
3062       **    x>=y AND x<=z
3063       **
3064       ** Code it as such, taking care to do the common subexpression
3065       ** elementation of x.
3066       */
3067       Expr exprAnd;
3068       Expr compLeft;
3069       Expr compRight;
3070       Expr exprX;
3071 
3072       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3073       exprX = *pExpr->pLeft;
3074       exprAnd.op = TK_AND;
3075       exprAnd.pLeft = &compLeft;
3076       exprAnd.pRight = &compRight;
3077       compLeft.op = TK_GE;
3078       compLeft.pLeft = &exprX;
3079       compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3080       compRight.op = TK_LE;
3081       compRight.pLeft = &exprX;
3082       compRight.pRight = pExpr->x.pList->a[1].pExpr;
3083       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
3084       testcase( regFree1==0 );
3085       exprX.op = TK_REGISTER;
3086       testcase( jumpIfNull==0 );
3087       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3088       break;
3089     }
3090     default: {
3091       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3092       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3093       testcase( regFree1==0 );
3094       testcase( jumpIfNull==0 );
3095       break;
3096     }
3097   }
3098   sqlite3ReleaseTempReg(pParse, regFree1);
3099   sqlite3ReleaseTempReg(pParse, regFree2);
3100 }
3101 
3102 /*
3103 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
3104 ** if they are identical and return FALSE if they differ in any way.
3105 **
3106 ** Sometimes this routine will return FALSE even if the two expressions
3107 ** really are equivalent.  If we cannot prove that the expressions are
3108 ** identical, we return FALSE just to be safe.  So if this routine
3109 ** returns false, then you do not really know for certain if the two
3110 ** expressions are the same.  But if you get a TRUE return, then you
3111 ** can be sure the expressions are the same.  In the places where
3112 ** this routine is used, it does not hurt to get an extra FALSE - that
3113 ** just might result in some slightly slower code.  But returning
3114 ** an incorrect TRUE could lead to a malfunction.
3115 */
3116 int sqlite3ExprCompare(Expr *pA, Expr *pB){
3117   int i;
3118   if( pA==0||pB==0 ){
3119     return pB==pA;
3120   }
3121   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
3122     return 0;
3123   }
3124   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
3125   if( pA->op!=pB->op ) return 0;
3126   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
3127   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
3128 
3129   if( pA->x.pList && pB->x.pList ){
3130     if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
3131     for(i=0; i<pA->x.pList->nExpr; i++){
3132       Expr *pExprA = pA->x.pList->a[i].pExpr;
3133       Expr *pExprB = pB->x.pList->a[i].pExpr;
3134       if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
3135     }
3136   }else if( pA->x.pList || pB->x.pList ){
3137     return 0;
3138   }
3139 
3140   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
3141   if( pA->op!=TK_COLUMN && pA->token.z ){
3142     if( pB->token.z==0 ) return 0;
3143     if( pB->token.n!=pA->token.n ) return 0;
3144     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
3145       return 0;
3146     }
3147   }
3148   return 1;
3149 }
3150 
3151 
3152 /*
3153 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
3154 ** the new element.  Return a negative number if malloc fails.
3155 */
3156 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
3157   int i;
3158   pInfo->aCol = sqlite3ArrayAllocate(
3159        db,
3160        pInfo->aCol,
3161        sizeof(pInfo->aCol[0]),
3162        3,
3163        &pInfo->nColumn,
3164        &pInfo->nColumnAlloc,
3165        &i
3166   );
3167   return i;
3168 }
3169 
3170 /*
3171 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
3172 ** the new element.  Return a negative number if malloc fails.
3173 */
3174 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
3175   int i;
3176   pInfo->aFunc = sqlite3ArrayAllocate(
3177        db,
3178        pInfo->aFunc,
3179        sizeof(pInfo->aFunc[0]),
3180        3,
3181        &pInfo->nFunc,
3182        &pInfo->nFuncAlloc,
3183        &i
3184   );
3185   return i;
3186 }
3187 
3188 /*
3189 ** This is the xExprCallback for a tree walker.  It is used to
3190 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
3191 ** for additional information.
3192 */
3193 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
3194   int i;
3195   NameContext *pNC = pWalker->u.pNC;
3196   Parse *pParse = pNC->pParse;
3197   SrcList *pSrcList = pNC->pSrcList;
3198   AggInfo *pAggInfo = pNC->pAggInfo;
3199 
3200   switch( pExpr->op ){
3201     case TK_AGG_COLUMN:
3202     case TK_COLUMN: {
3203       testcase( pExpr->op==TK_AGG_COLUMN );
3204       testcase( pExpr->op==TK_COLUMN );
3205       /* Check to see if the column is in one of the tables in the FROM
3206       ** clause of the aggregate query */
3207       if( pSrcList ){
3208         struct SrcList_item *pItem = pSrcList->a;
3209         for(i=0; i<pSrcList->nSrc; i++, pItem++){
3210           struct AggInfo_col *pCol;
3211           if( pExpr->iTable==pItem->iCursor ){
3212             /* If we reach this point, it means that pExpr refers to a table
3213             ** that is in the FROM clause of the aggregate query.
3214             **
3215             ** Make an entry for the column in pAggInfo->aCol[] if there
3216             ** is not an entry there already.
3217             */
3218             int k;
3219             pCol = pAggInfo->aCol;
3220             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
3221               if( pCol->iTable==pExpr->iTable &&
3222                   pCol->iColumn==pExpr->iColumn ){
3223                 break;
3224               }
3225             }
3226             if( (k>=pAggInfo->nColumn)
3227              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
3228             ){
3229               pCol = &pAggInfo->aCol[k];
3230               pCol->pTab = pExpr->pTab;
3231               pCol->iTable = pExpr->iTable;
3232               pCol->iColumn = pExpr->iColumn;
3233               pCol->iMem = ++pParse->nMem;
3234               pCol->iSorterColumn = -1;
3235               pCol->pExpr = pExpr;
3236               if( pAggInfo->pGroupBy ){
3237                 int j, n;
3238                 ExprList *pGB = pAggInfo->pGroupBy;
3239                 struct ExprList_item *pTerm = pGB->a;
3240                 n = pGB->nExpr;
3241                 for(j=0; j<n; j++, pTerm++){
3242                   Expr *pE = pTerm->pExpr;
3243                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
3244                       pE->iColumn==pExpr->iColumn ){
3245                     pCol->iSorterColumn = j;
3246                     break;
3247                   }
3248                 }
3249               }
3250               if( pCol->iSorterColumn<0 ){
3251                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
3252               }
3253             }
3254             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
3255             ** because it was there before or because we just created it).
3256             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
3257             ** pAggInfo->aCol[] entry.
3258             */
3259             pExpr->pAggInfo = pAggInfo;
3260             pExpr->op = TK_AGG_COLUMN;
3261             pExpr->iAgg = k;
3262             break;
3263           } /* endif pExpr->iTable==pItem->iCursor */
3264         } /* end loop over pSrcList */
3265       }
3266       return WRC_Prune;
3267     }
3268     case TK_AGG_FUNCTION: {
3269       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
3270       ** to be ignored */
3271       if( pNC->nDepth==0 ){
3272         /* Check to see if pExpr is a duplicate of another aggregate
3273         ** function that is already in the pAggInfo structure
3274         */
3275         struct AggInfo_func *pItem = pAggInfo->aFunc;
3276         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
3277           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
3278             break;
3279           }
3280         }
3281         if( i>=pAggInfo->nFunc ){
3282           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
3283           */
3284           u8 enc = ENC(pParse->db);
3285           i = addAggInfoFunc(pParse->db, pAggInfo);
3286           if( i>=0 ){
3287             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3288             pItem = &pAggInfo->aFunc[i];
3289             pItem->pExpr = pExpr;
3290             pItem->iMem = ++pParse->nMem;
3291             pItem->pFunc = sqlite3FindFunction(pParse->db,
3292                    (char*)pExpr->token.z, pExpr->token.n,
3293                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
3294             if( pExpr->flags & EP_Distinct ){
3295               pItem->iDistinct = pParse->nTab++;
3296             }else{
3297               pItem->iDistinct = -1;
3298             }
3299           }
3300         }
3301         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
3302         */
3303         pExpr->iAgg = i;
3304         pExpr->pAggInfo = pAggInfo;
3305         return WRC_Prune;
3306       }
3307     }
3308   }
3309   return WRC_Continue;
3310 }
3311 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
3312   NameContext *pNC = pWalker->u.pNC;
3313   if( pNC->nDepth==0 ){
3314     pNC->nDepth++;
3315     sqlite3WalkSelect(pWalker, pSelect);
3316     pNC->nDepth--;
3317     return WRC_Prune;
3318   }else{
3319     return WRC_Continue;
3320   }
3321 }
3322 
3323 /*
3324 ** Analyze the given expression looking for aggregate functions and
3325 ** for variables that need to be added to the pParse->aAgg[] array.
3326 ** Make additional entries to the pParse->aAgg[] array as necessary.
3327 **
3328 ** This routine should only be called after the expression has been
3329 ** analyzed by sqlite3ResolveExprNames().
3330 */
3331 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
3332   Walker w;
3333   w.xExprCallback = analyzeAggregate;
3334   w.xSelectCallback = analyzeAggregatesInSelect;
3335   w.u.pNC = pNC;
3336   sqlite3WalkExpr(&w, pExpr);
3337 }
3338 
3339 /*
3340 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
3341 ** expression list.  Return the number of errors.
3342 **
3343 ** If an error is found, the analysis is cut short.
3344 */
3345 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
3346   struct ExprList_item *pItem;
3347   int i;
3348   if( pList ){
3349     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
3350       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
3351     }
3352   }
3353 }
3354 
3355 /*
3356 ** Allocate a single new register for use to hold some intermediate result.
3357 */
3358 int sqlite3GetTempReg(Parse *pParse){
3359   if( pParse->nTempReg==0 ){
3360     return ++pParse->nMem;
3361   }
3362   return pParse->aTempReg[--pParse->nTempReg];
3363 }
3364 
3365 /*
3366 ** Deallocate a register, making available for reuse for some other
3367 ** purpose.
3368 **
3369 ** If a register is currently being used by the column cache, then
3370 ** the dallocation is deferred until the column cache line that uses
3371 ** the register becomes stale.
3372 */
3373 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
3374   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3375     int i;
3376     struct yColCache *p;
3377     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3378       if( p->iReg==iReg ){
3379         p->tempReg = 1;
3380         return;
3381       }
3382     }
3383     pParse->aTempReg[pParse->nTempReg++] = iReg;
3384   }
3385 }
3386 
3387 /*
3388 ** Allocate or deallocate a block of nReg consecutive registers
3389 */
3390 int sqlite3GetTempRange(Parse *pParse, int nReg){
3391   int i, n;
3392   i = pParse->iRangeReg;
3393   n = pParse->nRangeReg;
3394   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
3395     pParse->iRangeReg += nReg;
3396     pParse->nRangeReg -= nReg;
3397   }else{
3398     i = pParse->nMem+1;
3399     pParse->nMem += nReg;
3400   }
3401   return i;
3402 }
3403 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
3404   if( nReg>pParse->nRangeReg ){
3405     pParse->nRangeReg = nReg;
3406     pParse->iRangeReg = iReg;
3407   }
3408 }
3409