xref: /sqlite-3.40.0/src/expr.c (revision cc516af4)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 */
15 #include "sqliteInt.h"
16 
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20 
21 /*
22 ** Return the affinity character for a single column of a table.
23 */
24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){
25   assert( iCol<pTab->nCol );
26   return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
27 }
28 
29 /*
30 ** Return the 'affinity' of the expression pExpr if any.
31 **
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
36 **
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
39 **
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
44 */
45 char sqlite3ExprAffinity(const Expr *pExpr){
46   int op;
47   while( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
48     assert( pExpr->op==TK_COLLATE
49          || pExpr->op==TK_IF_NULL_ROW
50          || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
51     pExpr = pExpr->pLeft;
52     assert( pExpr!=0 );
53   }
54   op = pExpr->op;
55   if( op==TK_REGISTER ) op = pExpr->op2;
56   if( (op==TK_COLUMN || op==TK_AGG_COLUMN) && pExpr->y.pTab ){
57     return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
58   }
59   if( op==TK_SELECT ){
60     assert( pExpr->flags&EP_xIsSelect );
61     assert( pExpr->x.pSelect!=0 );
62     assert( pExpr->x.pSelect->pEList!=0 );
63     assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
64     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
65   }
66 #ifndef SQLITE_OMIT_CAST
67   if( op==TK_CAST ){
68     assert( !ExprHasProperty(pExpr, EP_IntValue) );
69     return sqlite3AffinityType(pExpr->u.zToken, 0);
70   }
71 #endif
72   if( op==TK_SELECT_COLUMN ){
73     assert( pExpr->pLeft->flags&EP_xIsSelect );
74     assert( pExpr->iColumn < pExpr->iTable );
75     assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
76     return sqlite3ExprAffinity(
77         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
78     );
79   }
80   if( op==TK_VECTOR ){
81     return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
82   }
83   return pExpr->affExpr;
84 }
85 
86 /*
87 ** Set the collating sequence for expression pExpr to be the collating
88 ** sequence named by pToken.   Return a pointer to a new Expr node that
89 ** implements the COLLATE operator.
90 **
91 ** If a memory allocation error occurs, that fact is recorded in pParse->db
92 ** and the pExpr parameter is returned unchanged.
93 */
94 Expr *sqlite3ExprAddCollateToken(
95   Parse *pParse,           /* Parsing context */
96   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
97   const Token *pCollName,  /* Name of collating sequence */
98   int dequote              /* True to dequote pCollName */
99 ){
100   if( pCollName->n>0 ){
101     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
102     if( pNew ){
103       pNew->pLeft = pExpr;
104       pNew->flags |= EP_Collate|EP_Skip;
105       pExpr = pNew;
106     }
107   }
108   return pExpr;
109 }
110 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
111   Token s;
112   assert( zC!=0 );
113   sqlite3TokenInit(&s, (char*)zC);
114   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
115 }
116 
117 /*
118 ** Skip over any TK_COLLATE operators.
119 */
120 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
121   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
122     assert( pExpr->op==TK_COLLATE );
123     pExpr = pExpr->pLeft;
124   }
125   return pExpr;
126 }
127 
128 /*
129 ** Skip over any TK_COLLATE operators and/or any unlikely()
130 ** or likelihood() or likely() functions at the root of an
131 ** expression.
132 */
133 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
134   while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
135     if( ExprHasProperty(pExpr, EP_Unlikely) ){
136       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
137       assert( pExpr->x.pList->nExpr>0 );
138       assert( pExpr->op==TK_FUNCTION );
139       pExpr = pExpr->x.pList->a[0].pExpr;
140     }else{
141       assert( pExpr->op==TK_COLLATE );
142       pExpr = pExpr->pLeft;
143     }
144   }
145   return pExpr;
146 }
147 
148 /*
149 ** Return the collation sequence for the expression pExpr. If
150 ** there is no defined collating sequence, return NULL.
151 **
152 ** See also: sqlite3ExprNNCollSeq()
153 **
154 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
155 ** default collation if pExpr has no defined collation.
156 **
157 ** The collating sequence might be determined by a COLLATE operator
158 ** or by the presence of a column with a defined collating sequence.
159 ** COLLATE operators take first precedence.  Left operands take
160 ** precedence over right operands.
161 */
162 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
163   sqlite3 *db = pParse->db;
164   CollSeq *pColl = 0;
165   const Expr *p = pExpr;
166   while( p ){
167     int op = p->op;
168     if( op==TK_REGISTER ) op = p->op2;
169     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
170      && p->y.pTab!=0
171     ){
172       /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
173       ** a TK_COLUMN but was previously evaluated and cached in a register */
174       int j = p->iColumn;
175       if( j>=0 ){
176         const char *zColl = p->y.pTab->aCol[j].zColl;
177         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
178       }
179       break;
180     }
181     if( op==TK_CAST || op==TK_UPLUS ){
182       p = p->pLeft;
183       continue;
184     }
185     if( op==TK_VECTOR ){
186       p = p->x.pList->a[0].pExpr;
187       continue;
188     }
189     if( op==TK_COLLATE ){
190       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
191       break;
192     }
193     if( p->flags & EP_Collate ){
194       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
195         p = p->pLeft;
196       }else{
197         Expr *pNext  = p->pRight;
198         /* The Expr.x union is never used at the same time as Expr.pRight */
199         assert( p->x.pList==0 || p->pRight==0 );
200         if( p->x.pList!=0
201          && !db->mallocFailed
202          && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
203         ){
204           int i;
205           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
206             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
207               pNext = p->x.pList->a[i].pExpr;
208               break;
209             }
210           }
211         }
212         p = pNext;
213       }
214     }else{
215       break;
216     }
217   }
218   if( sqlite3CheckCollSeq(pParse, pColl) ){
219     pColl = 0;
220   }
221   return pColl;
222 }
223 
224 /*
225 ** Return the collation sequence for the expression pExpr. If
226 ** there is no defined collating sequence, return a pointer to the
227 ** defautl collation sequence.
228 **
229 ** See also: sqlite3ExprCollSeq()
230 **
231 ** The sqlite3ExprCollSeq() routine works the same except that it
232 ** returns NULL if there is no defined collation.
233 */
234 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
235   CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
236   if( p==0 ) p = pParse->db->pDfltColl;
237   assert( p!=0 );
238   return p;
239 }
240 
241 /*
242 ** Return TRUE if the two expressions have equivalent collating sequences.
243 */
244 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
245   CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
246   CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
247   return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
248 }
249 
250 /*
251 ** pExpr is an operand of a comparison operator.  aff2 is the
252 ** type affinity of the other operand.  This routine returns the
253 ** type affinity that should be used for the comparison operator.
254 */
255 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
256   char aff1 = sqlite3ExprAffinity(pExpr);
257   if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
258     /* Both sides of the comparison are columns. If one has numeric
259     ** affinity, use that. Otherwise use no affinity.
260     */
261     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
262       return SQLITE_AFF_NUMERIC;
263     }else{
264       return SQLITE_AFF_BLOB;
265     }
266   }else{
267     /* One side is a column, the other is not. Use the columns affinity. */
268     assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
269     return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
270   }
271 }
272 
273 /*
274 ** pExpr is a comparison operator.  Return the type affinity that should
275 ** be applied to both operands prior to doing the comparison.
276 */
277 static char comparisonAffinity(const Expr *pExpr){
278   char aff;
279   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
280           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
281           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
282   assert( pExpr->pLeft );
283   aff = sqlite3ExprAffinity(pExpr->pLeft);
284   if( pExpr->pRight ){
285     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
286   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
287     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
288   }else if( aff==0 ){
289     aff = SQLITE_AFF_BLOB;
290   }
291   return aff;
292 }
293 
294 /*
295 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
296 ** idx_affinity is the affinity of an indexed column. Return true
297 ** if the index with affinity idx_affinity may be used to implement
298 ** the comparison in pExpr.
299 */
300 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
301   char aff = comparisonAffinity(pExpr);
302   if( aff<SQLITE_AFF_TEXT ){
303     return 1;
304   }
305   if( aff==SQLITE_AFF_TEXT ){
306     return idx_affinity==SQLITE_AFF_TEXT;
307   }
308   return sqlite3IsNumericAffinity(idx_affinity);
309 }
310 
311 /*
312 ** Return the P5 value that should be used for a binary comparison
313 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
314 */
315 static u8 binaryCompareP5(
316   const Expr *pExpr1,   /* Left operand */
317   const Expr *pExpr2,   /* Right operand */
318   int jumpIfNull        /* Extra flags added to P5 */
319 ){
320   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
321   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
322   return aff;
323 }
324 
325 /*
326 ** Return a pointer to the collation sequence that should be used by
327 ** a binary comparison operator comparing pLeft and pRight.
328 **
329 ** If the left hand expression has a collating sequence type, then it is
330 ** used. Otherwise the collation sequence for the right hand expression
331 ** is used, or the default (BINARY) if neither expression has a collating
332 ** type.
333 **
334 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
335 ** it is not considered.
336 */
337 CollSeq *sqlite3BinaryCompareCollSeq(
338   Parse *pParse,
339   const Expr *pLeft,
340   const Expr *pRight
341 ){
342   CollSeq *pColl;
343   assert( pLeft );
344   if( pLeft->flags & EP_Collate ){
345     pColl = sqlite3ExprCollSeq(pParse, pLeft);
346   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
347     pColl = sqlite3ExprCollSeq(pParse, pRight);
348   }else{
349     pColl = sqlite3ExprCollSeq(pParse, pLeft);
350     if( !pColl ){
351       pColl = sqlite3ExprCollSeq(pParse, pRight);
352     }
353   }
354   return pColl;
355 }
356 
357 /* Expresssion p is a comparison operator.  Return a collation sequence
358 ** appropriate for the comparison operator.
359 **
360 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
361 ** However, if the OP_Commuted flag is set, then the order of the operands
362 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
363 ** correct collating sequence is found.
364 */
365 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
366   if( ExprHasProperty(p, EP_Commuted) ){
367     return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
368   }else{
369     return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
370   }
371 }
372 
373 /*
374 ** Generate code for a comparison operator.
375 */
376 static int codeCompare(
377   Parse *pParse,    /* The parsing (and code generating) context */
378   Expr *pLeft,      /* The left operand */
379   Expr *pRight,     /* The right operand */
380   int opcode,       /* The comparison opcode */
381   int in1, int in2, /* Register holding operands */
382   int dest,         /* Jump here if true.  */
383   int jumpIfNull,   /* If true, jump if either operand is NULL */
384   int isCommuted    /* The comparison has been commuted */
385 ){
386   int p5;
387   int addr;
388   CollSeq *p4;
389 
390   if( pParse->nErr ) return 0;
391   if( isCommuted ){
392     p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
393   }else{
394     p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
395   }
396   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
397   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
398                            (void*)p4, P4_COLLSEQ);
399   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
400   return addr;
401 }
402 
403 /*
404 ** Return true if expression pExpr is a vector, or false otherwise.
405 **
406 ** A vector is defined as any expression that results in two or more
407 ** columns of result.  Every TK_VECTOR node is an vector because the
408 ** parser will not generate a TK_VECTOR with fewer than two entries.
409 ** But a TK_SELECT might be either a vector or a scalar. It is only
410 ** considered a vector if it has two or more result columns.
411 */
412 int sqlite3ExprIsVector(Expr *pExpr){
413   return sqlite3ExprVectorSize(pExpr)>1;
414 }
415 
416 /*
417 ** If the expression passed as the only argument is of type TK_VECTOR
418 ** return the number of expressions in the vector. Or, if the expression
419 ** is a sub-select, return the number of columns in the sub-select. For
420 ** any other type of expression, return 1.
421 */
422 int sqlite3ExprVectorSize(Expr *pExpr){
423   u8 op = pExpr->op;
424   if( op==TK_REGISTER ) op = pExpr->op2;
425   if( op==TK_VECTOR ){
426     return pExpr->x.pList->nExpr;
427   }else if( op==TK_SELECT ){
428     return pExpr->x.pSelect->pEList->nExpr;
429   }else{
430     return 1;
431   }
432 }
433 
434 /*
435 ** Return a pointer to a subexpression of pVector that is the i-th
436 ** column of the vector (numbered starting with 0).  The caller must
437 ** ensure that i is within range.
438 **
439 ** If pVector is really a scalar (and "scalar" here includes subqueries
440 ** that return a single column!) then return pVector unmodified.
441 **
442 ** pVector retains ownership of the returned subexpression.
443 **
444 ** If the vector is a (SELECT ...) then the expression returned is
445 ** just the expression for the i-th term of the result set, and may
446 ** not be ready for evaluation because the table cursor has not yet
447 ** been positioned.
448 */
449 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
450   assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
451   if( sqlite3ExprIsVector(pVector) ){
452     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
453     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
454       return pVector->x.pSelect->pEList->a[i].pExpr;
455     }else{
456       return pVector->x.pList->a[i].pExpr;
457     }
458   }
459   return pVector;
460 }
461 
462 /*
463 ** Compute and return a new Expr object which when passed to
464 ** sqlite3ExprCode() will generate all necessary code to compute
465 ** the iField-th column of the vector expression pVector.
466 **
467 ** It is ok for pVector to be a scalar (as long as iField==0).
468 ** In that case, this routine works like sqlite3ExprDup().
469 **
470 ** The caller owns the returned Expr object and is responsible for
471 ** ensuring that the returned value eventually gets freed.
472 **
473 ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
474 ** then the returned object will reference pVector and so pVector must remain
475 ** valid for the life of the returned object.  If pVector is a TK_VECTOR
476 ** or a scalar expression, then it can be deleted as soon as this routine
477 ** returns.
478 **
479 ** A trick to cause a TK_SELECT pVector to be deleted together with
480 ** the returned Expr object is to attach the pVector to the pRight field
481 ** of the returned TK_SELECT_COLUMN Expr object.
482 */
483 Expr *sqlite3ExprForVectorField(
484   Parse *pParse,       /* Parsing context */
485   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
486   int iField,          /* Which column of the vector to return */
487   int nField           /* Total number of columns in the vector */
488 ){
489   Expr *pRet;
490   if( pVector->op==TK_SELECT ){
491     assert( pVector->flags & EP_xIsSelect );
492     /* The TK_SELECT_COLUMN Expr node:
493     **
494     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
495     ** pRight:          not used.  But recursively deleted.
496     ** iColumn:         Index of a column in pVector
497     ** iTable:          0 or the number of columns on the LHS of an assignment
498     ** pLeft->iTable:   First in an array of register holding result, or 0
499     **                  if the result is not yet computed.
500     **
501     ** sqlite3ExprDelete() specifically skips the recursive delete of
502     ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
503     ** can be attached to pRight to cause this node to take ownership of
504     ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
505     ** with the same pLeft pointer to the pVector, but only one of them
506     ** will own the pVector.
507     */
508     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
509     if( pRet ){
510       pRet->iTable = nField;
511       pRet->iColumn = iField;
512       pRet->pLeft = pVector;
513     }
514   }else{
515     if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
516     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
517     sqlite3RenameTokenRemap(pParse, pRet, pVector);
518   }
519   return pRet;
520 }
521 
522 /*
523 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
524 ** it. Return the register in which the result is stored (or, if the
525 ** sub-select returns more than one column, the first in an array
526 ** of registers in which the result is stored).
527 **
528 ** If pExpr is not a TK_SELECT expression, return 0.
529 */
530 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
531   int reg = 0;
532 #ifndef SQLITE_OMIT_SUBQUERY
533   if( pExpr->op==TK_SELECT ){
534     reg = sqlite3CodeSubselect(pParse, pExpr);
535   }
536 #endif
537   return reg;
538 }
539 
540 /*
541 ** Argument pVector points to a vector expression - either a TK_VECTOR
542 ** or TK_SELECT that returns more than one column. This function returns
543 ** the register number of a register that contains the value of
544 ** element iField of the vector.
545 **
546 ** If pVector is a TK_SELECT expression, then code for it must have
547 ** already been generated using the exprCodeSubselect() routine. In this
548 ** case parameter regSelect should be the first in an array of registers
549 ** containing the results of the sub-select.
550 **
551 ** If pVector is of type TK_VECTOR, then code for the requested field
552 ** is generated. In this case (*pRegFree) may be set to the number of
553 ** a temporary register to be freed by the caller before returning.
554 **
555 ** Before returning, output parameter (*ppExpr) is set to point to the
556 ** Expr object corresponding to element iElem of the vector.
557 */
558 static int exprVectorRegister(
559   Parse *pParse,                  /* Parse context */
560   Expr *pVector,                  /* Vector to extract element from */
561   int iField,                     /* Field to extract from pVector */
562   int regSelect,                  /* First in array of registers */
563   Expr **ppExpr,                  /* OUT: Expression element */
564   int *pRegFree                   /* OUT: Temp register to free */
565 ){
566   u8 op = pVector->op;
567   assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
568   if( op==TK_REGISTER ){
569     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
570     return pVector->iTable+iField;
571   }
572   if( op==TK_SELECT ){
573     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
574      return regSelect+iField;
575   }
576   if( op==TK_VECTOR ){
577     *ppExpr = pVector->x.pList->a[iField].pExpr;
578     return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
579   }
580   return 0;
581 }
582 
583 /*
584 ** Expression pExpr is a comparison between two vector values. Compute
585 ** the result of the comparison (1, 0, or NULL) and write that
586 ** result into register dest.
587 **
588 ** The caller must satisfy the following preconditions:
589 **
590 **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
591 **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
592 **    otherwise:                op==pExpr->op and p5==0
593 */
594 static void codeVectorCompare(
595   Parse *pParse,        /* Code generator context */
596   Expr *pExpr,          /* The comparison operation */
597   int dest,             /* Write results into this register */
598   u8 op,                /* Comparison operator */
599   u8 p5                 /* SQLITE_NULLEQ or zero */
600 ){
601   Vdbe *v = pParse->pVdbe;
602   Expr *pLeft = pExpr->pLeft;
603   Expr *pRight = pExpr->pRight;
604   int nLeft = sqlite3ExprVectorSize(pLeft);
605   int i;
606   int regLeft = 0;
607   int regRight = 0;
608   u8 opx = op;
609   int addrCmp = 0;
610   int addrDone = sqlite3VdbeMakeLabel(pParse);
611   int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
612 
613   assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
614   if( pParse->nErr ) return;
615   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
616     sqlite3ErrorMsg(pParse, "row value misused");
617     return;
618   }
619   assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
620        || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
621        || pExpr->op==TK_LT || pExpr->op==TK_GT
622        || pExpr->op==TK_LE || pExpr->op==TK_GE
623   );
624   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
625             || (pExpr->op==TK_ISNOT && op==TK_NE) );
626   assert( p5==0 || pExpr->op!=op );
627   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
628 
629   if( op==TK_LE ) opx = TK_LT;
630   if( op==TK_GE ) opx = TK_GT;
631   if( op==TK_NE ) opx = TK_EQ;
632 
633   regLeft = exprCodeSubselect(pParse, pLeft);
634   regRight = exprCodeSubselect(pParse, pRight);
635 
636   sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
637   for(i=0; 1 /*Loop exits by "break"*/; i++){
638     int regFree1 = 0, regFree2 = 0;
639     Expr *pL = 0, *pR = 0;
640     int r1, r2;
641     assert( i>=0 && i<nLeft );
642     if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
643     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
644     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
645     addrCmp = sqlite3VdbeCurrentAddr(v);
646     codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
647     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
648     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
649     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
650     testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
651     testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
652     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
653     sqlite3ReleaseTempReg(pParse, regFree1);
654     sqlite3ReleaseTempReg(pParse, regFree2);
655     if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
656       addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
657       testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
658       testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
659     }
660     if( p5==SQLITE_NULLEQ ){
661       sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
662     }else{
663       sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
664     }
665     if( i==nLeft-1 ){
666       break;
667     }
668     if( opx==TK_EQ ){
669       sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
670     }else{
671       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
672       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
673       if( i==nLeft-2 ) opx = op;
674     }
675   }
676   sqlite3VdbeJumpHere(v, addrCmp);
677   sqlite3VdbeResolveLabel(v, addrDone);
678   if( op==TK_NE ){
679     sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
680   }
681 }
682 
683 #if SQLITE_MAX_EXPR_DEPTH>0
684 /*
685 ** Check that argument nHeight is less than or equal to the maximum
686 ** expression depth allowed. If it is not, leave an error message in
687 ** pParse.
688 */
689 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
690   int rc = SQLITE_OK;
691   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
692   if( nHeight>mxHeight ){
693     sqlite3ErrorMsg(pParse,
694        "Expression tree is too large (maximum depth %d)", mxHeight
695     );
696     rc = SQLITE_ERROR;
697   }
698   return rc;
699 }
700 
701 /* The following three functions, heightOfExpr(), heightOfExprList()
702 ** and heightOfSelect(), are used to determine the maximum height
703 ** of any expression tree referenced by the structure passed as the
704 ** first argument.
705 **
706 ** If this maximum height is greater than the current value pointed
707 ** to by pnHeight, the second parameter, then set *pnHeight to that
708 ** value.
709 */
710 static void heightOfExpr(Expr *p, int *pnHeight){
711   if( p ){
712     if( p->nHeight>*pnHeight ){
713       *pnHeight = p->nHeight;
714     }
715   }
716 }
717 static void heightOfExprList(ExprList *p, int *pnHeight){
718   if( p ){
719     int i;
720     for(i=0; i<p->nExpr; i++){
721       heightOfExpr(p->a[i].pExpr, pnHeight);
722     }
723   }
724 }
725 static void heightOfSelect(Select *pSelect, int *pnHeight){
726   Select *p;
727   for(p=pSelect; p; p=p->pPrior){
728     heightOfExpr(p->pWhere, pnHeight);
729     heightOfExpr(p->pHaving, pnHeight);
730     heightOfExpr(p->pLimit, pnHeight);
731     heightOfExprList(p->pEList, pnHeight);
732     heightOfExprList(p->pGroupBy, pnHeight);
733     heightOfExprList(p->pOrderBy, pnHeight);
734   }
735 }
736 
737 /*
738 ** Set the Expr.nHeight variable in the structure passed as an
739 ** argument. An expression with no children, Expr.pList or
740 ** Expr.pSelect member has a height of 1. Any other expression
741 ** has a height equal to the maximum height of any other
742 ** referenced Expr plus one.
743 **
744 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
745 ** if appropriate.
746 */
747 static void exprSetHeight(Expr *p){
748   int nHeight = 0;
749   heightOfExpr(p->pLeft, &nHeight);
750   heightOfExpr(p->pRight, &nHeight);
751   if( ExprHasProperty(p, EP_xIsSelect) ){
752     heightOfSelect(p->x.pSelect, &nHeight);
753   }else if( p->x.pList ){
754     heightOfExprList(p->x.pList, &nHeight);
755     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
756   }
757   p->nHeight = nHeight + 1;
758 }
759 
760 /*
761 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
762 ** the height is greater than the maximum allowed expression depth,
763 ** leave an error in pParse.
764 **
765 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
766 ** Expr.flags.
767 */
768 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
769   if( pParse->nErr ) return;
770   exprSetHeight(p);
771   sqlite3ExprCheckHeight(pParse, p->nHeight);
772 }
773 
774 /*
775 ** Return the maximum height of any expression tree referenced
776 ** by the select statement passed as an argument.
777 */
778 int sqlite3SelectExprHeight(Select *p){
779   int nHeight = 0;
780   heightOfSelect(p, &nHeight);
781   return nHeight;
782 }
783 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
784 /*
785 ** Propagate all EP_Propagate flags from the Expr.x.pList into
786 ** Expr.flags.
787 */
788 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
789   if( pParse->nErr ) return;
790   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
791     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
792   }
793 }
794 #define exprSetHeight(y)
795 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
796 
797 /*
798 ** This routine is the core allocator for Expr nodes.
799 **
800 ** Construct a new expression node and return a pointer to it.  Memory
801 ** for this node and for the pToken argument is a single allocation
802 ** obtained from sqlite3DbMalloc().  The calling function
803 ** is responsible for making sure the node eventually gets freed.
804 **
805 ** If dequote is true, then the token (if it exists) is dequoted.
806 ** If dequote is false, no dequoting is performed.  The deQuote
807 ** parameter is ignored if pToken is NULL or if the token does not
808 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
809 ** then the EP_DblQuoted flag is set on the expression node.
810 **
811 ** Special case:  If op==TK_INTEGER and pToken points to a string that
812 ** can be translated into a 32-bit integer, then the token is not
813 ** stored in u.zToken.  Instead, the integer values is written
814 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
815 ** is allocated to hold the integer text and the dequote flag is ignored.
816 */
817 Expr *sqlite3ExprAlloc(
818   sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
819   int op,                 /* Expression opcode */
820   const Token *pToken,    /* Token argument.  Might be NULL */
821   int dequote             /* True to dequote */
822 ){
823   Expr *pNew;
824   int nExtra = 0;
825   int iValue = 0;
826 
827   assert( db!=0 );
828   if( pToken ){
829     if( op!=TK_INTEGER || pToken->z==0
830           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
831       nExtra = pToken->n+1;
832       assert( iValue>=0 );
833     }
834   }
835   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
836   if( pNew ){
837     memset(pNew, 0, sizeof(Expr));
838     pNew->op = (u8)op;
839     pNew->iAgg = -1;
840     if( pToken ){
841       if( nExtra==0 ){
842         pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
843         pNew->u.iValue = iValue;
844       }else{
845         pNew->u.zToken = (char*)&pNew[1];
846         assert( pToken->z!=0 || pToken->n==0 );
847         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
848         pNew->u.zToken[pToken->n] = 0;
849         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
850           sqlite3DequoteExpr(pNew);
851         }
852       }
853     }
854 #if SQLITE_MAX_EXPR_DEPTH>0
855     pNew->nHeight = 1;
856 #endif
857   }
858   return pNew;
859 }
860 
861 /*
862 ** Allocate a new expression node from a zero-terminated token that has
863 ** already been dequoted.
864 */
865 Expr *sqlite3Expr(
866   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
867   int op,                 /* Expression opcode */
868   const char *zToken      /* Token argument.  Might be NULL */
869 ){
870   Token x;
871   x.z = zToken;
872   x.n = sqlite3Strlen30(zToken);
873   return sqlite3ExprAlloc(db, op, &x, 0);
874 }
875 
876 /*
877 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
878 **
879 ** If pRoot==NULL that means that a memory allocation error has occurred.
880 ** In that case, delete the subtrees pLeft and pRight.
881 */
882 void sqlite3ExprAttachSubtrees(
883   sqlite3 *db,
884   Expr *pRoot,
885   Expr *pLeft,
886   Expr *pRight
887 ){
888   if( pRoot==0 ){
889     assert( db->mallocFailed );
890     sqlite3ExprDelete(db, pLeft);
891     sqlite3ExprDelete(db, pRight);
892   }else{
893     if( pRight ){
894       pRoot->pRight = pRight;
895       pRoot->flags |= EP_Propagate & pRight->flags;
896     }
897     if( pLeft ){
898       pRoot->pLeft = pLeft;
899       pRoot->flags |= EP_Propagate & pLeft->flags;
900     }
901     exprSetHeight(pRoot);
902   }
903 }
904 
905 /*
906 ** Allocate an Expr node which joins as many as two subtrees.
907 **
908 ** One or both of the subtrees can be NULL.  Return a pointer to the new
909 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
910 ** free the subtrees and return NULL.
911 */
912 Expr *sqlite3PExpr(
913   Parse *pParse,          /* Parsing context */
914   int op,                 /* Expression opcode */
915   Expr *pLeft,            /* Left operand */
916   Expr *pRight            /* Right operand */
917 ){
918   Expr *p;
919   p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
920   if( p ){
921     memset(p, 0, sizeof(Expr));
922     p->op = op & 0xff;
923     p->iAgg = -1;
924     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
925     sqlite3ExprCheckHeight(pParse, p->nHeight);
926   }else{
927     sqlite3ExprDelete(pParse->db, pLeft);
928     sqlite3ExprDelete(pParse->db, pRight);
929   }
930   return p;
931 }
932 
933 /*
934 ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
935 ** do a memory allocation failure) then delete the pSelect object.
936 */
937 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
938   if( pExpr ){
939     pExpr->x.pSelect = pSelect;
940     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
941     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
942   }else{
943     assert( pParse->db->mallocFailed );
944     sqlite3SelectDelete(pParse->db, pSelect);
945   }
946 }
947 
948 /*
949 ** Expression list pEList is a list of vector values. This function
950 ** converts the contents of pEList to a VALUES(...) Select statement
951 ** returning 1 row for each element of the list. If there are any
952 ** non-vector expressions in the list, the corresponding row returned
953 ** by the values statement contains a single column, the value of
954 ** the non-vector expression itself.
955 **
956 ** For example, the expression list:
957 **
958 **   ( (1, 2), 3, (3, 4, 5) )
959 **
960 ** is translated to:
961 **
962 **   VALUES(1, 2), (3), (3, 4, 5)
963 **
964 ** This is used as part of processing IN(...) expressions with a list
965 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
966 */
967 Select *sqlite3ExprListToValues(Parse *pParse, ExprList *pEList){
968   int ii;
969   Select *pRet = 0;
970   for(ii=0; ii<pEList->nExpr; ii++){
971     Select *pSel;
972     ExprList *pList;
973     Expr *pExpr = pEList->a[ii].pExpr;
974     if( pExpr->op==TK_VECTOR ){
975       pList = pExpr->x.pList;
976       pExpr->x.pList = 0;
977     }else{
978       pList = sqlite3ExprListAppend(pParse, 0, pExpr);
979       pEList->a[ii].pExpr = 0;
980     }
981     pSel = sqlite3SelectNew(pParse, pList, 0, 0, 0, 0, 0, SF_Values, 0);
982     if( pSel ){
983       if( pRet ){
984         pSel->op = TK_ALL;
985         pSel->pPrior = pRet;
986       }
987       pRet = pSel;
988     }
989   }
990 
991   if( pRet && pRet->pPrior ){
992     pRet->selFlags |= SF_MultiValue;
993   }
994   sqlite3ExprListDelete(pParse->db, pEList);
995   return pRet;
996 }
997 
998 /*
999 ** Join two expressions using an AND operator.  If either expression is
1000 ** NULL, then just return the other expression.
1001 **
1002 ** If one side or the other of the AND is known to be false, then instead
1003 ** of returning an AND expression, just return a constant expression with
1004 ** a value of false.
1005 */
1006 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1007   sqlite3 *db = pParse->db;
1008   if( pLeft==0  ){
1009     return pRight;
1010   }else if( pRight==0 ){
1011     return pLeft;
1012   }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
1013          && !IN_RENAME_OBJECT
1014   ){
1015     sqlite3ExprDeferredDelete(pParse, pLeft);
1016     sqlite3ExprDeferredDelete(pParse, pRight);
1017     return sqlite3Expr(db, TK_INTEGER, "0");
1018   }else{
1019     return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1020   }
1021 }
1022 
1023 /*
1024 ** Construct a new expression node for a function with multiple
1025 ** arguments.
1026 */
1027 Expr *sqlite3ExprFunction(
1028   Parse *pParse,        /* Parsing context */
1029   ExprList *pList,      /* Argument list */
1030   Token *pToken,        /* Name of the function */
1031   int eDistinct         /* SF_Distinct or SF_ALL or 0 */
1032 ){
1033   Expr *pNew;
1034   sqlite3 *db = pParse->db;
1035   assert( pToken );
1036   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1037   if( pNew==0 ){
1038     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1039     return 0;
1040   }
1041   if( pList
1042    && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1043    && !pParse->nested
1044   ){
1045     sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1046   }
1047   pNew->x.pList = pList;
1048   ExprSetProperty(pNew, EP_HasFunc);
1049   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1050   sqlite3ExprSetHeightAndFlags(pParse, pNew);
1051   if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1052   return pNew;
1053 }
1054 
1055 /*
1056 ** Check to see if a function is usable according to current access
1057 ** rules:
1058 **
1059 **    SQLITE_FUNC_DIRECT    -     Only usable from top-level SQL
1060 **
1061 **    SQLITE_FUNC_UNSAFE    -     Usable if TRUSTED_SCHEMA or from
1062 **                                top-level SQL
1063 **
1064 ** If the function is not usable, create an error.
1065 */
1066 void sqlite3ExprFunctionUsable(
1067   Parse *pParse,         /* Parsing and code generating context */
1068   Expr *pExpr,           /* The function invocation */
1069   FuncDef *pDef          /* The function being invoked */
1070 ){
1071   assert( !IN_RENAME_OBJECT );
1072   assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1073   if( ExprHasProperty(pExpr, EP_FromDDL) ){
1074     if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1075      || (pParse->db->flags & SQLITE_TrustedSchema)==0
1076     ){
1077       /* Functions prohibited in triggers and views if:
1078       **     (1) tagged with SQLITE_DIRECTONLY
1079       **     (2) not tagged with SQLITE_INNOCUOUS (which means it
1080       **         is tagged with SQLITE_FUNC_UNSAFE) and
1081       **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1082       **         that the schema is possibly tainted).
1083       */
1084       sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
1085     }
1086   }
1087 }
1088 
1089 /*
1090 ** Assign a variable number to an expression that encodes a wildcard
1091 ** in the original SQL statement.
1092 **
1093 ** Wildcards consisting of a single "?" are assigned the next sequential
1094 ** variable number.
1095 **
1096 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
1097 ** sure "nnn" is not too big to avoid a denial of service attack when
1098 ** the SQL statement comes from an external source.
1099 **
1100 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1101 ** as the previous instance of the same wildcard.  Or if this is the first
1102 ** instance of the wildcard, the next sequential variable number is
1103 ** assigned.
1104 */
1105 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1106   sqlite3 *db = pParse->db;
1107   const char *z;
1108   ynVar x;
1109 
1110   if( pExpr==0 ) return;
1111   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1112   z = pExpr->u.zToken;
1113   assert( z!=0 );
1114   assert( z[0]!=0 );
1115   assert( n==(u32)sqlite3Strlen30(z) );
1116   if( z[1]==0 ){
1117     /* Wildcard of the form "?".  Assign the next variable number */
1118     assert( z[0]=='?' );
1119     x = (ynVar)(++pParse->nVar);
1120   }else{
1121     int doAdd = 0;
1122     if( z[0]=='?' ){
1123       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
1124       ** use it as the variable number */
1125       i64 i;
1126       int bOk;
1127       if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1128         i = z[1]-'0';  /* The common case of ?N for a single digit N */
1129         bOk = 1;
1130       }else{
1131         bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1132       }
1133       testcase( i==0 );
1134       testcase( i==1 );
1135       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1136       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1137       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1138         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1139             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1140         return;
1141       }
1142       x = (ynVar)i;
1143       if( x>pParse->nVar ){
1144         pParse->nVar = (int)x;
1145         doAdd = 1;
1146       }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1147         doAdd = 1;
1148       }
1149     }else{
1150       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
1151       ** number as the prior appearance of the same name, or if the name
1152       ** has never appeared before, reuse the same variable number
1153       */
1154       x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1155       if( x==0 ){
1156         x = (ynVar)(++pParse->nVar);
1157         doAdd = 1;
1158       }
1159     }
1160     if( doAdd ){
1161       pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1162     }
1163   }
1164   pExpr->iColumn = x;
1165   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1166     sqlite3ErrorMsg(pParse, "too many SQL variables");
1167   }
1168 }
1169 
1170 /*
1171 ** Recursively delete an expression tree.
1172 */
1173 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1174   assert( p!=0 );
1175   /* Sanity check: Assert that the IntValue is non-negative if it exists */
1176   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1177 
1178   assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
1179   assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
1180           || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
1181 #ifdef SQLITE_DEBUG
1182   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1183     assert( p->pLeft==0 );
1184     assert( p->pRight==0 );
1185     assert( p->x.pSelect==0 );
1186   }
1187 #endif
1188   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1189     /* The Expr.x union is never used at the same time as Expr.pRight */
1190     assert( p->x.pList==0 || p->pRight==0 );
1191     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1192     if( p->pRight ){
1193       assert( !ExprHasProperty(p, EP_WinFunc) );
1194       sqlite3ExprDeleteNN(db, p->pRight);
1195     }else if( ExprHasProperty(p, EP_xIsSelect) ){
1196       assert( !ExprHasProperty(p, EP_WinFunc) );
1197       sqlite3SelectDelete(db, p->x.pSelect);
1198     }else{
1199       sqlite3ExprListDelete(db, p->x.pList);
1200 #ifndef SQLITE_OMIT_WINDOWFUNC
1201       if( ExprHasProperty(p, EP_WinFunc) ){
1202         sqlite3WindowDelete(db, p->y.pWin);
1203       }
1204 #endif
1205     }
1206   }
1207   if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
1208   if( !ExprHasProperty(p, EP_Static) ){
1209     sqlite3DbFreeNN(db, p);
1210   }
1211 }
1212 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1213   if( p ) sqlite3ExprDeleteNN(db, p);
1214 }
1215 
1216 
1217 /*
1218 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1219 ** This is similar to sqlite3ExprDelete() except that the delete is
1220 ** deferred untilthe pParse is deleted.
1221 **
1222 ** The pExpr might be deleted immediately on an OOM error.
1223 **
1224 ** The deferred delete is (currently) implemented by adding the
1225 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1226 */
1227 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1228   pParse->pConstExpr =
1229       sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
1230 }
1231 
1232 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1233 ** expression.
1234 */
1235 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1236   if( p ){
1237     if( IN_RENAME_OBJECT ){
1238       sqlite3RenameExprUnmap(pParse, p);
1239     }
1240     sqlite3ExprDeleteNN(pParse->db, p);
1241   }
1242 }
1243 
1244 /*
1245 ** Return the number of bytes allocated for the expression structure
1246 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1247 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1248 */
1249 static int exprStructSize(Expr *p){
1250   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1251   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1252   return EXPR_FULLSIZE;
1253 }
1254 
1255 /*
1256 ** The dupedExpr*Size() routines each return the number of bytes required
1257 ** to store a copy of an expression or expression tree.  They differ in
1258 ** how much of the tree is measured.
1259 **
1260 **     dupedExprStructSize()     Size of only the Expr structure
1261 **     dupedExprNodeSize()       Size of Expr + space for token
1262 **     dupedExprSize()           Expr + token + subtree components
1263 **
1264 ***************************************************************************
1265 **
1266 ** The dupedExprStructSize() function returns two values OR-ed together:
1267 ** (1) the space required for a copy of the Expr structure only and
1268 ** (2) the EP_xxx flags that indicate what the structure size should be.
1269 ** The return values is always one of:
1270 **
1271 **      EXPR_FULLSIZE
1272 **      EXPR_REDUCEDSIZE   | EP_Reduced
1273 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
1274 **
1275 ** The size of the structure can be found by masking the return value
1276 ** of this routine with 0xfff.  The flags can be found by masking the
1277 ** return value with EP_Reduced|EP_TokenOnly.
1278 **
1279 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1280 ** (unreduced) Expr objects as they or originally constructed by the parser.
1281 ** During expression analysis, extra information is computed and moved into
1282 ** later parts of the Expr object and that extra information might get chopped
1283 ** off if the expression is reduced.  Note also that it does not work to
1284 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
1285 ** to reduce a pristine expression tree from the parser.  The implementation
1286 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1287 ** to enforce this constraint.
1288 */
1289 static int dupedExprStructSize(Expr *p, int flags){
1290   int nSize;
1291   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1292   assert( EXPR_FULLSIZE<=0xfff );
1293   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1294   if( 0==flags || p->op==TK_SELECT_COLUMN
1295 #ifndef SQLITE_OMIT_WINDOWFUNC
1296    || ExprHasProperty(p, EP_WinFunc)
1297 #endif
1298   ){
1299     nSize = EXPR_FULLSIZE;
1300   }else{
1301     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1302     assert( !ExprHasProperty(p, EP_FromJoin) );
1303     assert( !ExprHasProperty(p, EP_MemToken) );
1304     assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1305     if( p->pLeft || p->x.pList ){
1306       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1307     }else{
1308       assert( p->pRight==0 );
1309       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1310     }
1311   }
1312   return nSize;
1313 }
1314 
1315 /*
1316 ** This function returns the space in bytes required to store the copy
1317 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1318 ** string is defined.)
1319 */
1320 static int dupedExprNodeSize(Expr *p, int flags){
1321   int nByte = dupedExprStructSize(p, flags) & 0xfff;
1322   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1323     nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1324   }
1325   return ROUND8(nByte);
1326 }
1327 
1328 /*
1329 ** Return the number of bytes required to create a duplicate of the
1330 ** expression passed as the first argument. The second argument is a
1331 ** mask containing EXPRDUP_XXX flags.
1332 **
1333 ** The value returned includes space to create a copy of the Expr struct
1334 ** itself and the buffer referred to by Expr.u.zToken, if any.
1335 **
1336 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1337 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1338 ** and Expr.pRight variables (but not for any structures pointed to or
1339 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1340 */
1341 static int dupedExprSize(Expr *p, int flags){
1342   int nByte = 0;
1343   if( p ){
1344     nByte = dupedExprNodeSize(p, flags);
1345     if( flags&EXPRDUP_REDUCE ){
1346       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1347     }
1348   }
1349   return nByte;
1350 }
1351 
1352 /*
1353 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1354 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1355 ** to store the copy of expression p, the copies of p->u.zToken
1356 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1357 ** if any. Before returning, *pzBuffer is set to the first byte past the
1358 ** portion of the buffer copied into by this function.
1359 */
1360 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1361   Expr *pNew;           /* Value to return */
1362   u8 *zAlloc;           /* Memory space from which to build Expr object */
1363   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
1364 
1365   assert( db!=0 );
1366   assert( p );
1367   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1368   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1369 
1370   /* Figure out where to write the new Expr structure. */
1371   if( pzBuffer ){
1372     zAlloc = *pzBuffer;
1373     staticFlag = EP_Static;
1374     assert( zAlloc!=0 );
1375   }else{
1376     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1377     staticFlag = 0;
1378   }
1379   pNew = (Expr *)zAlloc;
1380 
1381   if( pNew ){
1382     /* Set nNewSize to the size allocated for the structure pointed to
1383     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1384     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1385     ** by the copy of the p->u.zToken string (if any).
1386     */
1387     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1388     const int nNewSize = nStructSize & 0xfff;
1389     int nToken;
1390     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1391       nToken = sqlite3Strlen30(p->u.zToken) + 1;
1392     }else{
1393       nToken = 0;
1394     }
1395     if( dupFlags ){
1396       assert( ExprHasProperty(p, EP_Reduced)==0 );
1397       memcpy(zAlloc, p, nNewSize);
1398     }else{
1399       u32 nSize = (u32)exprStructSize(p);
1400       memcpy(zAlloc, p, nSize);
1401       if( nSize<EXPR_FULLSIZE ){
1402         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1403       }
1404     }
1405 
1406     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1407     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1408     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1409     pNew->flags |= staticFlag;
1410     ExprClearVVAProperties(pNew);
1411     if( dupFlags ){
1412       ExprSetVVAProperty(pNew, EP_Immutable);
1413     }
1414 
1415     /* Copy the p->u.zToken string, if any. */
1416     if( nToken ){
1417       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1418       memcpy(zToken, p->u.zToken, nToken);
1419     }
1420 
1421     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1422       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1423       if( ExprHasProperty(p, EP_xIsSelect) ){
1424         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1425       }else{
1426         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1427       }
1428     }
1429 
1430     /* Fill in pNew->pLeft and pNew->pRight. */
1431     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
1432       zAlloc += dupedExprNodeSize(p, dupFlags);
1433       if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1434         pNew->pLeft = p->pLeft ?
1435                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1436         pNew->pRight = p->pRight ?
1437                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1438       }
1439 #ifndef SQLITE_OMIT_WINDOWFUNC
1440       if( ExprHasProperty(p, EP_WinFunc) ){
1441         pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1442         assert( ExprHasProperty(pNew, EP_WinFunc) );
1443       }
1444 #endif /* SQLITE_OMIT_WINDOWFUNC */
1445       if( pzBuffer ){
1446         *pzBuffer = zAlloc;
1447       }
1448     }else{
1449       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1450         if( pNew->op==TK_SELECT_COLUMN ){
1451           pNew->pLeft = p->pLeft;
1452           assert( p->pRight==0  || p->pRight==p->pLeft
1453                                 || ExprHasProperty(p->pLeft, EP_Subquery) );
1454         }else{
1455           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1456         }
1457         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1458       }
1459     }
1460   }
1461   return pNew;
1462 }
1463 
1464 /*
1465 ** Create and return a deep copy of the object passed as the second
1466 ** argument. If an OOM condition is encountered, NULL is returned
1467 ** and the db->mallocFailed flag set.
1468 */
1469 #ifndef SQLITE_OMIT_CTE
1470 With *sqlite3WithDup(sqlite3 *db, With *p){
1471   With *pRet = 0;
1472   if( p ){
1473     sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1474     pRet = sqlite3DbMallocZero(db, nByte);
1475     if( pRet ){
1476       int i;
1477       pRet->nCte = p->nCte;
1478       for(i=0; i<p->nCte; i++){
1479         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1480         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1481         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1482       }
1483     }
1484   }
1485   return pRet;
1486 }
1487 #else
1488 # define sqlite3WithDup(x,y) 0
1489 #endif
1490 
1491 #ifndef SQLITE_OMIT_WINDOWFUNC
1492 /*
1493 ** The gatherSelectWindows() procedure and its helper routine
1494 ** gatherSelectWindowsCallback() are used to scan all the expressions
1495 ** an a newly duplicated SELECT statement and gather all of the Window
1496 ** objects found there, assembling them onto the linked list at Select->pWin.
1497 */
1498 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1499   if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1500     Select *pSelect = pWalker->u.pSelect;
1501     Window *pWin = pExpr->y.pWin;
1502     assert( pWin );
1503     assert( IsWindowFunc(pExpr) );
1504     assert( pWin->ppThis==0 );
1505     sqlite3WindowLink(pSelect, pWin);
1506   }
1507   return WRC_Continue;
1508 }
1509 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1510   return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1511 }
1512 static void gatherSelectWindows(Select *p){
1513   Walker w;
1514   w.xExprCallback = gatherSelectWindowsCallback;
1515   w.xSelectCallback = gatherSelectWindowsSelectCallback;
1516   w.xSelectCallback2 = 0;
1517   w.pParse = 0;
1518   w.u.pSelect = p;
1519   sqlite3WalkSelect(&w, p);
1520 }
1521 #endif
1522 
1523 
1524 /*
1525 ** The following group of routines make deep copies of expressions,
1526 ** expression lists, ID lists, and select statements.  The copies can
1527 ** be deleted (by being passed to their respective ...Delete() routines)
1528 ** without effecting the originals.
1529 **
1530 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1531 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1532 ** by subsequent calls to sqlite*ListAppend() routines.
1533 **
1534 ** Any tables that the SrcList might point to are not duplicated.
1535 **
1536 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1537 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1538 ** truncated version of the usual Expr structure that will be stored as
1539 ** part of the in-memory representation of the database schema.
1540 */
1541 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
1542   assert( flags==0 || flags==EXPRDUP_REDUCE );
1543   return p ? exprDup(db, p, flags, 0) : 0;
1544 }
1545 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1546   ExprList *pNew;
1547   struct ExprList_item *pItem, *pOldItem;
1548   int i;
1549   Expr *pPriorSelectColOld = 0;
1550   Expr *pPriorSelectColNew = 0;
1551   assert( db!=0 );
1552   if( p==0 ) return 0;
1553   pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1554   if( pNew==0 ) return 0;
1555   pNew->nExpr = p->nExpr;
1556   pNew->nAlloc = p->nAlloc;
1557   pItem = pNew->a;
1558   pOldItem = p->a;
1559   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1560     Expr *pOldExpr = pOldItem->pExpr;
1561     Expr *pNewExpr;
1562     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1563     if( pOldExpr
1564      && pOldExpr->op==TK_SELECT_COLUMN
1565      && (pNewExpr = pItem->pExpr)!=0
1566     ){
1567       if( pNewExpr->pRight ){
1568         pPriorSelectColOld = pOldExpr->pRight;
1569         pPriorSelectColNew = pNewExpr->pRight;
1570         pNewExpr->pLeft = pNewExpr->pRight;
1571       }else{
1572         if( pOldExpr->pLeft!=pPriorSelectColOld ){
1573           pPriorSelectColOld = pOldExpr->pLeft;
1574           pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1575           pNewExpr->pRight = pPriorSelectColNew;
1576         }
1577         pNewExpr->pLeft = pPriorSelectColNew;
1578       }
1579     }
1580     pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1581     pItem->sortFlags = pOldItem->sortFlags;
1582     pItem->eEName = pOldItem->eEName;
1583     pItem->done = 0;
1584     pItem->bNulls = pOldItem->bNulls;
1585     pItem->bSorterRef = pOldItem->bSorterRef;
1586     pItem->u = pOldItem->u;
1587   }
1588   return pNew;
1589 }
1590 
1591 /*
1592 ** If cursors, triggers, views and subqueries are all omitted from
1593 ** the build, then none of the following routines, except for
1594 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1595 ** called with a NULL argument.
1596 */
1597 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1598  || !defined(SQLITE_OMIT_SUBQUERY)
1599 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1600   SrcList *pNew;
1601   int i;
1602   int nByte;
1603   assert( db!=0 );
1604   if( p==0 ) return 0;
1605   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1606   pNew = sqlite3DbMallocRawNN(db, nByte );
1607   if( pNew==0 ) return 0;
1608   pNew->nSrc = pNew->nAlloc = p->nSrc;
1609   for(i=0; i<p->nSrc; i++){
1610     SrcItem *pNewItem = &pNew->a[i];
1611     SrcItem *pOldItem = &p->a[i];
1612     Table *pTab;
1613     pNewItem->pSchema = pOldItem->pSchema;
1614     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1615     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1616     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1617     pNewItem->fg = pOldItem->fg;
1618     pNewItem->iCursor = pOldItem->iCursor;
1619     pNewItem->addrFillSub = pOldItem->addrFillSub;
1620     pNewItem->regReturn = pOldItem->regReturn;
1621     if( pNewItem->fg.isIndexedBy ){
1622       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1623     }
1624     pNewItem->u2 = pOldItem->u2;
1625     if( pNewItem->fg.isCte ){
1626       pNewItem->u2.pCteUse->nUse++;
1627     }
1628     if( pNewItem->fg.isTabFunc ){
1629       pNewItem->u1.pFuncArg =
1630           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1631     }
1632     pTab = pNewItem->pTab = pOldItem->pTab;
1633     if( pTab ){
1634       pTab->nTabRef++;
1635     }
1636     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1637     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
1638     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1639     pNewItem->colUsed = pOldItem->colUsed;
1640   }
1641   return pNew;
1642 }
1643 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1644   IdList *pNew;
1645   int i;
1646   assert( db!=0 );
1647   if( p==0 ) return 0;
1648   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1649   if( pNew==0 ) return 0;
1650   pNew->nId = p->nId;
1651   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1652   if( pNew->a==0 ){
1653     sqlite3DbFreeNN(db, pNew);
1654     return 0;
1655   }
1656   /* Note that because the size of the allocation for p->a[] is not
1657   ** necessarily a power of two, sqlite3IdListAppend() may not be called
1658   ** on the duplicate created by this function. */
1659   for(i=0; i<p->nId; i++){
1660     struct IdList_item *pNewItem = &pNew->a[i];
1661     struct IdList_item *pOldItem = &p->a[i];
1662     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1663     pNewItem->idx = pOldItem->idx;
1664   }
1665   return pNew;
1666 }
1667 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1668   Select *pRet = 0;
1669   Select *pNext = 0;
1670   Select **pp = &pRet;
1671   Select *p;
1672 
1673   assert( db!=0 );
1674   for(p=pDup; p; p=p->pPrior){
1675     Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1676     if( pNew==0 ) break;
1677     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1678     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1679     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1680     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1681     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1682     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1683     pNew->op = p->op;
1684     pNew->pNext = pNext;
1685     pNew->pPrior = 0;
1686     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1687     pNew->iLimit = 0;
1688     pNew->iOffset = 0;
1689     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1690     pNew->addrOpenEphm[0] = -1;
1691     pNew->addrOpenEphm[1] = -1;
1692     pNew->nSelectRow = p->nSelectRow;
1693     pNew->pWith = sqlite3WithDup(db, p->pWith);
1694 #ifndef SQLITE_OMIT_WINDOWFUNC
1695     pNew->pWin = 0;
1696     pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1697     if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1698 #endif
1699     pNew->selId = p->selId;
1700     if( db->mallocFailed ){
1701       /* Any prior OOM might have left the Select object incomplete.
1702       ** Delete the whole thing rather than allow an incomplete Select
1703       ** to be used by the code generator. */
1704       pNew->pNext = 0;
1705       sqlite3SelectDelete(db, pNew);
1706       break;
1707     }
1708     *pp = pNew;
1709     pp = &pNew->pPrior;
1710     pNext = pNew;
1711   }
1712 
1713   return pRet;
1714 }
1715 #else
1716 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1717   assert( p==0 );
1718   return 0;
1719 }
1720 #endif
1721 
1722 
1723 /*
1724 ** Add a new element to the end of an expression list.  If pList is
1725 ** initially NULL, then create a new expression list.
1726 **
1727 ** The pList argument must be either NULL or a pointer to an ExprList
1728 ** obtained from a prior call to sqlite3ExprListAppend().  This routine
1729 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1730 ** Reason:  This routine assumes that the number of slots in pList->a[]
1731 ** is a power of two.  That is true for sqlite3ExprListAppend() returns
1732 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1733 **
1734 ** If a memory allocation error occurs, the entire list is freed and
1735 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1736 ** that the new entry was successfully appended.
1737 */
1738 static const struct ExprList_item zeroItem = {0};
1739 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
1740   sqlite3 *db,            /* Database handle.  Used for memory allocation */
1741   Expr *pExpr             /* Expression to be appended. Might be NULL */
1742 ){
1743   struct ExprList_item *pItem;
1744   ExprList *pList;
1745 
1746   pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
1747   if( pList==0 ){
1748     sqlite3ExprDelete(db, pExpr);
1749     return 0;
1750   }
1751   pList->nAlloc = 4;
1752   pList->nExpr = 1;
1753   pItem = &pList->a[0];
1754   *pItem = zeroItem;
1755   pItem->pExpr = pExpr;
1756   return pList;
1757 }
1758 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
1759   sqlite3 *db,            /* Database handle.  Used for memory allocation */
1760   ExprList *pList,        /* List to which to append. Might be NULL */
1761   Expr *pExpr             /* Expression to be appended. Might be NULL */
1762 ){
1763   struct ExprList_item *pItem;
1764   ExprList *pNew;
1765   pList->nAlloc *= 2;
1766   pNew = sqlite3DbRealloc(db, pList,
1767        sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
1768   if( pNew==0 ){
1769     sqlite3ExprListDelete(db, pList);
1770     sqlite3ExprDelete(db, pExpr);
1771     return 0;
1772   }else{
1773     pList = pNew;
1774   }
1775   pItem = &pList->a[pList->nExpr++];
1776   *pItem = zeroItem;
1777   pItem->pExpr = pExpr;
1778   return pList;
1779 }
1780 ExprList *sqlite3ExprListAppend(
1781   Parse *pParse,          /* Parsing context */
1782   ExprList *pList,        /* List to which to append. Might be NULL */
1783   Expr *pExpr             /* Expression to be appended. Might be NULL */
1784 ){
1785   struct ExprList_item *pItem;
1786   if( pList==0 ){
1787     return sqlite3ExprListAppendNew(pParse->db,pExpr);
1788   }
1789   if( pList->nAlloc<pList->nExpr+1 ){
1790     return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
1791   }
1792   pItem = &pList->a[pList->nExpr++];
1793   *pItem = zeroItem;
1794   pItem->pExpr = pExpr;
1795   return pList;
1796 }
1797 
1798 /*
1799 ** pColumns and pExpr form a vector assignment which is part of the SET
1800 ** clause of an UPDATE statement.  Like this:
1801 **
1802 **        (a,b,c) = (expr1,expr2,expr3)
1803 ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
1804 **
1805 ** For each term of the vector assignment, append new entries to the
1806 ** expression list pList.  In the case of a subquery on the RHS, append
1807 ** TK_SELECT_COLUMN expressions.
1808 */
1809 ExprList *sqlite3ExprListAppendVector(
1810   Parse *pParse,         /* Parsing context */
1811   ExprList *pList,       /* List to which to append. Might be NULL */
1812   IdList *pColumns,      /* List of names of LHS of the assignment */
1813   Expr *pExpr            /* Vector expression to be appended. Might be NULL */
1814 ){
1815   sqlite3 *db = pParse->db;
1816   int n;
1817   int i;
1818   int iFirst = pList ? pList->nExpr : 0;
1819   /* pColumns can only be NULL due to an OOM but an OOM will cause an
1820   ** exit prior to this routine being invoked */
1821   if( NEVER(pColumns==0) ) goto vector_append_error;
1822   if( pExpr==0 ) goto vector_append_error;
1823 
1824   /* If the RHS is a vector, then we can immediately check to see that
1825   ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
1826   ** wildcards ("*") in the result set of the SELECT must be expanded before
1827   ** we can do the size check, so defer the size check until code generation.
1828   */
1829   if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1830     sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1831                     pColumns->nId, n);
1832     goto vector_append_error;
1833   }
1834 
1835   for(i=0; i<pColumns->nId; i++){
1836     Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
1837     assert( pSubExpr!=0 || db->mallocFailed );
1838     if( pSubExpr==0 ) continue;
1839     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1840     if( pList ){
1841       assert( pList->nExpr==iFirst+i+1 );
1842       pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
1843       pColumns->a[i].zName = 0;
1844     }
1845   }
1846 
1847   if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1848     Expr *pFirst = pList->a[iFirst].pExpr;
1849     assert( pFirst!=0 );
1850     assert( pFirst->op==TK_SELECT_COLUMN );
1851 
1852     /* Store the SELECT statement in pRight so it will be deleted when
1853     ** sqlite3ExprListDelete() is called */
1854     pFirst->pRight = pExpr;
1855     pExpr = 0;
1856 
1857     /* Remember the size of the LHS in iTable so that we can check that
1858     ** the RHS and LHS sizes match during code generation. */
1859     pFirst->iTable = pColumns->nId;
1860   }
1861 
1862 vector_append_error:
1863   sqlite3ExprUnmapAndDelete(pParse, pExpr);
1864   sqlite3IdListDelete(db, pColumns);
1865   return pList;
1866 }
1867 
1868 /*
1869 ** Set the sort order for the last element on the given ExprList.
1870 */
1871 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
1872   struct ExprList_item *pItem;
1873   if( p==0 ) return;
1874   assert( p->nExpr>0 );
1875 
1876   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
1877   assert( iSortOrder==SQLITE_SO_UNDEFINED
1878        || iSortOrder==SQLITE_SO_ASC
1879        || iSortOrder==SQLITE_SO_DESC
1880   );
1881   assert( eNulls==SQLITE_SO_UNDEFINED
1882        || eNulls==SQLITE_SO_ASC
1883        || eNulls==SQLITE_SO_DESC
1884   );
1885 
1886   pItem = &p->a[p->nExpr-1];
1887   assert( pItem->bNulls==0 );
1888   if( iSortOrder==SQLITE_SO_UNDEFINED ){
1889     iSortOrder = SQLITE_SO_ASC;
1890   }
1891   pItem->sortFlags = (u8)iSortOrder;
1892 
1893   if( eNulls!=SQLITE_SO_UNDEFINED ){
1894     pItem->bNulls = 1;
1895     if( iSortOrder!=eNulls ){
1896       pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
1897     }
1898   }
1899 }
1900 
1901 /*
1902 ** Set the ExprList.a[].zEName element of the most recently added item
1903 ** on the expression list.
1904 **
1905 ** pList might be NULL following an OOM error.  But pName should never be
1906 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1907 ** is set.
1908 */
1909 void sqlite3ExprListSetName(
1910   Parse *pParse,          /* Parsing context */
1911   ExprList *pList,        /* List to which to add the span. */
1912   Token *pName,           /* Name to be added */
1913   int dequote             /* True to cause the name to be dequoted */
1914 ){
1915   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1916   assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
1917   if( pList ){
1918     struct ExprList_item *pItem;
1919     assert( pList->nExpr>0 );
1920     pItem = &pList->a[pList->nExpr-1];
1921     assert( pItem->zEName==0 );
1922     assert( pItem->eEName==ENAME_NAME );
1923     pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1924     if( dequote ){
1925       /* If dequote==0, then pName->z does not point to part of a DDL
1926       ** statement handled by the parser. And so no token need be added
1927       ** to the token-map.  */
1928       sqlite3Dequote(pItem->zEName);
1929       if( IN_RENAME_OBJECT ){
1930         sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
1931       }
1932     }
1933   }
1934 }
1935 
1936 /*
1937 ** Set the ExprList.a[].zSpan element of the most recently added item
1938 ** on the expression list.
1939 **
1940 ** pList might be NULL following an OOM error.  But pSpan should never be
1941 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1942 ** is set.
1943 */
1944 void sqlite3ExprListSetSpan(
1945   Parse *pParse,          /* Parsing context */
1946   ExprList *pList,        /* List to which to add the span. */
1947   const char *zStart,     /* Start of the span */
1948   const char *zEnd        /* End of the span */
1949 ){
1950   sqlite3 *db = pParse->db;
1951   assert( pList!=0 || db->mallocFailed!=0 );
1952   if( pList ){
1953     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1954     assert( pList->nExpr>0 );
1955     if( pItem->zEName==0 ){
1956       pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
1957       pItem->eEName = ENAME_SPAN;
1958     }
1959   }
1960 }
1961 
1962 /*
1963 ** If the expression list pEList contains more than iLimit elements,
1964 ** leave an error message in pParse.
1965 */
1966 void sqlite3ExprListCheckLength(
1967   Parse *pParse,
1968   ExprList *pEList,
1969   const char *zObject
1970 ){
1971   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1972   testcase( pEList && pEList->nExpr==mx );
1973   testcase( pEList && pEList->nExpr==mx+1 );
1974   if( pEList && pEList->nExpr>mx ){
1975     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1976   }
1977 }
1978 
1979 /*
1980 ** Delete an entire expression list.
1981 */
1982 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1983   int i = pList->nExpr;
1984   struct ExprList_item *pItem =  pList->a;
1985   assert( pList->nExpr>0 );
1986   do{
1987     sqlite3ExprDelete(db, pItem->pExpr);
1988     sqlite3DbFree(db, pItem->zEName);
1989     pItem++;
1990   }while( --i>0 );
1991   sqlite3DbFreeNN(db, pList);
1992 }
1993 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1994   if( pList ) exprListDeleteNN(db, pList);
1995 }
1996 
1997 /*
1998 ** Return the bitwise-OR of all Expr.flags fields in the given
1999 ** ExprList.
2000 */
2001 u32 sqlite3ExprListFlags(const ExprList *pList){
2002   int i;
2003   u32 m = 0;
2004   assert( pList!=0 );
2005   for(i=0; i<pList->nExpr; i++){
2006      Expr *pExpr = pList->a[i].pExpr;
2007      assert( pExpr!=0 );
2008      m |= pExpr->flags;
2009   }
2010   return m;
2011 }
2012 
2013 /*
2014 ** This is a SELECT-node callback for the expression walker that
2015 ** always "fails".  By "fail" in this case, we mean set
2016 ** pWalker->eCode to zero and abort.
2017 **
2018 ** This callback is used by multiple expression walkers.
2019 */
2020 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2021   UNUSED_PARAMETER(NotUsed);
2022   pWalker->eCode = 0;
2023   return WRC_Abort;
2024 }
2025 
2026 /*
2027 ** Check the input string to see if it is "true" or "false" (in any case).
2028 **
2029 **       If the string is....           Return
2030 **         "true"                         EP_IsTrue
2031 **         "false"                        EP_IsFalse
2032 **         anything else                  0
2033 */
2034 u32 sqlite3IsTrueOrFalse(const char *zIn){
2035   if( sqlite3StrICmp(zIn, "true")==0  ) return EP_IsTrue;
2036   if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2037   return 0;
2038 }
2039 
2040 
2041 /*
2042 ** If the input expression is an ID with the name "true" or "false"
2043 ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
2044 ** the conversion happened, and zero if the expression is unaltered.
2045 */
2046 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2047   u32 v;
2048   assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2049   if( !ExprHasProperty(pExpr, EP_Quoted)
2050    && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2051   ){
2052     pExpr->op = TK_TRUEFALSE;
2053     ExprSetProperty(pExpr, v);
2054     return 1;
2055   }
2056   return 0;
2057 }
2058 
2059 /*
2060 ** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
2061 ** and 0 if it is FALSE.
2062 */
2063 int sqlite3ExprTruthValue(const Expr *pExpr){
2064   pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
2065   assert( pExpr->op==TK_TRUEFALSE );
2066   assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2067        || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2068   return pExpr->u.zToken[4]==0;
2069 }
2070 
2071 /*
2072 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2073 ** terms that are always true or false.  Return the simplified expression.
2074 ** Or return the original expression if no simplification is possible.
2075 **
2076 ** Examples:
2077 **
2078 **     (x<10) AND true                =>   (x<10)
2079 **     (x<10) AND false               =>   false
2080 **     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)
2081 **     (x<10) AND (y=22 OR true)      =>   (x<10)
2082 **     (y=22) OR true                 =>   true
2083 */
2084 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2085   assert( pExpr!=0 );
2086   if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2087     Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2088     Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2089     if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2090       pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2091     }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2092       pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2093     }
2094   }
2095   return pExpr;
2096 }
2097 
2098 
2099 /*
2100 ** These routines are Walker callbacks used to check expressions to
2101 ** see if they are "constant" for some definition of constant.  The
2102 ** Walker.eCode value determines the type of "constant" we are looking
2103 ** for.
2104 **
2105 ** These callback routines are used to implement the following:
2106 **
2107 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
2108 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
2109 **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
2110 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
2111 **
2112 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2113 ** is found to not be a constant.
2114 **
2115 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2116 ** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5
2117 ** when parsing an existing schema out of the sqlite_schema table and 4
2118 ** when processing a new CREATE TABLE statement.  A bound parameter raises
2119 ** an error for new statements, but is silently converted
2120 ** to NULL for existing schemas.  This allows sqlite_schema tables that
2121 ** contain a bound parameter because they were generated by older versions
2122 ** of SQLite to be parsed by newer versions of SQLite without raising a
2123 ** malformed schema error.
2124 */
2125 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2126 
2127   /* If pWalker->eCode is 2 then any term of the expression that comes from
2128   ** the ON or USING clauses of a left join disqualifies the expression
2129   ** from being considered constant. */
2130   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
2131     pWalker->eCode = 0;
2132     return WRC_Abort;
2133   }
2134 
2135   switch( pExpr->op ){
2136     /* Consider functions to be constant if all their arguments are constant
2137     ** and either pWalker->eCode==4 or 5 or the function has the
2138     ** SQLITE_FUNC_CONST flag. */
2139     case TK_FUNCTION:
2140       if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2141        && !ExprHasProperty(pExpr, EP_WinFunc)
2142       ){
2143         if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2144         return WRC_Continue;
2145       }else{
2146         pWalker->eCode = 0;
2147         return WRC_Abort;
2148       }
2149     case TK_ID:
2150       /* Convert "true" or "false" in a DEFAULT clause into the
2151       ** appropriate TK_TRUEFALSE operator */
2152       if( sqlite3ExprIdToTrueFalse(pExpr) ){
2153         return WRC_Prune;
2154       }
2155       /* no break */ deliberate_fall_through
2156     case TK_COLUMN:
2157     case TK_AGG_FUNCTION:
2158     case TK_AGG_COLUMN:
2159       testcase( pExpr->op==TK_ID );
2160       testcase( pExpr->op==TK_COLUMN );
2161       testcase( pExpr->op==TK_AGG_FUNCTION );
2162       testcase( pExpr->op==TK_AGG_COLUMN );
2163       if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2164         return WRC_Continue;
2165       }
2166       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2167         return WRC_Continue;
2168       }
2169       /* no break */ deliberate_fall_through
2170     case TK_IF_NULL_ROW:
2171     case TK_REGISTER:
2172     case TK_DOT:
2173       testcase( pExpr->op==TK_REGISTER );
2174       testcase( pExpr->op==TK_IF_NULL_ROW );
2175       testcase( pExpr->op==TK_DOT );
2176       pWalker->eCode = 0;
2177       return WRC_Abort;
2178     case TK_VARIABLE:
2179       if( pWalker->eCode==5 ){
2180         /* Silently convert bound parameters that appear inside of CREATE
2181         ** statements into a NULL when parsing the CREATE statement text out
2182         ** of the sqlite_schema table */
2183         pExpr->op = TK_NULL;
2184       }else if( pWalker->eCode==4 ){
2185         /* A bound parameter in a CREATE statement that originates from
2186         ** sqlite3_prepare() causes an error */
2187         pWalker->eCode = 0;
2188         return WRC_Abort;
2189       }
2190       /* no break */ deliberate_fall_through
2191     default:
2192       testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2193       testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2194       return WRC_Continue;
2195   }
2196 }
2197 static int exprIsConst(Expr *p, int initFlag, int iCur){
2198   Walker w;
2199   w.eCode = initFlag;
2200   w.xExprCallback = exprNodeIsConstant;
2201   w.xSelectCallback = sqlite3SelectWalkFail;
2202 #ifdef SQLITE_DEBUG
2203   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2204 #endif
2205   w.u.iCur = iCur;
2206   sqlite3WalkExpr(&w, p);
2207   return w.eCode;
2208 }
2209 
2210 /*
2211 ** Walk an expression tree.  Return non-zero if the expression is constant
2212 ** and 0 if it involves variables or function calls.
2213 **
2214 ** For the purposes of this function, a double-quoted string (ex: "abc")
2215 ** is considered a variable but a single-quoted string (ex: 'abc') is
2216 ** a constant.
2217 */
2218 int sqlite3ExprIsConstant(Expr *p){
2219   return exprIsConst(p, 1, 0);
2220 }
2221 
2222 /*
2223 ** Walk an expression tree.  Return non-zero if
2224 **
2225 **   (1) the expression is constant, and
2226 **   (2) the expression does originate in the ON or USING clause
2227 **       of a LEFT JOIN, and
2228 **   (3) the expression does not contain any EP_FixedCol TK_COLUMN
2229 **       operands created by the constant propagation optimization.
2230 **
2231 ** When this routine returns true, it indicates that the expression
2232 ** can be added to the pParse->pConstExpr list and evaluated once when
2233 ** the prepared statement starts up.  See sqlite3ExprCodeRunJustOnce().
2234 */
2235 int sqlite3ExprIsConstantNotJoin(Expr *p){
2236   return exprIsConst(p, 2, 0);
2237 }
2238 
2239 /*
2240 ** Walk an expression tree.  Return non-zero if the expression is constant
2241 ** for any single row of the table with cursor iCur.  In other words, the
2242 ** expression must not refer to any non-deterministic function nor any
2243 ** table other than iCur.
2244 */
2245 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2246   return exprIsConst(p, 3, iCur);
2247 }
2248 
2249 
2250 /*
2251 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2252 */
2253 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2254   ExprList *pGroupBy = pWalker->u.pGroupBy;
2255   int i;
2256 
2257   /* Check if pExpr is identical to any GROUP BY term. If so, consider
2258   ** it constant.  */
2259   for(i=0; i<pGroupBy->nExpr; i++){
2260     Expr *p = pGroupBy->a[i].pExpr;
2261     if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2262       CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2263       if( sqlite3IsBinary(pColl) ){
2264         return WRC_Prune;
2265       }
2266     }
2267   }
2268 
2269   /* Check if pExpr is a sub-select. If so, consider it variable. */
2270   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2271     pWalker->eCode = 0;
2272     return WRC_Abort;
2273   }
2274 
2275   return exprNodeIsConstant(pWalker, pExpr);
2276 }
2277 
2278 /*
2279 ** Walk the expression tree passed as the first argument. Return non-zero
2280 ** if the expression consists entirely of constants or copies of terms
2281 ** in pGroupBy that sort with the BINARY collation sequence.
2282 **
2283 ** This routine is used to determine if a term of the HAVING clause can
2284 ** be promoted into the WHERE clause.  In order for such a promotion to work,
2285 ** the value of the HAVING clause term must be the same for all members of
2286 ** a "group".  The requirement that the GROUP BY term must be BINARY
2287 ** assumes that no other collating sequence will have a finer-grained
2288 ** grouping than binary.  In other words (A=B COLLATE binary) implies
2289 ** A=B in every other collating sequence.  The requirement that the
2290 ** GROUP BY be BINARY is stricter than necessary.  It would also work
2291 ** to promote HAVING clauses that use the same alternative collating
2292 ** sequence as the GROUP BY term, but that is much harder to check,
2293 ** alternative collating sequences are uncommon, and this is only an
2294 ** optimization, so we take the easy way out and simply require the
2295 ** GROUP BY to use the BINARY collating sequence.
2296 */
2297 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2298   Walker w;
2299   w.eCode = 1;
2300   w.xExprCallback = exprNodeIsConstantOrGroupBy;
2301   w.xSelectCallback = 0;
2302   w.u.pGroupBy = pGroupBy;
2303   w.pParse = pParse;
2304   sqlite3WalkExpr(&w, p);
2305   return w.eCode;
2306 }
2307 
2308 /*
2309 ** Walk an expression tree for the DEFAULT field of a column definition
2310 ** in a CREATE TABLE statement.  Return non-zero if the expression is
2311 ** acceptable for use as a DEFAULT.  That is to say, return non-zero if
2312 ** the expression is constant or a function call with constant arguments.
2313 ** Return and 0 if there are any variables.
2314 **
2315 ** isInit is true when parsing from sqlite_schema.  isInit is false when
2316 ** processing a new CREATE TABLE statement.  When isInit is true, parameters
2317 ** (such as ? or $abc) in the expression are converted into NULL.  When
2318 ** isInit is false, parameters raise an error.  Parameters should not be
2319 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2320 ** allowed it, so we need to support it when reading sqlite_schema for
2321 ** backwards compatibility.
2322 **
2323 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2324 **
2325 ** For the purposes of this function, a double-quoted string (ex: "abc")
2326 ** is considered a variable but a single-quoted string (ex: 'abc') is
2327 ** a constant.
2328 */
2329 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2330   assert( isInit==0 || isInit==1 );
2331   return exprIsConst(p, 4+isInit, 0);
2332 }
2333 
2334 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2335 /*
2336 ** Walk an expression tree.  Return 1 if the expression contains a
2337 ** subquery of some kind.  Return 0 if there are no subqueries.
2338 */
2339 int sqlite3ExprContainsSubquery(Expr *p){
2340   Walker w;
2341   w.eCode = 1;
2342   w.xExprCallback = sqlite3ExprWalkNoop;
2343   w.xSelectCallback = sqlite3SelectWalkFail;
2344 #ifdef SQLITE_DEBUG
2345   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2346 #endif
2347   sqlite3WalkExpr(&w, p);
2348   return w.eCode==0;
2349 }
2350 #endif
2351 
2352 /*
2353 ** If the expression p codes a constant integer that is small enough
2354 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2355 ** in *pValue.  If the expression is not an integer or if it is too big
2356 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2357 */
2358 int sqlite3ExprIsInteger(Expr *p, int *pValue){
2359   int rc = 0;
2360   if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
2361 
2362   /* If an expression is an integer literal that fits in a signed 32-bit
2363   ** integer, then the EP_IntValue flag will have already been set */
2364   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2365            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2366 
2367   if( p->flags & EP_IntValue ){
2368     *pValue = p->u.iValue;
2369     return 1;
2370   }
2371   switch( p->op ){
2372     case TK_UPLUS: {
2373       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2374       break;
2375     }
2376     case TK_UMINUS: {
2377       int v;
2378       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2379         assert( v!=(-2147483647-1) );
2380         *pValue = -v;
2381         rc = 1;
2382       }
2383       break;
2384     }
2385     default: break;
2386   }
2387   return rc;
2388 }
2389 
2390 /*
2391 ** Return FALSE if there is no chance that the expression can be NULL.
2392 **
2393 ** If the expression might be NULL or if the expression is too complex
2394 ** to tell return TRUE.
2395 **
2396 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2397 ** when we know that a value cannot be NULL.  Hence, a false positive
2398 ** (returning TRUE when in fact the expression can never be NULL) might
2399 ** be a small performance hit but is otherwise harmless.  On the other
2400 ** hand, a false negative (returning FALSE when the result could be NULL)
2401 ** will likely result in an incorrect answer.  So when in doubt, return
2402 ** TRUE.
2403 */
2404 int sqlite3ExprCanBeNull(const Expr *p){
2405   u8 op;
2406   assert( p!=0 );
2407   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2408     p = p->pLeft;
2409     assert( p!=0 );
2410   }
2411   op = p->op;
2412   if( op==TK_REGISTER ) op = p->op2;
2413   switch( op ){
2414     case TK_INTEGER:
2415     case TK_STRING:
2416     case TK_FLOAT:
2417     case TK_BLOB:
2418       return 0;
2419     case TK_COLUMN:
2420       return ExprHasProperty(p, EP_CanBeNull) ||
2421              p->y.pTab==0 ||  /* Reference to column of index on expression */
2422              (p->iColumn>=0
2423               && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
2424               && p->y.pTab->aCol[p->iColumn].notNull==0);
2425     default:
2426       return 1;
2427   }
2428 }
2429 
2430 /*
2431 ** Return TRUE if the given expression is a constant which would be
2432 ** unchanged by OP_Affinity with the affinity given in the second
2433 ** argument.
2434 **
2435 ** This routine is used to determine if the OP_Affinity operation
2436 ** can be omitted.  When in doubt return FALSE.  A false negative
2437 ** is harmless.  A false positive, however, can result in the wrong
2438 ** answer.
2439 */
2440 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2441   u8 op;
2442   int unaryMinus = 0;
2443   if( aff==SQLITE_AFF_BLOB ) return 1;
2444   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2445     if( p->op==TK_UMINUS ) unaryMinus = 1;
2446     p = p->pLeft;
2447   }
2448   op = p->op;
2449   if( op==TK_REGISTER ) op = p->op2;
2450   switch( op ){
2451     case TK_INTEGER: {
2452       return aff>=SQLITE_AFF_NUMERIC;
2453     }
2454     case TK_FLOAT: {
2455       return aff>=SQLITE_AFF_NUMERIC;
2456     }
2457     case TK_STRING: {
2458       return !unaryMinus && aff==SQLITE_AFF_TEXT;
2459     }
2460     case TK_BLOB: {
2461       return !unaryMinus;
2462     }
2463     case TK_COLUMN: {
2464       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
2465       return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2466     }
2467     default: {
2468       return 0;
2469     }
2470   }
2471 }
2472 
2473 /*
2474 ** Return TRUE if the given string is a row-id column name.
2475 */
2476 int sqlite3IsRowid(const char *z){
2477   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2478   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2479   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2480   return 0;
2481 }
2482 
2483 /*
2484 ** pX is the RHS of an IN operator.  If pX is a SELECT statement
2485 ** that can be simplified to a direct table access, then return
2486 ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
2487 ** or if the SELECT statement needs to be manifested into a transient
2488 ** table, then return NULL.
2489 */
2490 #ifndef SQLITE_OMIT_SUBQUERY
2491 static Select *isCandidateForInOpt(Expr *pX){
2492   Select *p;
2493   SrcList *pSrc;
2494   ExprList *pEList;
2495   Table *pTab;
2496   int i;
2497   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
2498   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
2499   p = pX->x.pSelect;
2500   if( p->pPrior ) return 0;              /* Not a compound SELECT */
2501   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2502     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2503     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2504     return 0; /* No DISTINCT keyword and no aggregate functions */
2505   }
2506   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
2507   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
2508   if( p->pWhere ) return 0;              /* Has no WHERE clause */
2509   pSrc = p->pSrc;
2510   assert( pSrc!=0 );
2511   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
2512   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
2513   pTab = pSrc->a[0].pTab;
2514   assert( pTab!=0 );
2515   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
2516   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
2517   pEList = p->pEList;
2518   assert( pEList!=0 );
2519   /* All SELECT results must be columns. */
2520   for(i=0; i<pEList->nExpr; i++){
2521     Expr *pRes = pEList->a[i].pExpr;
2522     if( pRes->op!=TK_COLUMN ) return 0;
2523     assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
2524   }
2525   return p;
2526 }
2527 #endif /* SQLITE_OMIT_SUBQUERY */
2528 
2529 #ifndef SQLITE_OMIT_SUBQUERY
2530 /*
2531 ** Generate code that checks the left-most column of index table iCur to see if
2532 ** it contains any NULL entries.  Cause the register at regHasNull to be set
2533 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
2534 ** to be set to NULL if iCur contains one or more NULL values.
2535 */
2536 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2537   int addr1;
2538   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2539   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2540   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2541   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2542   VdbeComment((v, "first_entry_in(%d)", iCur));
2543   sqlite3VdbeJumpHere(v, addr1);
2544 }
2545 #endif
2546 
2547 
2548 #ifndef SQLITE_OMIT_SUBQUERY
2549 /*
2550 ** The argument is an IN operator with a list (not a subquery) on the
2551 ** right-hand side.  Return TRUE if that list is constant.
2552 */
2553 static int sqlite3InRhsIsConstant(Expr *pIn){
2554   Expr *pLHS;
2555   int res;
2556   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2557   pLHS = pIn->pLeft;
2558   pIn->pLeft = 0;
2559   res = sqlite3ExprIsConstant(pIn);
2560   pIn->pLeft = pLHS;
2561   return res;
2562 }
2563 #endif
2564 
2565 /*
2566 ** This function is used by the implementation of the IN (...) operator.
2567 ** The pX parameter is the expression on the RHS of the IN operator, which
2568 ** might be either a list of expressions or a subquery.
2569 **
2570 ** The job of this routine is to find or create a b-tree object that can
2571 ** be used either to test for membership in the RHS set or to iterate through
2572 ** all members of the RHS set, skipping duplicates.
2573 **
2574 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2575 ** and pX->iTable is set to the index of that cursor.
2576 **
2577 ** The returned value of this function indicates the b-tree type, as follows:
2578 **
2579 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
2580 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
2581 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2582 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
2583 **                         populated epheremal table.
2584 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
2585 **                         implemented as a sequence of comparisons.
2586 **
2587 ** An existing b-tree might be used if the RHS expression pX is a simple
2588 ** subquery such as:
2589 **
2590 **     SELECT <column1>, <column2>... FROM <table>
2591 **
2592 ** If the RHS of the IN operator is a list or a more complex subquery, then
2593 ** an ephemeral table might need to be generated from the RHS and then
2594 ** pX->iTable made to point to the ephemeral table instead of an
2595 ** existing table.
2596 **
2597 ** The inFlags parameter must contain, at a minimum, one of the bits
2598 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
2599 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2600 ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
2601 ** be used to loop over all values of the RHS of the IN operator.
2602 **
2603 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2604 ** through the set members) then the b-tree must not contain duplicates.
2605 ** An epheremal table will be created unless the selected columns are guaranteed
2606 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2607 ** a UNIQUE constraint or index.
2608 **
2609 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2610 ** for fast set membership tests) then an epheremal table must
2611 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2612 ** index can be found with the specified <columns> as its left-most.
2613 **
2614 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2615 ** if the RHS of the IN operator is a list (not a subquery) then this
2616 ** routine might decide that creating an ephemeral b-tree for membership
2617 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
2618 ** calling routine should implement the IN operator using a sequence
2619 ** of Eq or Ne comparison operations.
2620 **
2621 ** When the b-tree is being used for membership tests, the calling function
2622 ** might need to know whether or not the RHS side of the IN operator
2623 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
2624 ** if there is any chance that the (...) might contain a NULL value at
2625 ** runtime, then a register is allocated and the register number written
2626 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2627 ** NULL value, then *prRhsHasNull is left unchanged.
2628 **
2629 ** If a register is allocated and its location stored in *prRhsHasNull, then
2630 ** the value in that register will be NULL if the b-tree contains one or more
2631 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2632 ** NULL values.
2633 **
2634 ** If the aiMap parameter is not NULL, it must point to an array containing
2635 ** one element for each column returned by the SELECT statement on the RHS
2636 ** of the IN(...) operator. The i'th entry of the array is populated with the
2637 ** offset of the index column that matches the i'th column returned by the
2638 ** SELECT. For example, if the expression and selected index are:
2639 **
2640 **   (?,?,?) IN (SELECT a, b, c FROM t1)
2641 **   CREATE INDEX i1 ON t1(b, c, a);
2642 **
2643 ** then aiMap[] is populated with {2, 0, 1}.
2644 */
2645 #ifndef SQLITE_OMIT_SUBQUERY
2646 int sqlite3FindInIndex(
2647   Parse *pParse,             /* Parsing context */
2648   Expr *pX,                  /* The IN expression */
2649   u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2650   int *prRhsHasNull,         /* Register holding NULL status.  See notes */
2651   int *aiMap,                /* Mapping from Index fields to RHS fields */
2652   int *piTab                 /* OUT: index to use */
2653 ){
2654   Select *p;                            /* SELECT to the right of IN operator */
2655   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
2656   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
2657   int mustBeUnique;                     /* True if RHS must be unique */
2658   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
2659 
2660   assert( pX->op==TK_IN );
2661   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2662 
2663   /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2664   ** whether or not the SELECT result contains NULL values, check whether
2665   ** or not NULL is actually possible (it may not be, for example, due
2666   ** to NOT NULL constraints in the schema). If no NULL values are possible,
2667   ** set prRhsHasNull to 0 before continuing.  */
2668   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2669     int i;
2670     ExprList *pEList = pX->x.pSelect->pEList;
2671     for(i=0; i<pEList->nExpr; i++){
2672       if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2673     }
2674     if( i==pEList->nExpr ){
2675       prRhsHasNull = 0;
2676     }
2677   }
2678 
2679   /* Check to see if an existing table or index can be used to
2680   ** satisfy the query.  This is preferable to generating a new
2681   ** ephemeral table.  */
2682   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2683     sqlite3 *db = pParse->db;              /* Database connection */
2684     Table *pTab;                           /* Table <table>. */
2685     int iDb;                               /* Database idx for pTab */
2686     ExprList *pEList = p->pEList;
2687     int nExpr = pEList->nExpr;
2688 
2689     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
2690     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2691     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
2692     pTab = p->pSrc->a[0].pTab;
2693 
2694     /* Code an OP_Transaction and OP_TableLock for <table>. */
2695     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2696     assert( iDb>=0 && iDb<SQLITE_MAX_DB );
2697     sqlite3CodeVerifySchema(pParse, iDb);
2698     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2699 
2700     assert(v);  /* sqlite3GetVdbe() has always been previously called */
2701     if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2702       /* The "x IN (SELECT rowid FROM table)" case */
2703       int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2704       VdbeCoverage(v);
2705 
2706       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2707       eType = IN_INDEX_ROWID;
2708       ExplainQueryPlan((pParse, 0,
2709             "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
2710       sqlite3VdbeJumpHere(v, iAddr);
2711     }else{
2712       Index *pIdx;                         /* Iterator variable */
2713       int affinity_ok = 1;
2714       int i;
2715 
2716       /* Check that the affinity that will be used to perform each
2717       ** comparison is the same as the affinity of each column in table
2718       ** on the RHS of the IN operator.  If it not, it is not possible to
2719       ** use any index of the RHS table.  */
2720       for(i=0; i<nExpr && affinity_ok; i++){
2721         Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2722         int iCol = pEList->a[i].pExpr->iColumn;
2723         char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2724         char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2725         testcase( cmpaff==SQLITE_AFF_BLOB );
2726         testcase( cmpaff==SQLITE_AFF_TEXT );
2727         switch( cmpaff ){
2728           case SQLITE_AFF_BLOB:
2729             break;
2730           case SQLITE_AFF_TEXT:
2731             /* sqlite3CompareAffinity() only returns TEXT if one side or the
2732             ** other has no affinity and the other side is TEXT.  Hence,
2733             ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2734             ** and for the term on the LHS of the IN to have no affinity. */
2735             assert( idxaff==SQLITE_AFF_TEXT );
2736             break;
2737           default:
2738             affinity_ok = sqlite3IsNumericAffinity(idxaff);
2739         }
2740       }
2741 
2742       if( affinity_ok ){
2743         /* Search for an existing index that will work for this IN operator */
2744         for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2745           Bitmask colUsed;      /* Columns of the index used */
2746           Bitmask mCol;         /* Mask for the current column */
2747           if( pIdx->nColumn<nExpr ) continue;
2748           if( pIdx->pPartIdxWhere!=0 ) continue;
2749           /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2750           ** BITMASK(nExpr) without overflowing */
2751           testcase( pIdx->nColumn==BMS-2 );
2752           testcase( pIdx->nColumn==BMS-1 );
2753           if( pIdx->nColumn>=BMS-1 ) continue;
2754           if( mustBeUnique ){
2755             if( pIdx->nKeyCol>nExpr
2756              ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2757             ){
2758               continue;  /* This index is not unique over the IN RHS columns */
2759             }
2760           }
2761 
2762           colUsed = 0;   /* Columns of index used so far */
2763           for(i=0; i<nExpr; i++){
2764             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2765             Expr *pRhs = pEList->a[i].pExpr;
2766             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2767             int j;
2768 
2769             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2770             for(j=0; j<nExpr; j++){
2771               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2772               assert( pIdx->azColl[j] );
2773               if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2774                 continue;
2775               }
2776               break;
2777             }
2778             if( j==nExpr ) break;
2779             mCol = MASKBIT(j);
2780             if( mCol & colUsed ) break; /* Each column used only once */
2781             colUsed |= mCol;
2782             if( aiMap ) aiMap[i] = j;
2783           }
2784 
2785           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2786           if( colUsed==(MASKBIT(nExpr)-1) ){
2787             /* If we reach this point, that means the index pIdx is usable */
2788             int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2789             ExplainQueryPlan((pParse, 0,
2790                               "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
2791             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2792             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2793             VdbeComment((v, "%s", pIdx->zName));
2794             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2795             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2796 
2797             if( prRhsHasNull ){
2798 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2799               i64 mask = (1<<nExpr)-1;
2800               sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2801                   iTab, 0, 0, (u8*)&mask, P4_INT64);
2802 #endif
2803               *prRhsHasNull = ++pParse->nMem;
2804               if( nExpr==1 ){
2805                 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2806               }
2807             }
2808             sqlite3VdbeJumpHere(v, iAddr);
2809           }
2810         } /* End loop over indexes */
2811       } /* End if( affinity_ok ) */
2812     } /* End if not an rowid index */
2813   } /* End attempt to optimize using an index */
2814 
2815   /* If no preexisting index is available for the IN clause
2816   ** and IN_INDEX_NOOP is an allowed reply
2817   ** and the RHS of the IN operator is a list, not a subquery
2818   ** and the RHS is not constant or has two or fewer terms,
2819   ** then it is not worth creating an ephemeral table to evaluate
2820   ** the IN operator so return IN_INDEX_NOOP.
2821   */
2822   if( eType==0
2823    && (inFlags & IN_INDEX_NOOP_OK)
2824    && !ExprHasProperty(pX, EP_xIsSelect)
2825    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2826   ){
2827     eType = IN_INDEX_NOOP;
2828   }
2829 
2830   if( eType==0 ){
2831     /* Could not find an existing table or index to use as the RHS b-tree.
2832     ** We will have to generate an ephemeral table to do the job.
2833     */
2834     u32 savedNQueryLoop = pParse->nQueryLoop;
2835     int rMayHaveNull = 0;
2836     eType = IN_INDEX_EPH;
2837     if( inFlags & IN_INDEX_LOOP ){
2838       pParse->nQueryLoop = 0;
2839     }else if( prRhsHasNull ){
2840       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2841     }
2842     assert( pX->op==TK_IN );
2843     sqlite3CodeRhsOfIN(pParse, pX, iTab);
2844     if( rMayHaveNull ){
2845       sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
2846     }
2847     pParse->nQueryLoop = savedNQueryLoop;
2848   }
2849 
2850   if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2851     int i, n;
2852     n = sqlite3ExprVectorSize(pX->pLeft);
2853     for(i=0; i<n; i++) aiMap[i] = i;
2854   }
2855   *piTab = iTab;
2856   return eType;
2857 }
2858 #endif
2859 
2860 #ifndef SQLITE_OMIT_SUBQUERY
2861 /*
2862 ** Argument pExpr is an (?, ?...) IN(...) expression. This
2863 ** function allocates and returns a nul-terminated string containing
2864 ** the affinities to be used for each column of the comparison.
2865 **
2866 ** It is the responsibility of the caller to ensure that the returned
2867 ** string is eventually freed using sqlite3DbFree().
2868 */
2869 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2870   Expr *pLeft = pExpr->pLeft;
2871   int nVal = sqlite3ExprVectorSize(pLeft);
2872   Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
2873   char *zRet;
2874 
2875   assert( pExpr->op==TK_IN );
2876   zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
2877   if( zRet ){
2878     int i;
2879     for(i=0; i<nVal; i++){
2880       Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2881       char a = sqlite3ExprAffinity(pA);
2882       if( pSelect ){
2883         zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2884       }else{
2885         zRet[i] = a;
2886       }
2887     }
2888     zRet[nVal] = '\0';
2889   }
2890   return zRet;
2891 }
2892 #endif
2893 
2894 #ifndef SQLITE_OMIT_SUBQUERY
2895 /*
2896 ** Load the Parse object passed as the first argument with an error
2897 ** message of the form:
2898 **
2899 **   "sub-select returns N columns - expected M"
2900 */
2901 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2902   if( pParse->nErr==0 ){
2903     const char *zFmt = "sub-select returns %d columns - expected %d";
2904     sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2905   }
2906 }
2907 #endif
2908 
2909 /*
2910 ** Expression pExpr is a vector that has been used in a context where
2911 ** it is not permitted. If pExpr is a sub-select vector, this routine
2912 ** loads the Parse object with a message of the form:
2913 **
2914 **   "sub-select returns N columns - expected 1"
2915 **
2916 ** Or, if it is a regular scalar vector:
2917 **
2918 **   "row value misused"
2919 */
2920 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2921 #ifndef SQLITE_OMIT_SUBQUERY
2922   if( pExpr->flags & EP_xIsSelect ){
2923     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2924   }else
2925 #endif
2926   {
2927     sqlite3ErrorMsg(pParse, "row value misused");
2928   }
2929 }
2930 
2931 #ifndef SQLITE_OMIT_SUBQUERY
2932 /*
2933 ** Generate code that will construct an ephemeral table containing all terms
2934 ** in the RHS of an IN operator.  The IN operator can be in either of two
2935 ** forms:
2936 **
2937 **     x IN (4,5,11)              -- IN operator with list on right-hand side
2938 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
2939 **
2940 ** The pExpr parameter is the IN operator.  The cursor number for the
2941 ** constructed ephermeral table is returned.  The first time the ephemeral
2942 ** table is computed, the cursor number is also stored in pExpr->iTable,
2943 ** however the cursor number returned might not be the same, as it might
2944 ** have been duplicated using OP_OpenDup.
2945 **
2946 ** If the LHS expression ("x" in the examples) is a column value, or
2947 ** the SELECT statement returns a column value, then the affinity of that
2948 ** column is used to build the index keys. If both 'x' and the
2949 ** SELECT... statement are columns, then numeric affinity is used
2950 ** if either column has NUMERIC or INTEGER affinity. If neither
2951 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2952 ** is used.
2953 */
2954 void sqlite3CodeRhsOfIN(
2955   Parse *pParse,          /* Parsing context */
2956   Expr *pExpr,            /* The IN operator */
2957   int iTab                /* Use this cursor number */
2958 ){
2959   int addrOnce = 0;           /* Address of the OP_Once instruction at top */
2960   int addr;                   /* Address of OP_OpenEphemeral instruction */
2961   Expr *pLeft;                /* the LHS of the IN operator */
2962   KeyInfo *pKeyInfo = 0;      /* Key information */
2963   int nVal;                   /* Size of vector pLeft */
2964   Vdbe *v;                    /* The prepared statement under construction */
2965 
2966   v = pParse->pVdbe;
2967   assert( v!=0 );
2968 
2969   /* The evaluation of the IN must be repeated every time it
2970   ** is encountered if any of the following is true:
2971   **
2972   **    *  The right-hand side is a correlated subquery
2973   **    *  The right-hand side is an expression list containing variables
2974   **    *  We are inside a trigger
2975   **
2976   ** If all of the above are false, then we can compute the RHS just once
2977   ** and reuse it many names.
2978   */
2979   if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
2980     /* Reuse of the RHS is allowed */
2981     /* If this routine has already been coded, but the previous code
2982     ** might not have been invoked yet, so invoke it now as a subroutine.
2983     */
2984     if( ExprHasProperty(pExpr, EP_Subrtn) ){
2985       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2986       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2987         ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
2988               pExpr->x.pSelect->selId));
2989       }
2990       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
2991                         pExpr->y.sub.iAddr);
2992       sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
2993       sqlite3VdbeJumpHere(v, addrOnce);
2994       return;
2995     }
2996 
2997     /* Begin coding the subroutine */
2998     ExprSetProperty(pExpr, EP_Subrtn);
2999     assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3000     pExpr->y.sub.regReturn = ++pParse->nMem;
3001     pExpr->y.sub.iAddr =
3002       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
3003     VdbeComment((v, "return address"));
3004 
3005     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3006   }
3007 
3008   /* Check to see if this is a vector IN operator */
3009   pLeft = pExpr->pLeft;
3010   nVal = sqlite3ExprVectorSize(pLeft);
3011 
3012   /* Construct the ephemeral table that will contain the content of
3013   ** RHS of the IN operator.
3014   */
3015   pExpr->iTable = iTab;
3016   addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3017 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3018   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3019     VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3020   }else{
3021     VdbeComment((v, "RHS of IN operator"));
3022   }
3023 #endif
3024   pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3025 
3026   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3027     /* Case 1:     expr IN (SELECT ...)
3028     **
3029     ** Generate code to write the results of the select into the temporary
3030     ** table allocated and opened above.
3031     */
3032     Select *pSelect = pExpr->x.pSelect;
3033     ExprList *pEList = pSelect->pEList;
3034 
3035     ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3036         addrOnce?"":"CORRELATED ", pSelect->selId
3037     ));
3038     /* If the LHS and RHS of the IN operator do not match, that
3039     ** error will have been caught long before we reach this point. */
3040     if( ALWAYS(pEList->nExpr==nVal) ){
3041       Select *pCopy;
3042       SelectDest dest;
3043       int i;
3044       int rc;
3045       sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3046       dest.zAffSdst = exprINAffinity(pParse, pExpr);
3047       pSelect->iLimit = 0;
3048       testcase( pSelect->selFlags & SF_Distinct );
3049       testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3050       pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3051       rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3052       sqlite3SelectDelete(pParse->db, pCopy);
3053       sqlite3DbFree(pParse->db, dest.zAffSdst);
3054       if( rc ){
3055         sqlite3KeyInfoUnref(pKeyInfo);
3056         return;
3057       }
3058       assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3059       assert( pEList!=0 );
3060       assert( pEList->nExpr>0 );
3061       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3062       for(i=0; i<nVal; i++){
3063         Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3064         pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3065             pParse, p, pEList->a[i].pExpr
3066         );
3067       }
3068     }
3069   }else if( ALWAYS(pExpr->x.pList!=0) ){
3070     /* Case 2:     expr IN (exprlist)
3071     **
3072     ** For each expression, build an index key from the evaluation and
3073     ** store it in the temporary table. If <expr> is a column, then use
3074     ** that columns affinity when building index keys. If <expr> is not
3075     ** a column, use numeric affinity.
3076     */
3077     char affinity;            /* Affinity of the LHS of the IN */
3078     int i;
3079     ExprList *pList = pExpr->x.pList;
3080     struct ExprList_item *pItem;
3081     int r1, r2;
3082     affinity = sqlite3ExprAffinity(pLeft);
3083     if( affinity<=SQLITE_AFF_NONE ){
3084       affinity = SQLITE_AFF_BLOB;
3085     }else if( affinity==SQLITE_AFF_REAL ){
3086       affinity = SQLITE_AFF_NUMERIC;
3087     }
3088     if( pKeyInfo ){
3089       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3090       pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3091     }
3092 
3093     /* Loop through each expression in <exprlist>. */
3094     r1 = sqlite3GetTempReg(pParse);
3095     r2 = sqlite3GetTempReg(pParse);
3096     for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3097       Expr *pE2 = pItem->pExpr;
3098 
3099       /* If the expression is not constant then we will need to
3100       ** disable the test that was generated above that makes sure
3101       ** this code only executes once.  Because for a non-constant
3102       ** expression we need to rerun this code each time.
3103       */
3104       if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
3105         sqlite3VdbeChangeToNoop(v, addrOnce);
3106         ExprClearProperty(pExpr, EP_Subrtn);
3107         addrOnce = 0;
3108       }
3109 
3110       /* Evaluate the expression and insert it into the temp table */
3111       sqlite3ExprCode(pParse, pE2, r1);
3112       sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3113       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3114     }
3115     sqlite3ReleaseTempReg(pParse, r1);
3116     sqlite3ReleaseTempReg(pParse, r2);
3117   }
3118   if( pKeyInfo ){
3119     sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3120   }
3121   if( addrOnce ){
3122     sqlite3VdbeJumpHere(v, addrOnce);
3123     /* Subroutine return */
3124     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
3125     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
3126     sqlite3ClearTempRegCache(pParse);
3127   }
3128 }
3129 #endif /* SQLITE_OMIT_SUBQUERY */
3130 
3131 /*
3132 ** Generate code for scalar subqueries used as a subquery expression
3133 ** or EXISTS operator:
3134 **
3135 **     (SELECT a FROM b)          -- subquery
3136 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
3137 **
3138 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3139 **
3140 ** Return the register that holds the result.  For a multi-column SELECT,
3141 ** the result is stored in a contiguous array of registers and the
3142 ** return value is the register of the left-most result column.
3143 ** Return 0 if an error occurs.
3144 */
3145 #ifndef SQLITE_OMIT_SUBQUERY
3146 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3147   int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
3148   int rReg = 0;               /* Register storing resulting */
3149   Select *pSel;               /* SELECT statement to encode */
3150   SelectDest dest;            /* How to deal with SELECT result */
3151   int nReg;                   /* Registers to allocate */
3152   Expr *pLimit;               /* New limit expression */
3153 
3154   Vdbe *v = pParse->pVdbe;
3155   assert( v!=0 );
3156   if( pParse->nErr ) return 0;
3157   testcase( pExpr->op==TK_EXISTS );
3158   testcase( pExpr->op==TK_SELECT );
3159   assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3160   assert( ExprHasProperty(pExpr, EP_xIsSelect) );
3161   pSel = pExpr->x.pSelect;
3162 
3163   /* If this routine has already been coded, then invoke it as a
3164   ** subroutine. */
3165   if( ExprHasProperty(pExpr, EP_Subrtn) ){
3166     ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3167     sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3168                       pExpr->y.sub.iAddr);
3169     return pExpr->iTable;
3170   }
3171 
3172   /* Begin coding the subroutine */
3173   ExprSetProperty(pExpr, EP_Subrtn);
3174   pExpr->y.sub.regReturn = ++pParse->nMem;
3175   pExpr->y.sub.iAddr =
3176     sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
3177   VdbeComment((v, "return address"));
3178 
3179 
3180   /* The evaluation of the EXISTS/SELECT must be repeated every time it
3181   ** is encountered if any of the following is true:
3182   **
3183   **    *  The right-hand side is a correlated subquery
3184   **    *  The right-hand side is an expression list containing variables
3185   **    *  We are inside a trigger
3186   **
3187   ** If all of the above are false, then we can run this code just once
3188   ** save the results, and reuse the same result on subsequent invocations.
3189   */
3190   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3191     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3192   }
3193 
3194   /* For a SELECT, generate code to put the values for all columns of
3195   ** the first row into an array of registers and return the index of
3196   ** the first register.
3197   **
3198   ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3199   ** into a register and return that register number.
3200   **
3201   ** In both cases, the query is augmented with "LIMIT 1".  Any
3202   ** preexisting limit is discarded in place of the new LIMIT 1.
3203   */
3204   ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
3205         addrOnce?"":"CORRELATED ", pSel->selId));
3206   nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3207   sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3208   pParse->nMem += nReg;
3209   if( pExpr->op==TK_SELECT ){
3210     dest.eDest = SRT_Mem;
3211     dest.iSdst = dest.iSDParm;
3212     dest.nSdst = nReg;
3213     sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3214     VdbeComment((v, "Init subquery result"));
3215   }else{
3216     dest.eDest = SRT_Exists;
3217     sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3218     VdbeComment((v, "Init EXISTS result"));
3219   }
3220   if( pSel->pLimit ){
3221     /* The subquery already has a limit.  If the pre-existing limit is X
3222     ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3223     sqlite3 *db = pParse->db;
3224     pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3225     if( pLimit ){
3226       pLimit->affExpr = SQLITE_AFF_NUMERIC;
3227       pLimit = sqlite3PExpr(pParse, TK_NE,
3228                             sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3229     }
3230     sqlite3ExprDelete(db, pSel->pLimit->pLeft);
3231     pSel->pLimit->pLeft = pLimit;
3232   }else{
3233     /* If there is no pre-existing limit add a limit of 1 */
3234     pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3235     pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3236   }
3237   pSel->iLimit = 0;
3238   if( sqlite3Select(pParse, pSel, &dest) ){
3239     if( pParse->nErr ){
3240       pExpr->op2 = pExpr->op;
3241       pExpr->op = TK_ERROR;
3242     }
3243     return 0;
3244   }
3245   pExpr->iTable = rReg = dest.iSDParm;
3246   ExprSetVVAProperty(pExpr, EP_NoReduce);
3247   if( addrOnce ){
3248     sqlite3VdbeJumpHere(v, addrOnce);
3249   }
3250 
3251   /* Subroutine return */
3252   sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
3253   sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
3254   sqlite3ClearTempRegCache(pParse);
3255   return rReg;
3256 }
3257 #endif /* SQLITE_OMIT_SUBQUERY */
3258 
3259 #ifndef SQLITE_OMIT_SUBQUERY
3260 /*
3261 ** Expr pIn is an IN(...) expression. This function checks that the
3262 ** sub-select on the RHS of the IN() operator has the same number of
3263 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3264 ** a sub-query, that the LHS is a vector of size 1.
3265 */
3266 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3267   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3268   if( (pIn->flags & EP_xIsSelect)!=0 && !pParse->db->mallocFailed ){
3269     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3270       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3271       return 1;
3272     }
3273   }else if( nVector!=1 ){
3274     sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3275     return 1;
3276   }
3277   return 0;
3278 }
3279 #endif
3280 
3281 #ifndef SQLITE_OMIT_SUBQUERY
3282 /*
3283 ** Generate code for an IN expression.
3284 **
3285 **      x IN (SELECT ...)
3286 **      x IN (value, value, ...)
3287 **
3288 ** The left-hand side (LHS) is a scalar or vector expression.  The
3289 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3290 ** subquery.  If the RHS is a subquery, the number of result columns must
3291 ** match the number of columns in the vector on the LHS.  If the RHS is
3292 ** a list of values, the LHS must be a scalar.
3293 **
3294 ** The IN operator is true if the LHS value is contained within the RHS.
3295 ** The result is false if the LHS is definitely not in the RHS.  The
3296 ** result is NULL if the presence of the LHS in the RHS cannot be
3297 ** determined due to NULLs.
3298 **
3299 ** This routine generates code that jumps to destIfFalse if the LHS is not
3300 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
3301 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
3302 ** within the RHS then fall through.
3303 **
3304 ** See the separate in-operator.md documentation file in the canonical
3305 ** SQLite source tree for additional information.
3306 */
3307 static void sqlite3ExprCodeIN(
3308   Parse *pParse,        /* Parsing and code generating context */
3309   Expr *pExpr,          /* The IN expression */
3310   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
3311   int destIfNull        /* Jump here if the results are unknown due to NULLs */
3312 ){
3313   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
3314   int eType;            /* Type of the RHS */
3315   int rLhs;             /* Register(s) holding the LHS values */
3316   int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
3317   Vdbe *v;              /* Statement under construction */
3318   int *aiMap = 0;       /* Map from vector field to index column */
3319   char *zAff = 0;       /* Affinity string for comparisons */
3320   int nVector;          /* Size of vectors for this IN operator */
3321   int iDummy;           /* Dummy parameter to exprCodeVector() */
3322   Expr *pLeft;          /* The LHS of the IN operator */
3323   int i;                /* loop counter */
3324   int destStep2;        /* Where to jump when NULLs seen in step 2 */
3325   int destStep6 = 0;    /* Start of code for Step 6 */
3326   int addrTruthOp;      /* Address of opcode that determines the IN is true */
3327   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
3328   int addrTop;          /* Top of the step-6 loop */
3329   int iTab = 0;         /* Index to use */
3330   u8 okConstFactor = pParse->okConstFactor;
3331 
3332   assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3333   pLeft = pExpr->pLeft;
3334   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3335   zAff = exprINAffinity(pParse, pExpr);
3336   nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3337   aiMap = (int*)sqlite3DbMallocZero(
3338       pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3339   );
3340   if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3341 
3342   /* Attempt to compute the RHS. After this step, if anything other than
3343   ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3344   ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3345   ** the RHS has not yet been coded.  */
3346   v = pParse->pVdbe;
3347   assert( v!=0 );       /* OOM detected prior to this routine */
3348   VdbeNoopComment((v, "begin IN expr"));
3349   eType = sqlite3FindInIndex(pParse, pExpr,
3350                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3351                              destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3352                              aiMap, &iTab);
3353 
3354   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3355        || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3356   );
3357 #ifdef SQLITE_DEBUG
3358   /* Confirm that aiMap[] contains nVector integer values between 0 and
3359   ** nVector-1. */
3360   for(i=0; i<nVector; i++){
3361     int j, cnt;
3362     for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3363     assert( cnt==1 );
3364   }
3365 #endif
3366 
3367   /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3368   ** vector, then it is stored in an array of nVector registers starting
3369   ** at r1.
3370   **
3371   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3372   ** so that the fields are in the same order as an existing index.   The
3373   ** aiMap[] array contains a mapping from the original LHS field order to
3374   ** the field order that matches the RHS index.
3375   **
3376   ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3377   ** even if it is constant, as OP_Affinity may be used on the register
3378   ** by code generated below.  */
3379   assert( pParse->okConstFactor==okConstFactor );
3380   pParse->okConstFactor = 0;
3381   rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3382   pParse->okConstFactor = okConstFactor;
3383   for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3384   if( i==nVector ){
3385     /* LHS fields are not reordered */
3386     rLhs = rLhsOrig;
3387   }else{
3388     /* Need to reorder the LHS fields according to aiMap */
3389     rLhs = sqlite3GetTempRange(pParse, nVector);
3390     for(i=0; i<nVector; i++){
3391       sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3392     }
3393   }
3394 
3395   /* If sqlite3FindInIndex() did not find or create an index that is
3396   ** suitable for evaluating the IN operator, then evaluate using a
3397   ** sequence of comparisons.
3398   **
3399   ** This is step (1) in the in-operator.md optimized algorithm.
3400   */
3401   if( eType==IN_INDEX_NOOP ){
3402     ExprList *pList = pExpr->x.pList;
3403     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3404     int labelOk = sqlite3VdbeMakeLabel(pParse);
3405     int r2, regToFree;
3406     int regCkNull = 0;
3407     int ii;
3408     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3409     if( destIfNull!=destIfFalse ){
3410       regCkNull = sqlite3GetTempReg(pParse);
3411       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3412     }
3413     for(ii=0; ii<pList->nExpr; ii++){
3414       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3415       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3416         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3417       }
3418       sqlite3ReleaseTempReg(pParse, regToFree);
3419       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3420         int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3421         sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3422                           (void*)pColl, P4_COLLSEQ);
3423         VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3424         VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3425         VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3426         VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3427         sqlite3VdbeChangeP5(v, zAff[0]);
3428       }else{
3429         int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3430         assert( destIfNull==destIfFalse );
3431         sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3432                           (void*)pColl, P4_COLLSEQ);
3433         VdbeCoverageIf(v, op==OP_Ne);
3434         VdbeCoverageIf(v, op==OP_IsNull);
3435         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3436       }
3437     }
3438     if( regCkNull ){
3439       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3440       sqlite3VdbeGoto(v, destIfFalse);
3441     }
3442     sqlite3VdbeResolveLabel(v, labelOk);
3443     sqlite3ReleaseTempReg(pParse, regCkNull);
3444     goto sqlite3ExprCodeIN_finished;
3445   }
3446 
3447   /* Step 2: Check to see if the LHS contains any NULL columns.  If the
3448   ** LHS does contain NULLs then the result must be either FALSE or NULL.
3449   ** We will then skip the binary search of the RHS.
3450   */
3451   if( destIfNull==destIfFalse ){
3452     destStep2 = destIfFalse;
3453   }else{
3454     destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3455   }
3456   if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
3457   for(i=0; i<nVector; i++){
3458     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3459     if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3460     if( sqlite3ExprCanBeNull(p) ){
3461       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3462       VdbeCoverage(v);
3463     }
3464   }
3465 
3466   /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
3467   ** of the RHS using the LHS as a probe.  If found, the result is
3468   ** true.
3469   */
3470   if( eType==IN_INDEX_ROWID ){
3471     /* In this case, the RHS is the ROWID of table b-tree and so we also
3472     ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
3473     ** into a single opcode. */
3474     sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3475     VdbeCoverage(v);
3476     addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
3477   }else{
3478     sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3479     if( destIfFalse==destIfNull ){
3480       /* Combine Step 3 and Step 5 into a single opcode */
3481       sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3482                            rLhs, nVector); VdbeCoverage(v);
3483       goto sqlite3ExprCodeIN_finished;
3484     }
3485     /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3486     addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3487                                       rLhs, nVector); VdbeCoverage(v);
3488   }
3489 
3490   /* Step 4.  If the RHS is known to be non-NULL and we did not find
3491   ** an match on the search above, then the result must be FALSE.
3492   */
3493   if( rRhsHasNull && nVector==1 ){
3494     sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3495     VdbeCoverage(v);
3496   }
3497 
3498   /* Step 5.  If we do not care about the difference between NULL and
3499   ** FALSE, then just return false.
3500   */
3501   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3502 
3503   /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
3504   ** If any comparison is NULL, then the result is NULL.  If all
3505   ** comparisons are FALSE then the final result is FALSE.
3506   **
3507   ** For a scalar LHS, it is sufficient to check just the first row
3508   ** of the RHS.
3509   */
3510   if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3511   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3512   VdbeCoverage(v);
3513   if( nVector>1 ){
3514     destNotNull = sqlite3VdbeMakeLabel(pParse);
3515   }else{
3516     /* For nVector==1, combine steps 6 and 7 by immediately returning
3517     ** FALSE if the first comparison is not NULL */
3518     destNotNull = destIfFalse;
3519   }
3520   for(i=0; i<nVector; i++){
3521     Expr *p;
3522     CollSeq *pColl;
3523     int r3 = sqlite3GetTempReg(pParse);
3524     p = sqlite3VectorFieldSubexpr(pLeft, i);
3525     pColl = sqlite3ExprCollSeq(pParse, p);
3526     sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3527     sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3528                       (void*)pColl, P4_COLLSEQ);
3529     VdbeCoverage(v);
3530     sqlite3ReleaseTempReg(pParse, r3);
3531   }
3532   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3533   if( nVector>1 ){
3534     sqlite3VdbeResolveLabel(v, destNotNull);
3535     sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3536     VdbeCoverage(v);
3537 
3538     /* Step 7:  If we reach this point, we know that the result must
3539     ** be false. */
3540     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3541   }
3542 
3543   /* Jumps here in order to return true. */
3544   sqlite3VdbeJumpHere(v, addrTruthOp);
3545 
3546 sqlite3ExprCodeIN_finished:
3547   if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3548   VdbeComment((v, "end IN expr"));
3549 sqlite3ExprCodeIN_oom_error:
3550   sqlite3DbFree(pParse->db, aiMap);
3551   sqlite3DbFree(pParse->db, zAff);
3552 }
3553 #endif /* SQLITE_OMIT_SUBQUERY */
3554 
3555 #ifndef SQLITE_OMIT_FLOATING_POINT
3556 /*
3557 ** Generate an instruction that will put the floating point
3558 ** value described by z[0..n-1] into register iMem.
3559 **
3560 ** The z[] string will probably not be zero-terminated.  But the
3561 ** z[n] character is guaranteed to be something that does not look
3562 ** like the continuation of the number.
3563 */
3564 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3565   if( ALWAYS(z!=0) ){
3566     double value;
3567     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3568     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3569     if( negateFlag ) value = -value;
3570     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3571   }
3572 }
3573 #endif
3574 
3575 
3576 /*
3577 ** Generate an instruction that will put the integer describe by
3578 ** text z[0..n-1] into register iMem.
3579 **
3580 ** Expr.u.zToken is always UTF8 and zero-terminated.
3581 */
3582 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3583   Vdbe *v = pParse->pVdbe;
3584   if( pExpr->flags & EP_IntValue ){
3585     int i = pExpr->u.iValue;
3586     assert( i>=0 );
3587     if( negFlag ) i = -i;
3588     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3589   }else{
3590     int c;
3591     i64 value;
3592     const char *z = pExpr->u.zToken;
3593     assert( z!=0 );
3594     c = sqlite3DecOrHexToI64(z, &value);
3595     if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3596 #ifdef SQLITE_OMIT_FLOATING_POINT
3597       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3598 #else
3599 #ifndef SQLITE_OMIT_HEX_INTEGER
3600       if( sqlite3_strnicmp(z,"0x",2)==0 ){
3601         sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
3602       }else
3603 #endif
3604       {
3605         codeReal(v, z, negFlag, iMem);
3606       }
3607 #endif
3608     }else{
3609       if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3610       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3611     }
3612   }
3613 }
3614 
3615 
3616 /* Generate code that will load into register regOut a value that is
3617 ** appropriate for the iIdxCol-th column of index pIdx.
3618 */
3619 void sqlite3ExprCodeLoadIndexColumn(
3620   Parse *pParse,  /* The parsing context */
3621   Index *pIdx,    /* The index whose column is to be loaded */
3622   int iTabCur,    /* Cursor pointing to a table row */
3623   int iIdxCol,    /* The column of the index to be loaded */
3624   int regOut      /* Store the index column value in this register */
3625 ){
3626   i16 iTabCol = pIdx->aiColumn[iIdxCol];
3627   if( iTabCol==XN_EXPR ){
3628     assert( pIdx->aColExpr );
3629     assert( pIdx->aColExpr->nExpr>iIdxCol );
3630     pParse->iSelfTab = iTabCur + 1;
3631     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3632     pParse->iSelfTab = 0;
3633   }else{
3634     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3635                                     iTabCol, regOut);
3636   }
3637 }
3638 
3639 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3640 /*
3641 ** Generate code that will compute the value of generated column pCol
3642 ** and store the result in register regOut
3643 */
3644 void sqlite3ExprCodeGeneratedColumn(
3645   Parse *pParse,
3646   Column *pCol,
3647   int regOut
3648 ){
3649   int iAddr;
3650   Vdbe *v = pParse->pVdbe;
3651   assert( v!=0 );
3652   assert( pParse->iSelfTab!=0 );
3653   if( pParse->iSelfTab>0 ){
3654     iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
3655   }else{
3656     iAddr = 0;
3657   }
3658   sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
3659   if( pCol->affinity>=SQLITE_AFF_TEXT ){
3660     sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
3661   }
3662   if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
3663 }
3664 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3665 
3666 /*
3667 ** Generate code to extract the value of the iCol-th column of a table.
3668 */
3669 void sqlite3ExprCodeGetColumnOfTable(
3670   Vdbe *v,        /* Parsing context */
3671   Table *pTab,    /* The table containing the value */
3672   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
3673   int iCol,       /* Index of the column to extract */
3674   int regOut      /* Extract the value into this register */
3675 ){
3676   Column *pCol;
3677   assert( v!=0 );
3678   if( pTab==0 ){
3679     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3680     return;
3681   }
3682   if( iCol<0 || iCol==pTab->iPKey ){
3683     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3684   }else{
3685     int op;
3686     int x;
3687     if( IsVirtual(pTab) ){
3688       op = OP_VColumn;
3689       x = iCol;
3690 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3691     }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
3692       Parse *pParse = sqlite3VdbeParser(v);
3693       if( pCol->colFlags & COLFLAG_BUSY ){
3694         sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
3695       }else{
3696         int savedSelfTab = pParse->iSelfTab;
3697         pCol->colFlags |= COLFLAG_BUSY;
3698         pParse->iSelfTab = iTabCur+1;
3699         sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
3700         pParse->iSelfTab = savedSelfTab;
3701         pCol->colFlags &= ~COLFLAG_BUSY;
3702       }
3703       return;
3704 #endif
3705     }else if( !HasRowid(pTab) ){
3706       testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
3707       x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3708       op = OP_Column;
3709     }else{
3710       x = sqlite3TableColumnToStorage(pTab,iCol);
3711       testcase( x!=iCol );
3712       op = OP_Column;
3713     }
3714     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3715     sqlite3ColumnDefault(v, pTab, iCol, regOut);
3716   }
3717 }
3718 
3719 /*
3720 ** Generate code that will extract the iColumn-th column from
3721 ** table pTab and store the column value in register iReg.
3722 **
3723 ** There must be an open cursor to pTab in iTable when this routine
3724 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
3725 */
3726 int sqlite3ExprCodeGetColumn(
3727   Parse *pParse,   /* Parsing and code generating context */
3728   Table *pTab,     /* Description of the table we are reading from */
3729   int iColumn,     /* Index of the table column */
3730   int iTable,      /* The cursor pointing to the table */
3731   int iReg,        /* Store results here */
3732   u8 p5            /* P5 value for OP_Column + FLAGS */
3733 ){
3734   assert( pParse->pVdbe!=0 );
3735   sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
3736   if( p5 ){
3737     VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
3738     if( pOp->opcode==OP_Column ) pOp->p5 = p5;
3739   }
3740   return iReg;
3741 }
3742 
3743 /*
3744 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3745 ** over to iTo..iTo+nReg-1.
3746 */
3747 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3748   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3749 }
3750 
3751 /*
3752 ** Convert a scalar expression node to a TK_REGISTER referencing
3753 ** register iReg.  The caller must ensure that iReg already contains
3754 ** the correct value for the expression.
3755 */
3756 static void exprToRegister(Expr *pExpr, int iReg){
3757   Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
3758   if( NEVER(p==0) ) return;
3759   p->op2 = p->op;
3760   p->op = TK_REGISTER;
3761   p->iTable = iReg;
3762   ExprClearProperty(p, EP_Skip);
3763 }
3764 
3765 /*
3766 ** Evaluate an expression (either a vector or a scalar expression) and store
3767 ** the result in continguous temporary registers.  Return the index of
3768 ** the first register used to store the result.
3769 **
3770 ** If the returned result register is a temporary scalar, then also write
3771 ** that register number into *piFreeable.  If the returned result register
3772 ** is not a temporary or if the expression is a vector set *piFreeable
3773 ** to 0.
3774 */
3775 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3776   int iResult;
3777   int nResult = sqlite3ExprVectorSize(p);
3778   if( nResult==1 ){
3779     iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3780   }else{
3781     *piFreeable = 0;
3782     if( p->op==TK_SELECT ){
3783 #if SQLITE_OMIT_SUBQUERY
3784       iResult = 0;
3785 #else
3786       iResult = sqlite3CodeSubselect(pParse, p);
3787 #endif
3788     }else{
3789       int i;
3790       iResult = pParse->nMem+1;
3791       pParse->nMem += nResult;
3792       for(i=0; i<nResult; i++){
3793         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
3794       }
3795     }
3796   }
3797   return iResult;
3798 }
3799 
3800 /*
3801 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
3802 ** so that a subsequent copy will not be merged into this one.
3803 */
3804 static void setDoNotMergeFlagOnCopy(Vdbe *v){
3805   if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
3806     sqlite3VdbeChangeP5(v, 1);  /* Tag trailing OP_Copy as not mergable */
3807   }
3808 }
3809 
3810 /*
3811 ** Generate code to implement special SQL functions that are implemented
3812 ** in-line rather than by using the usual callbacks.
3813 */
3814 static int exprCodeInlineFunction(
3815   Parse *pParse,        /* Parsing context */
3816   ExprList *pFarg,      /* List of function arguments */
3817   int iFuncId,          /* Function ID.  One of the INTFUNC_... values */
3818   int target            /* Store function result in this register */
3819 ){
3820   int nFarg;
3821   Vdbe *v = pParse->pVdbe;
3822   assert( v!=0 );
3823   assert( pFarg!=0 );
3824   nFarg = pFarg->nExpr;
3825   assert( nFarg>0 );  /* All in-line functions have at least one argument */
3826   switch( iFuncId ){
3827     case INLINEFUNC_coalesce: {
3828       /* Attempt a direct implementation of the built-in COALESCE() and
3829       ** IFNULL() functions.  This avoids unnecessary evaluation of
3830       ** arguments past the first non-NULL argument.
3831       */
3832       int endCoalesce = sqlite3VdbeMakeLabel(pParse);
3833       int i;
3834       assert( nFarg>=2 );
3835       sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3836       for(i=1; i<nFarg; i++){
3837         sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3838         VdbeCoverage(v);
3839         sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3840       }
3841       setDoNotMergeFlagOnCopy(v);
3842       sqlite3VdbeResolveLabel(v, endCoalesce);
3843       break;
3844     }
3845     case INLINEFUNC_iif: {
3846       Expr caseExpr;
3847       memset(&caseExpr, 0, sizeof(caseExpr));
3848       caseExpr.op = TK_CASE;
3849       caseExpr.x.pList = pFarg;
3850       return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
3851     }
3852 
3853     default: {
3854       /* The UNLIKELY() function is a no-op.  The result is the value
3855       ** of the first argument.
3856       */
3857       assert( nFarg==1 || nFarg==2 );
3858       target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3859       break;
3860     }
3861 
3862   /***********************************************************************
3863   ** Test-only SQL functions that are only usable if enabled
3864   ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
3865   */
3866     case INLINEFUNC_expr_compare: {
3867       /* Compare two expressions using sqlite3ExprCompare() */
3868       assert( nFarg==2 );
3869       sqlite3VdbeAddOp2(v, OP_Integer,
3870          sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3871          target);
3872       break;
3873     }
3874 
3875     case INLINEFUNC_expr_implies_expr: {
3876       /* Compare two expressions using sqlite3ExprImpliesExpr() */
3877       assert( nFarg==2 );
3878       sqlite3VdbeAddOp2(v, OP_Integer,
3879          sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3880          target);
3881       break;
3882     }
3883 
3884     case INLINEFUNC_implies_nonnull_row: {
3885       /* REsult of sqlite3ExprImpliesNonNullRow() */
3886       Expr *pA1;
3887       assert( nFarg==2 );
3888       pA1 = pFarg->a[1].pExpr;
3889       if( pA1->op==TK_COLUMN ){
3890         sqlite3VdbeAddOp2(v, OP_Integer,
3891            sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
3892            target);
3893       }else{
3894         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3895       }
3896       break;
3897     }
3898 
3899 #ifdef SQLITE_DEBUG
3900     case INLINEFUNC_affinity: {
3901       /* The AFFINITY() function evaluates to a string that describes
3902       ** the type affinity of the argument.  This is used for testing of
3903       ** the SQLite type logic.
3904       */
3905       const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3906       char aff;
3907       assert( nFarg==1 );
3908       aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3909       sqlite3VdbeLoadString(v, target,
3910               (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
3911       break;
3912     }
3913 #endif
3914   }
3915   return target;
3916 }
3917 
3918 
3919 /*
3920 ** Generate code into the current Vdbe to evaluate the given
3921 ** expression.  Attempt to store the results in register "target".
3922 ** Return the register where results are stored.
3923 **
3924 ** With this routine, there is no guarantee that results will
3925 ** be stored in target.  The result might be stored in some other
3926 ** register if it is convenient to do so.  The calling function
3927 ** must check the return code and move the results to the desired
3928 ** register.
3929 */
3930 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
3931   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
3932   int op;                   /* The opcode being coded */
3933   int inReg = target;       /* Results stored in register inReg */
3934   int regFree1 = 0;         /* If non-zero free this temporary register */
3935   int regFree2 = 0;         /* If non-zero free this temporary register */
3936   int r1, r2;               /* Various register numbers */
3937   Expr tempX;               /* Temporary expression node */
3938   int p5 = 0;
3939 
3940   assert( target>0 && target<=pParse->nMem );
3941   assert( v!=0 );
3942 
3943 expr_code_doover:
3944   if( pExpr==0 ){
3945     op = TK_NULL;
3946   }else{
3947     assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3948     op = pExpr->op;
3949   }
3950   switch( op ){
3951     case TK_AGG_COLUMN: {
3952       AggInfo *pAggInfo = pExpr->pAggInfo;
3953       struct AggInfo_col *pCol;
3954       assert( pAggInfo!=0 );
3955       assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
3956       pCol = &pAggInfo->aCol[pExpr->iAgg];
3957       if( !pAggInfo->directMode ){
3958         assert( pCol->iMem>0 );
3959         return pCol->iMem;
3960       }else if( pAggInfo->useSortingIdx ){
3961         Table *pTab = pCol->pTab;
3962         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3963                               pCol->iSorterColumn, target);
3964         if( pCol->iColumn<0 ){
3965           VdbeComment((v,"%s.rowid",pTab->zName));
3966         }else{
3967           VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
3968           if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
3969             sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3970           }
3971         }
3972         return target;
3973       }
3974       /* Otherwise, fall thru into the TK_COLUMN case */
3975       /* no break */ deliberate_fall_through
3976     }
3977     case TK_COLUMN: {
3978       int iTab = pExpr->iTable;
3979       int iReg;
3980       if( ExprHasProperty(pExpr, EP_FixedCol) ){
3981         /* This COLUMN expression is really a constant due to WHERE clause
3982         ** constraints, and that constant is coded by the pExpr->pLeft
3983         ** expresssion.  However, make sure the constant has the correct
3984         ** datatype by applying the Affinity of the table column to the
3985         ** constant.
3986         */
3987         int aff;
3988         iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
3989         if( pExpr->y.pTab ){
3990           aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
3991         }else{
3992           aff = pExpr->affExpr;
3993         }
3994         if( aff>SQLITE_AFF_BLOB ){
3995           static const char zAff[] = "B\000C\000D\000E";
3996           assert( SQLITE_AFF_BLOB=='A' );
3997           assert( SQLITE_AFF_TEXT=='B' );
3998           sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3999                             &zAff[(aff-'B')*2], P4_STATIC);
4000         }
4001         return iReg;
4002       }
4003       if( iTab<0 ){
4004         if( pParse->iSelfTab<0 ){
4005           /* Other columns in the same row for CHECK constraints or
4006           ** generated columns or for inserting into partial index.
4007           ** The row is unpacked into registers beginning at
4008           ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register
4009           ** immediately prior to the first column.
4010           */
4011           Column *pCol;
4012           Table *pTab = pExpr->y.pTab;
4013           int iSrc;
4014           int iCol = pExpr->iColumn;
4015           assert( pTab!=0 );
4016           assert( iCol>=XN_ROWID );
4017           assert( iCol<pTab->nCol );
4018           if( iCol<0 ){
4019             return -1-pParse->iSelfTab;
4020           }
4021           pCol = pTab->aCol + iCol;
4022           testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4023           iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4024 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4025           if( pCol->colFlags & COLFLAG_GENERATED ){
4026             if( pCol->colFlags & COLFLAG_BUSY ){
4027               sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4028                               pCol->zName);
4029               return 0;
4030             }
4031             pCol->colFlags |= COLFLAG_BUSY;
4032             if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4033               sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
4034             }
4035             pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4036             return iSrc;
4037           }else
4038 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4039           if( pCol->affinity==SQLITE_AFF_REAL ){
4040             sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4041             sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4042             return target;
4043           }else{
4044             return iSrc;
4045           }
4046         }else{
4047           /* Coding an expression that is part of an index where column names
4048           ** in the index refer to the table to which the index belongs */
4049           iTab = pParse->iSelfTab - 1;
4050         }
4051       }
4052       iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4053                                pExpr->iColumn, iTab, target,
4054                                pExpr->op2);
4055       if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
4056         sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
4057       }
4058       return iReg;
4059     }
4060     case TK_INTEGER: {
4061       codeInteger(pParse, pExpr, 0, target);
4062       return target;
4063     }
4064     case TK_TRUEFALSE: {
4065       sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4066       return target;
4067     }
4068 #ifndef SQLITE_OMIT_FLOATING_POINT
4069     case TK_FLOAT: {
4070       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4071       codeReal(v, pExpr->u.zToken, 0, target);
4072       return target;
4073     }
4074 #endif
4075     case TK_STRING: {
4076       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4077       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4078       return target;
4079     }
4080     default: {
4081       /* Make NULL the default case so that if a bug causes an illegal
4082       ** Expr node to be passed into this function, it will be handled
4083       ** sanely and not crash.  But keep the assert() to bring the problem
4084       ** to the attention of the developers. */
4085       assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4086       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4087       return target;
4088     }
4089 #ifndef SQLITE_OMIT_BLOB_LITERAL
4090     case TK_BLOB: {
4091       int n;
4092       const char *z;
4093       char *zBlob;
4094       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4095       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4096       assert( pExpr->u.zToken[1]=='\'' );
4097       z = &pExpr->u.zToken[2];
4098       n = sqlite3Strlen30(z) - 1;
4099       assert( z[n]=='\'' );
4100       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4101       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4102       return target;
4103     }
4104 #endif
4105     case TK_VARIABLE: {
4106       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4107       assert( pExpr->u.zToken!=0 );
4108       assert( pExpr->u.zToken[0]!=0 );
4109       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4110       if( pExpr->u.zToken[1]!=0 ){
4111         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
4112         assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
4113         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
4114         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
4115       }
4116       return target;
4117     }
4118     case TK_REGISTER: {
4119       return pExpr->iTable;
4120     }
4121 #ifndef SQLITE_OMIT_CAST
4122     case TK_CAST: {
4123       /* Expressions of the form:   CAST(pLeft AS token) */
4124       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
4125       if( inReg!=target ){
4126         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
4127         inReg = target;
4128       }
4129       sqlite3VdbeAddOp2(v, OP_Cast, target,
4130                         sqlite3AffinityType(pExpr->u.zToken, 0));
4131       return inReg;
4132     }
4133 #endif /* SQLITE_OMIT_CAST */
4134     case TK_IS:
4135     case TK_ISNOT:
4136       op = (op==TK_IS) ? TK_EQ : TK_NE;
4137       p5 = SQLITE_NULLEQ;
4138       /* fall-through */
4139     case TK_LT:
4140     case TK_LE:
4141     case TK_GT:
4142     case TK_GE:
4143     case TK_NE:
4144     case TK_EQ: {
4145       Expr *pLeft = pExpr->pLeft;
4146       if( sqlite3ExprIsVector(pLeft) ){
4147         codeVectorCompare(pParse, pExpr, target, op, p5);
4148       }else{
4149         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4150         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4151         sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4152         codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4153             sqlite3VdbeCurrentAddr(v)+2, p5,
4154             ExprHasProperty(pExpr,EP_Commuted));
4155         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4156         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4157         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4158         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4159         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4160         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4161         if( p5==SQLITE_NULLEQ ){
4162           sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4163         }else{
4164           sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4165         }
4166         testcase( regFree1==0 );
4167         testcase( regFree2==0 );
4168       }
4169       break;
4170     }
4171     case TK_AND:
4172     case TK_OR:
4173     case TK_PLUS:
4174     case TK_STAR:
4175     case TK_MINUS:
4176     case TK_REM:
4177     case TK_BITAND:
4178     case TK_BITOR:
4179     case TK_SLASH:
4180     case TK_LSHIFT:
4181     case TK_RSHIFT:
4182     case TK_CONCAT: {
4183       assert( TK_AND==OP_And );            testcase( op==TK_AND );
4184       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
4185       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
4186       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
4187       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
4188       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
4189       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
4190       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
4191       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
4192       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
4193       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
4194       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4195       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4196       sqlite3VdbeAddOp3(v, op, r2, r1, target);
4197       testcase( regFree1==0 );
4198       testcase( regFree2==0 );
4199       break;
4200     }
4201     case TK_UMINUS: {
4202       Expr *pLeft = pExpr->pLeft;
4203       assert( pLeft );
4204       if( pLeft->op==TK_INTEGER ){
4205         codeInteger(pParse, pLeft, 1, target);
4206         return target;
4207 #ifndef SQLITE_OMIT_FLOATING_POINT
4208       }else if( pLeft->op==TK_FLOAT ){
4209         assert( !ExprHasProperty(pExpr, EP_IntValue) );
4210         codeReal(v, pLeft->u.zToken, 1, target);
4211         return target;
4212 #endif
4213       }else{
4214         tempX.op = TK_INTEGER;
4215         tempX.flags = EP_IntValue|EP_TokenOnly;
4216         tempX.u.iValue = 0;
4217         ExprClearVVAProperties(&tempX);
4218         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4219         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4220         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4221         testcase( regFree2==0 );
4222       }
4223       break;
4224     }
4225     case TK_BITNOT:
4226     case TK_NOT: {
4227       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
4228       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
4229       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4230       testcase( regFree1==0 );
4231       sqlite3VdbeAddOp2(v, op, r1, inReg);
4232       break;
4233     }
4234     case TK_TRUTH: {
4235       int isTrue;    /* IS TRUE or IS NOT TRUE */
4236       int bNormal;   /* IS TRUE or IS FALSE */
4237       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4238       testcase( regFree1==0 );
4239       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4240       bNormal = pExpr->op2==TK_IS;
4241       testcase( isTrue && bNormal);
4242       testcase( !isTrue && bNormal);
4243       sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4244       break;
4245     }
4246     case TK_ISNULL:
4247     case TK_NOTNULL: {
4248       int addr;
4249       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
4250       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4251       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4252       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4253       testcase( regFree1==0 );
4254       addr = sqlite3VdbeAddOp1(v, op, r1);
4255       VdbeCoverageIf(v, op==TK_ISNULL);
4256       VdbeCoverageIf(v, op==TK_NOTNULL);
4257       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4258       sqlite3VdbeJumpHere(v, addr);
4259       break;
4260     }
4261     case TK_AGG_FUNCTION: {
4262       AggInfo *pInfo = pExpr->pAggInfo;
4263       if( pInfo==0
4264        || NEVER(pExpr->iAgg<0)
4265        || NEVER(pExpr->iAgg>=pInfo->nFunc)
4266       ){
4267         assert( !ExprHasProperty(pExpr, EP_IntValue) );
4268         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
4269       }else{
4270         return pInfo->aFunc[pExpr->iAgg].iMem;
4271       }
4272       break;
4273     }
4274     case TK_FUNCTION: {
4275       ExprList *pFarg;       /* List of function arguments */
4276       int nFarg;             /* Number of function arguments */
4277       FuncDef *pDef;         /* The function definition object */
4278       const char *zId;       /* The function name */
4279       u32 constMask = 0;     /* Mask of function arguments that are constant */
4280       int i;                 /* Loop counter */
4281       sqlite3 *db = pParse->db;  /* The database connection */
4282       u8 enc = ENC(db);      /* The text encoding used by this database */
4283       CollSeq *pColl = 0;    /* A collating sequence */
4284 
4285 #ifndef SQLITE_OMIT_WINDOWFUNC
4286       if( ExprHasProperty(pExpr, EP_WinFunc) ){
4287         return pExpr->y.pWin->regResult;
4288       }
4289 #endif
4290 
4291       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4292         /* SQL functions can be expensive. So try to avoid running them
4293         ** multiple times if we know they always give the same result */
4294         return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4295       }
4296       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4297       assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4298       pFarg = pExpr->x.pList;
4299       nFarg = pFarg ? pFarg->nExpr : 0;
4300       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4301       zId = pExpr->u.zToken;
4302       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4303 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4304       if( pDef==0 && pParse->explain ){
4305         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4306       }
4307 #endif
4308       if( pDef==0 || pDef->xFinalize!=0 ){
4309         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
4310         break;
4311       }
4312       if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
4313         assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4314         assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4315         return exprCodeInlineFunction(pParse, pFarg,
4316              SQLITE_PTR_TO_INT(pDef->pUserData), target);
4317       }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4318         sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4319       }
4320 
4321       for(i=0; i<nFarg; i++){
4322         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4323           testcase( i==31 );
4324           constMask |= MASKBIT32(i);
4325         }
4326         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4327           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4328         }
4329       }
4330       if( pFarg ){
4331         if( constMask ){
4332           r1 = pParse->nMem+1;
4333           pParse->nMem += nFarg;
4334         }else{
4335           r1 = sqlite3GetTempRange(pParse, nFarg);
4336         }
4337 
4338         /* For length() and typeof() functions with a column argument,
4339         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4340         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
4341         ** loading.
4342         */
4343         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4344           u8 exprOp;
4345           assert( nFarg==1 );
4346           assert( pFarg->a[0].pExpr!=0 );
4347           exprOp = pFarg->a[0].pExpr->op;
4348           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4349             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4350             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4351             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
4352             pFarg->a[0].pExpr->op2 =
4353                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
4354           }
4355         }
4356 
4357         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
4358                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
4359       }else{
4360         r1 = 0;
4361       }
4362 #ifndef SQLITE_OMIT_VIRTUALTABLE
4363       /* Possibly overload the function if the first argument is
4364       ** a virtual table column.
4365       **
4366       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4367       ** second argument, not the first, as the argument to test to
4368       ** see if it is a column in a virtual table.  This is done because
4369       ** the left operand of infix functions (the operand we want to
4370       ** control overloading) ends up as the second argument to the
4371       ** function.  The expression "A glob B" is equivalent to
4372       ** "glob(B,A).  We want to use the A in "A glob B" to test
4373       ** for function overloading.  But we use the B term in "glob(B,A)".
4374       */
4375       if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4376         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4377       }else if( nFarg>0 ){
4378         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4379       }
4380 #endif
4381       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4382         if( !pColl ) pColl = db->pDfltColl;
4383         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4384       }
4385 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4386       if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
4387         Expr *pArg = pFarg->a[0].pExpr;
4388         if( pArg->op==TK_COLUMN ){
4389           sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4390         }else{
4391           sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4392         }
4393       }else
4394 #endif
4395       {
4396         sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4397                                    pDef, pExpr->op2);
4398       }
4399       if( nFarg ){
4400         if( constMask==0 ){
4401           sqlite3ReleaseTempRange(pParse, r1, nFarg);
4402         }else{
4403           sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4404         }
4405       }
4406       return target;
4407     }
4408 #ifndef SQLITE_OMIT_SUBQUERY
4409     case TK_EXISTS:
4410     case TK_SELECT: {
4411       int nCol;
4412       testcase( op==TK_EXISTS );
4413       testcase( op==TK_SELECT );
4414       if( pParse->db->mallocFailed ){
4415         return 0;
4416       }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
4417         sqlite3SubselectError(pParse, nCol, 1);
4418       }else{
4419         return sqlite3CodeSubselect(pParse, pExpr);
4420       }
4421       break;
4422     }
4423     case TK_SELECT_COLUMN: {
4424       int n;
4425       if( pExpr->pLeft->iTable==0 ){
4426         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
4427       }
4428       assert( pExpr->pLeft->op==TK_SELECT || pExpr->pLeft->op==TK_ERROR );
4429       n = sqlite3ExprVectorSize(pExpr->pLeft);
4430       if( pExpr->iTable!=n ){
4431         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4432                                 pExpr->iTable, n);
4433       }
4434       return pExpr->pLeft->iTable + pExpr->iColumn;
4435     }
4436     case TK_IN: {
4437       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4438       int destIfNull = sqlite3VdbeMakeLabel(pParse);
4439       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4440       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4441       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4442       sqlite3VdbeResolveLabel(v, destIfFalse);
4443       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4444       sqlite3VdbeResolveLabel(v, destIfNull);
4445       return target;
4446     }
4447 #endif /* SQLITE_OMIT_SUBQUERY */
4448 
4449 
4450     /*
4451     **    x BETWEEN y AND z
4452     **
4453     ** This is equivalent to
4454     **
4455     **    x>=y AND x<=z
4456     **
4457     ** X is stored in pExpr->pLeft.
4458     ** Y is stored in pExpr->pList->a[0].pExpr.
4459     ** Z is stored in pExpr->pList->a[1].pExpr.
4460     */
4461     case TK_BETWEEN: {
4462       exprCodeBetween(pParse, pExpr, target, 0, 0);
4463       return target;
4464     }
4465     case TK_SPAN:
4466     case TK_COLLATE:
4467     case TK_UPLUS: {
4468       pExpr = pExpr->pLeft;
4469       goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4470     }
4471 
4472     case TK_TRIGGER: {
4473       /* If the opcode is TK_TRIGGER, then the expression is a reference
4474       ** to a column in the new.* or old.* pseudo-tables available to
4475       ** trigger programs. In this case Expr.iTable is set to 1 for the
4476       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4477       ** is set to the column of the pseudo-table to read, or to -1 to
4478       ** read the rowid field.
4479       **
4480       ** The expression is implemented using an OP_Param opcode. The p1
4481       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4482       ** to reference another column of the old.* pseudo-table, where
4483       ** i is the index of the column. For a new.rowid reference, p1 is
4484       ** set to (n+1), where n is the number of columns in each pseudo-table.
4485       ** For a reference to any other column in the new.* pseudo-table, p1
4486       ** is set to (n+2+i), where n and i are as defined previously. For
4487       ** example, if the table on which triggers are being fired is
4488       ** declared as:
4489       **
4490       **   CREATE TABLE t1(a, b);
4491       **
4492       ** Then p1 is interpreted as follows:
4493       **
4494       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
4495       **   p1==1   ->    old.a         p1==4   ->    new.a
4496       **   p1==2   ->    old.b         p1==5   ->    new.b
4497       */
4498       Table *pTab = pExpr->y.pTab;
4499       int iCol = pExpr->iColumn;
4500       int p1 = pExpr->iTable * (pTab->nCol+1) + 1
4501                      + sqlite3TableColumnToStorage(pTab, iCol);
4502 
4503       assert( pExpr->iTable==0 || pExpr->iTable==1 );
4504       assert( iCol>=-1 && iCol<pTab->nCol );
4505       assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
4506       assert( p1>=0 && p1<(pTab->nCol*2+2) );
4507 
4508       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
4509       VdbeComment((v, "r[%d]=%s.%s", target,
4510         (pExpr->iTable ? "new" : "old"),
4511         (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
4512       ));
4513 
4514 #ifndef SQLITE_OMIT_FLOATING_POINT
4515       /* If the column has REAL affinity, it may currently be stored as an
4516       ** integer. Use OP_RealAffinity to make sure it is really real.
4517       **
4518       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4519       ** floating point when extracting it from the record.  */
4520       if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
4521         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4522       }
4523 #endif
4524       break;
4525     }
4526 
4527     case TK_VECTOR: {
4528       sqlite3ErrorMsg(pParse, "row value misused");
4529       break;
4530     }
4531 
4532     /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4533     ** that derive from the right-hand table of a LEFT JOIN.  The
4534     ** Expr.iTable value is the table number for the right-hand table.
4535     ** The expression is only evaluated if that table is not currently
4536     ** on a LEFT JOIN NULL row.
4537     */
4538     case TK_IF_NULL_ROW: {
4539       int addrINR;
4540       u8 okConstFactor = pParse->okConstFactor;
4541       addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
4542       /* Temporarily disable factoring of constant expressions, since
4543       ** even though expressions may appear to be constant, they are not
4544       ** really constant because they originate from the right-hand side
4545       ** of a LEFT JOIN. */
4546       pParse->okConstFactor = 0;
4547       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
4548       pParse->okConstFactor = okConstFactor;
4549       sqlite3VdbeJumpHere(v, addrINR);
4550       sqlite3VdbeChangeP3(v, addrINR, inReg);
4551       break;
4552     }
4553 
4554     /*
4555     ** Form A:
4556     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4557     **
4558     ** Form B:
4559     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4560     **
4561     ** Form A is can be transformed into the equivalent form B as follows:
4562     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4563     **        WHEN x=eN THEN rN ELSE y END
4564     **
4565     ** X (if it exists) is in pExpr->pLeft.
4566     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4567     ** odd.  The Y is also optional.  If the number of elements in x.pList
4568     ** is even, then Y is omitted and the "otherwise" result is NULL.
4569     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4570     **
4571     ** The result of the expression is the Ri for the first matching Ei,
4572     ** or if there is no matching Ei, the ELSE term Y, or if there is
4573     ** no ELSE term, NULL.
4574     */
4575     case TK_CASE: {
4576       int endLabel;                     /* GOTO label for end of CASE stmt */
4577       int nextCase;                     /* GOTO label for next WHEN clause */
4578       int nExpr;                        /* 2x number of WHEN terms */
4579       int i;                            /* Loop counter */
4580       ExprList *pEList;                 /* List of WHEN terms */
4581       struct ExprList_item *aListelem;  /* Array of WHEN terms */
4582       Expr opCompare;                   /* The X==Ei expression */
4583       Expr *pX;                         /* The X expression */
4584       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
4585       Expr *pDel = 0;
4586       sqlite3 *db = pParse->db;
4587 
4588       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
4589       assert(pExpr->x.pList->nExpr > 0);
4590       pEList = pExpr->x.pList;
4591       aListelem = pEList->a;
4592       nExpr = pEList->nExpr;
4593       endLabel = sqlite3VdbeMakeLabel(pParse);
4594       if( (pX = pExpr->pLeft)!=0 ){
4595         pDel = sqlite3ExprDup(db, pX, 0);
4596         if( db->mallocFailed ){
4597           sqlite3ExprDelete(db, pDel);
4598           break;
4599         }
4600         testcase( pX->op==TK_COLUMN );
4601         exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4602         testcase( regFree1==0 );
4603         memset(&opCompare, 0, sizeof(opCompare));
4604         opCompare.op = TK_EQ;
4605         opCompare.pLeft = pDel;
4606         pTest = &opCompare;
4607         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4608         ** The value in regFree1 might get SCopy-ed into the file result.
4609         ** So make sure that the regFree1 register is not reused for other
4610         ** purposes and possibly overwritten.  */
4611         regFree1 = 0;
4612       }
4613       for(i=0; i<nExpr-1; i=i+2){
4614         if( pX ){
4615           assert( pTest!=0 );
4616           opCompare.pRight = aListelem[i].pExpr;
4617         }else{
4618           pTest = aListelem[i].pExpr;
4619         }
4620         nextCase = sqlite3VdbeMakeLabel(pParse);
4621         testcase( pTest->op==TK_COLUMN );
4622         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4623         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4624         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4625         sqlite3VdbeGoto(v, endLabel);
4626         sqlite3VdbeResolveLabel(v, nextCase);
4627       }
4628       if( (nExpr&1)!=0 ){
4629         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4630       }else{
4631         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4632       }
4633       sqlite3ExprDelete(db, pDel);
4634       setDoNotMergeFlagOnCopy(v);
4635       sqlite3VdbeResolveLabel(v, endLabel);
4636       break;
4637     }
4638 #ifndef SQLITE_OMIT_TRIGGER
4639     case TK_RAISE: {
4640       assert( pExpr->affExpr==OE_Rollback
4641            || pExpr->affExpr==OE_Abort
4642            || pExpr->affExpr==OE_Fail
4643            || pExpr->affExpr==OE_Ignore
4644       );
4645       if( !pParse->pTriggerTab && !pParse->nested ){
4646         sqlite3ErrorMsg(pParse,
4647                        "RAISE() may only be used within a trigger-program");
4648         return 0;
4649       }
4650       if( pExpr->affExpr==OE_Abort ){
4651         sqlite3MayAbort(pParse);
4652       }
4653       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4654       if( pExpr->affExpr==OE_Ignore ){
4655         sqlite3VdbeAddOp4(
4656             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
4657         VdbeCoverage(v);
4658       }else{
4659         sqlite3HaltConstraint(pParse,
4660              pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
4661              pExpr->affExpr, pExpr->u.zToken, 0, 0);
4662       }
4663 
4664       break;
4665     }
4666 #endif
4667   }
4668   sqlite3ReleaseTempReg(pParse, regFree1);
4669   sqlite3ReleaseTempReg(pParse, regFree2);
4670   return inReg;
4671 }
4672 
4673 /*
4674 ** Generate code that will evaluate expression pExpr just one time
4675 ** per prepared statement execution.
4676 **
4677 ** If the expression uses functions (that might throw an exception) then
4678 ** guard them with an OP_Once opcode to ensure that the code is only executed
4679 ** once. If no functions are involved, then factor the code out and put it at
4680 ** the end of the prepared statement in the initialization section.
4681 **
4682 ** If regDest>=0 then the result is always stored in that register and the
4683 ** result is not reusable.  If regDest<0 then this routine is free to
4684 ** store the value whereever it wants.  The register where the expression
4685 ** is stored is returned.  When regDest<0, two identical expressions might
4686 ** code to the same register, if they do not contain function calls and hence
4687 ** are factored out into the initialization section at the end of the
4688 ** prepared statement.
4689 */
4690 int sqlite3ExprCodeRunJustOnce(
4691   Parse *pParse,    /* Parsing context */
4692   Expr *pExpr,      /* The expression to code when the VDBE initializes */
4693   int regDest       /* Store the value in this register */
4694 ){
4695   ExprList *p;
4696   assert( ConstFactorOk(pParse) );
4697   p = pParse->pConstExpr;
4698   if( regDest<0 && p ){
4699     struct ExprList_item *pItem;
4700     int i;
4701     for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
4702       if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
4703         return pItem->u.iConstExprReg;
4704       }
4705     }
4706   }
4707   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4708   if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
4709     Vdbe *v = pParse->pVdbe;
4710     int addr;
4711     assert( v );
4712     addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
4713     pParse->okConstFactor = 0;
4714     if( !pParse->db->mallocFailed ){
4715       if( regDest<0 ) regDest = ++pParse->nMem;
4716       sqlite3ExprCode(pParse, pExpr, regDest);
4717     }
4718     pParse->okConstFactor = 1;
4719     sqlite3ExprDelete(pParse->db, pExpr);
4720     sqlite3VdbeJumpHere(v, addr);
4721   }else{
4722     p = sqlite3ExprListAppend(pParse, p, pExpr);
4723     if( p ){
4724        struct ExprList_item *pItem = &p->a[p->nExpr-1];
4725        pItem->reusable = regDest<0;
4726        if( regDest<0 ) regDest = ++pParse->nMem;
4727        pItem->u.iConstExprReg = regDest;
4728     }
4729     pParse->pConstExpr = p;
4730   }
4731   return regDest;
4732 }
4733 
4734 /*
4735 ** Generate code to evaluate an expression and store the results
4736 ** into a register.  Return the register number where the results
4737 ** are stored.
4738 **
4739 ** If the register is a temporary register that can be deallocated,
4740 ** then write its number into *pReg.  If the result register is not
4741 ** a temporary, then set *pReg to zero.
4742 **
4743 ** If pExpr is a constant, then this routine might generate this
4744 ** code to fill the register in the initialization section of the
4745 ** VDBE program, in order to factor it out of the evaluation loop.
4746 */
4747 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4748   int r2;
4749   pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
4750   if( ConstFactorOk(pParse)
4751    && ALWAYS(pExpr!=0)
4752    && pExpr->op!=TK_REGISTER
4753    && sqlite3ExprIsConstantNotJoin(pExpr)
4754   ){
4755     *pReg  = 0;
4756     r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4757   }else{
4758     int r1 = sqlite3GetTempReg(pParse);
4759     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4760     if( r2==r1 ){
4761       *pReg = r1;
4762     }else{
4763       sqlite3ReleaseTempReg(pParse, r1);
4764       *pReg = 0;
4765     }
4766   }
4767   return r2;
4768 }
4769 
4770 /*
4771 ** Generate code that will evaluate expression pExpr and store the
4772 ** results in register target.  The results are guaranteed to appear
4773 ** in register target.
4774 */
4775 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
4776   int inReg;
4777 
4778   assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
4779   assert( target>0 && target<=pParse->nMem );
4780   assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
4781   if( pParse->pVdbe==0 ) return;
4782   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
4783   if( inReg!=target ){
4784     u8 op;
4785     if( ExprHasProperty(pExpr,EP_Subquery) ){
4786       op = OP_Copy;
4787     }else{
4788       op = OP_SCopy;
4789     }
4790     sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
4791   }
4792 }
4793 
4794 /*
4795 ** Make a transient copy of expression pExpr and then code it using
4796 ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
4797 ** except that the input expression is guaranteed to be unchanged.
4798 */
4799 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4800   sqlite3 *db = pParse->db;
4801   pExpr = sqlite3ExprDup(db, pExpr, 0);
4802   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4803   sqlite3ExprDelete(db, pExpr);
4804 }
4805 
4806 /*
4807 ** Generate code that will evaluate expression pExpr and store the
4808 ** results in register target.  The results are guaranteed to appear
4809 ** in register target.  If the expression is constant, then this routine
4810 ** might choose to code the expression at initialization time.
4811 */
4812 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4813   if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
4814     sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
4815   }else{
4816     sqlite3ExprCodeCopy(pParse, pExpr, target);
4817   }
4818 }
4819 
4820 /*
4821 ** Generate code that pushes the value of every element of the given
4822 ** expression list into a sequence of registers beginning at target.
4823 **
4824 ** Return the number of elements evaluated.  The number returned will
4825 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
4826 ** is defined.
4827 **
4828 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4829 ** filled using OP_SCopy.  OP_Copy must be used instead.
4830 **
4831 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4832 ** factored out into initialization code.
4833 **
4834 ** The SQLITE_ECEL_REF flag means that expressions in the list with
4835 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4836 ** in registers at srcReg, and so the value can be copied from there.
4837 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
4838 ** are simply omitted rather than being copied from srcReg.
4839 */
4840 int sqlite3ExprCodeExprList(
4841   Parse *pParse,     /* Parsing context */
4842   ExprList *pList,   /* The expression list to be coded */
4843   int target,        /* Where to write results */
4844   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
4845   u8 flags           /* SQLITE_ECEL_* flags */
4846 ){
4847   struct ExprList_item *pItem;
4848   int i, j, n;
4849   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
4850   Vdbe *v = pParse->pVdbe;
4851   assert( pList!=0 );
4852   assert( target>0 );
4853   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
4854   n = pList->nExpr;
4855   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4856   for(pItem=pList->a, i=0; i<n; i++, pItem++){
4857     Expr *pExpr = pItem->pExpr;
4858 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
4859     if( pItem->bSorterRef ){
4860       i--;
4861       n--;
4862     }else
4863 #endif
4864     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4865       if( flags & SQLITE_ECEL_OMITREF ){
4866         i--;
4867         n--;
4868       }else{
4869         sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4870       }
4871     }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4872            && sqlite3ExprIsConstantNotJoin(pExpr)
4873     ){
4874       sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
4875     }else{
4876       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4877       if( inReg!=target+i ){
4878         VdbeOp *pOp;
4879         if( copyOp==OP_Copy
4880          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4881          && pOp->p1+pOp->p3+1==inReg
4882          && pOp->p2+pOp->p3+1==target+i
4883          && pOp->p5==0  /* The do-not-merge flag must be clear */
4884         ){
4885           pOp->p3++;
4886         }else{
4887           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4888         }
4889       }
4890     }
4891   }
4892   return n;
4893 }
4894 
4895 /*
4896 ** Generate code for a BETWEEN operator.
4897 **
4898 **    x BETWEEN y AND z
4899 **
4900 ** The above is equivalent to
4901 **
4902 **    x>=y AND x<=z
4903 **
4904 ** Code it as such, taking care to do the common subexpression
4905 ** elimination of x.
4906 **
4907 ** The xJumpIf parameter determines details:
4908 **
4909 **    NULL:                   Store the boolean result in reg[dest]
4910 **    sqlite3ExprIfTrue:      Jump to dest if true
4911 **    sqlite3ExprIfFalse:     Jump to dest if false
4912 **
4913 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
4914 */
4915 static void exprCodeBetween(
4916   Parse *pParse,    /* Parsing and code generating context */
4917   Expr *pExpr,      /* The BETWEEN expression */
4918   int dest,         /* Jump destination or storage location */
4919   void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
4920   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
4921 ){
4922   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
4923   Expr compLeft;    /* The  x>=y  term */
4924   Expr compRight;   /* The  x<=z  term */
4925   int regFree1 = 0; /* Temporary use register */
4926   Expr *pDel = 0;
4927   sqlite3 *db = pParse->db;
4928 
4929   memset(&compLeft, 0, sizeof(Expr));
4930   memset(&compRight, 0, sizeof(Expr));
4931   memset(&exprAnd, 0, sizeof(Expr));
4932 
4933   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4934   pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
4935   if( db->mallocFailed==0 ){
4936     exprAnd.op = TK_AND;
4937     exprAnd.pLeft = &compLeft;
4938     exprAnd.pRight = &compRight;
4939     compLeft.op = TK_GE;
4940     compLeft.pLeft = pDel;
4941     compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4942     compRight.op = TK_LE;
4943     compRight.pLeft = pDel;
4944     compRight.pRight = pExpr->x.pList->a[1].pExpr;
4945     exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4946     if( xJump ){
4947       xJump(pParse, &exprAnd, dest, jumpIfNull);
4948     }else{
4949       /* Mark the expression is being from the ON or USING clause of a join
4950       ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4951       ** it into the Parse.pConstExpr list.  We should use a new bit for this,
4952       ** for clarity, but we are out of bits in the Expr.flags field so we
4953       ** have to reuse the EP_FromJoin bit.  Bummer. */
4954       pDel->flags |= EP_FromJoin;
4955       sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
4956     }
4957     sqlite3ReleaseTempReg(pParse, regFree1);
4958   }
4959   sqlite3ExprDelete(db, pDel);
4960 
4961   /* Ensure adequate test coverage */
4962   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
4963   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
4964   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
4965   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
4966   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4967   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4968   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4969   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
4970   testcase( xJump==0 );
4971 }
4972 
4973 /*
4974 ** Generate code for a boolean expression such that a jump is made
4975 ** to the label "dest" if the expression is true but execution
4976 ** continues straight thru if the expression is false.
4977 **
4978 ** If the expression evaluates to NULL (neither true nor false), then
4979 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4980 **
4981 ** This code depends on the fact that certain token values (ex: TK_EQ)
4982 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4983 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
4984 ** the make process cause these values to align.  Assert()s in the code
4985 ** below verify that the numbers are aligned correctly.
4986 */
4987 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4988   Vdbe *v = pParse->pVdbe;
4989   int op = 0;
4990   int regFree1 = 0;
4991   int regFree2 = 0;
4992   int r1, r2;
4993 
4994   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4995   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
4996   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
4997   assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
4998   op = pExpr->op;
4999   switch( op ){
5000     case TK_AND:
5001     case TK_OR: {
5002       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5003       if( pAlt!=pExpr ){
5004         sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5005       }else if( op==TK_AND ){
5006         int d2 = sqlite3VdbeMakeLabel(pParse);
5007         testcase( jumpIfNull==0 );
5008         sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5009                            jumpIfNull^SQLITE_JUMPIFNULL);
5010         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5011         sqlite3VdbeResolveLabel(v, d2);
5012       }else{
5013         testcase( jumpIfNull==0 );
5014         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5015         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5016       }
5017       break;
5018     }
5019     case TK_NOT: {
5020       testcase( jumpIfNull==0 );
5021       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5022       break;
5023     }
5024     case TK_TRUTH: {
5025       int isNot;      /* IS NOT TRUE or IS NOT FALSE */
5026       int isTrue;     /* IS TRUE or IS NOT TRUE */
5027       testcase( jumpIfNull==0 );
5028       isNot = pExpr->op2==TK_ISNOT;
5029       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5030       testcase( isTrue && isNot );
5031       testcase( !isTrue && isNot );
5032       if( isTrue ^ isNot ){
5033         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5034                           isNot ? SQLITE_JUMPIFNULL : 0);
5035       }else{
5036         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5037                            isNot ? SQLITE_JUMPIFNULL : 0);
5038       }
5039       break;
5040     }
5041     case TK_IS:
5042     case TK_ISNOT:
5043       testcase( op==TK_IS );
5044       testcase( op==TK_ISNOT );
5045       op = (op==TK_IS) ? TK_EQ : TK_NE;
5046       jumpIfNull = SQLITE_NULLEQ;
5047       /* no break */ deliberate_fall_through
5048     case TK_LT:
5049     case TK_LE:
5050     case TK_GT:
5051     case TK_GE:
5052     case TK_NE:
5053     case TK_EQ: {
5054       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5055       testcase( jumpIfNull==0 );
5056       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5057       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5058       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5059                   r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5060       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5061       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5062       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5063       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5064       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5065       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5066       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5067       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5068       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5069       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5070       testcase( regFree1==0 );
5071       testcase( regFree2==0 );
5072       break;
5073     }
5074     case TK_ISNULL:
5075     case TK_NOTNULL: {
5076       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
5077       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5078       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5079       sqlite3VdbeAddOp2(v, op, r1, dest);
5080       VdbeCoverageIf(v, op==TK_ISNULL);
5081       VdbeCoverageIf(v, op==TK_NOTNULL);
5082       testcase( regFree1==0 );
5083       break;
5084     }
5085     case TK_BETWEEN: {
5086       testcase( jumpIfNull==0 );
5087       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5088       break;
5089     }
5090 #ifndef SQLITE_OMIT_SUBQUERY
5091     case TK_IN: {
5092       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5093       int destIfNull = jumpIfNull ? dest : destIfFalse;
5094       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5095       sqlite3VdbeGoto(v, dest);
5096       sqlite3VdbeResolveLabel(v, destIfFalse);
5097       break;
5098     }
5099 #endif
5100     default: {
5101     default_expr:
5102       if( ExprAlwaysTrue(pExpr) ){
5103         sqlite3VdbeGoto(v, dest);
5104       }else if( ExprAlwaysFalse(pExpr) ){
5105         /* No-op */
5106       }else{
5107         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5108         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5109         VdbeCoverage(v);
5110         testcase( regFree1==0 );
5111         testcase( jumpIfNull==0 );
5112       }
5113       break;
5114     }
5115   }
5116   sqlite3ReleaseTempReg(pParse, regFree1);
5117   sqlite3ReleaseTempReg(pParse, regFree2);
5118 }
5119 
5120 /*
5121 ** Generate code for a boolean expression such that a jump is made
5122 ** to the label "dest" if the expression is false but execution
5123 ** continues straight thru if the expression is true.
5124 **
5125 ** If the expression evaluates to NULL (neither true nor false) then
5126 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5127 ** is 0.
5128 */
5129 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5130   Vdbe *v = pParse->pVdbe;
5131   int op = 0;
5132   int regFree1 = 0;
5133   int regFree2 = 0;
5134   int r1, r2;
5135 
5136   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5137   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5138   if( pExpr==0 )    return;
5139   assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
5140 
5141   /* The value of pExpr->op and op are related as follows:
5142   **
5143   **       pExpr->op            op
5144   **       ---------          ----------
5145   **       TK_ISNULL          OP_NotNull
5146   **       TK_NOTNULL         OP_IsNull
5147   **       TK_NE              OP_Eq
5148   **       TK_EQ              OP_Ne
5149   **       TK_GT              OP_Le
5150   **       TK_LE              OP_Gt
5151   **       TK_GE              OP_Lt
5152   **       TK_LT              OP_Ge
5153   **
5154   ** For other values of pExpr->op, op is undefined and unused.
5155   ** The value of TK_ and OP_ constants are arranged such that we
5156   ** can compute the mapping above using the following expression.
5157   ** Assert()s verify that the computation is correct.
5158   */
5159   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5160 
5161   /* Verify correct alignment of TK_ and OP_ constants
5162   */
5163   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5164   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5165   assert( pExpr->op!=TK_NE || op==OP_Eq );
5166   assert( pExpr->op!=TK_EQ || op==OP_Ne );
5167   assert( pExpr->op!=TK_LT || op==OP_Ge );
5168   assert( pExpr->op!=TK_LE || op==OP_Gt );
5169   assert( pExpr->op!=TK_GT || op==OP_Le );
5170   assert( pExpr->op!=TK_GE || op==OP_Lt );
5171 
5172   switch( pExpr->op ){
5173     case TK_AND:
5174     case TK_OR: {
5175       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5176       if( pAlt!=pExpr ){
5177         sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5178       }else if( pExpr->op==TK_AND ){
5179         testcase( jumpIfNull==0 );
5180         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5181         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5182       }else{
5183         int d2 = sqlite3VdbeMakeLabel(pParse);
5184         testcase( jumpIfNull==0 );
5185         sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5186                           jumpIfNull^SQLITE_JUMPIFNULL);
5187         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5188         sqlite3VdbeResolveLabel(v, d2);
5189       }
5190       break;
5191     }
5192     case TK_NOT: {
5193       testcase( jumpIfNull==0 );
5194       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5195       break;
5196     }
5197     case TK_TRUTH: {
5198       int isNot;   /* IS NOT TRUE or IS NOT FALSE */
5199       int isTrue;  /* IS TRUE or IS NOT TRUE */
5200       testcase( jumpIfNull==0 );
5201       isNot = pExpr->op2==TK_ISNOT;
5202       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5203       testcase( isTrue && isNot );
5204       testcase( !isTrue && isNot );
5205       if( isTrue ^ isNot ){
5206         /* IS TRUE and IS NOT FALSE */
5207         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5208                            isNot ? 0 : SQLITE_JUMPIFNULL);
5209 
5210       }else{
5211         /* IS FALSE and IS NOT TRUE */
5212         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5213                           isNot ? 0 : SQLITE_JUMPIFNULL);
5214       }
5215       break;
5216     }
5217     case TK_IS:
5218     case TK_ISNOT:
5219       testcase( pExpr->op==TK_IS );
5220       testcase( pExpr->op==TK_ISNOT );
5221       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5222       jumpIfNull = SQLITE_NULLEQ;
5223       /* no break */ deliberate_fall_through
5224     case TK_LT:
5225     case TK_LE:
5226     case TK_GT:
5227     case TK_GE:
5228     case TK_NE:
5229     case TK_EQ: {
5230       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5231       testcase( jumpIfNull==0 );
5232       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5233       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5234       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5235                   r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5236       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5237       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5238       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5239       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5240       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5241       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5242       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5243       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5244       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5245       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5246       testcase( regFree1==0 );
5247       testcase( regFree2==0 );
5248       break;
5249     }
5250     case TK_ISNULL:
5251     case TK_NOTNULL: {
5252       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5253       sqlite3VdbeAddOp2(v, op, r1, dest);
5254       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
5255       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
5256       testcase( regFree1==0 );
5257       break;
5258     }
5259     case TK_BETWEEN: {
5260       testcase( jumpIfNull==0 );
5261       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5262       break;
5263     }
5264 #ifndef SQLITE_OMIT_SUBQUERY
5265     case TK_IN: {
5266       if( jumpIfNull ){
5267         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5268       }else{
5269         int destIfNull = sqlite3VdbeMakeLabel(pParse);
5270         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5271         sqlite3VdbeResolveLabel(v, destIfNull);
5272       }
5273       break;
5274     }
5275 #endif
5276     default: {
5277     default_expr:
5278       if( ExprAlwaysFalse(pExpr) ){
5279         sqlite3VdbeGoto(v, dest);
5280       }else if( ExprAlwaysTrue(pExpr) ){
5281         /* no-op */
5282       }else{
5283         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5284         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5285         VdbeCoverage(v);
5286         testcase( regFree1==0 );
5287         testcase( jumpIfNull==0 );
5288       }
5289       break;
5290     }
5291   }
5292   sqlite3ReleaseTempReg(pParse, regFree1);
5293   sqlite3ReleaseTempReg(pParse, regFree2);
5294 }
5295 
5296 /*
5297 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5298 ** code generation, and that copy is deleted after code generation. This
5299 ** ensures that the original pExpr is unchanged.
5300 */
5301 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5302   sqlite3 *db = pParse->db;
5303   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5304   if( db->mallocFailed==0 ){
5305     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5306   }
5307   sqlite3ExprDelete(db, pCopy);
5308 }
5309 
5310 /*
5311 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5312 ** type of expression.
5313 **
5314 ** If pExpr is a simple SQL value - an integer, real, string, blob
5315 ** or NULL value - then the VDBE currently being prepared is configured
5316 ** to re-prepare each time a new value is bound to variable pVar.
5317 **
5318 ** Additionally, if pExpr is a simple SQL value and the value is the
5319 ** same as that currently bound to variable pVar, non-zero is returned.
5320 ** Otherwise, if the values are not the same or if pExpr is not a simple
5321 ** SQL value, zero is returned.
5322 */
5323 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
5324   int res = 0;
5325   int iVar;
5326   sqlite3_value *pL, *pR = 0;
5327 
5328   sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5329   if( pR ){
5330     iVar = pVar->iColumn;
5331     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5332     pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5333     if( pL ){
5334       if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5335         sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5336       }
5337       res =  0==sqlite3MemCompare(pL, pR, 0);
5338     }
5339     sqlite3ValueFree(pR);
5340     sqlite3ValueFree(pL);
5341   }
5342 
5343   return res;
5344 }
5345 
5346 /*
5347 ** Do a deep comparison of two expression trees.  Return 0 if the two
5348 ** expressions are completely identical.  Return 1 if they differ only
5349 ** by a COLLATE operator at the top level.  Return 2 if there are differences
5350 ** other than the top-level COLLATE operator.
5351 **
5352 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5353 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5354 **
5355 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
5356 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5357 **
5358 ** Sometimes this routine will return 2 even if the two expressions
5359 ** really are equivalent.  If we cannot prove that the expressions are
5360 ** identical, we return 2 just to be safe.  So if this routine
5361 ** returns 2, then you do not really know for certain if the two
5362 ** expressions are the same.  But if you get a 0 or 1 return, then you
5363 ** can be sure the expressions are the same.  In the places where
5364 ** this routine is used, it does not hurt to get an extra 2 - that
5365 ** just might result in some slightly slower code.  But returning
5366 ** an incorrect 0 or 1 could lead to a malfunction.
5367 **
5368 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5369 ** pParse->pReprepare can be matched against literals in pB.  The
5370 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5371 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5372 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5373 ** pB causes a return value of 2.
5374 */
5375 int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
5376   u32 combinedFlags;
5377   if( pA==0 || pB==0 ){
5378     return pB==pA ? 0 : 2;
5379   }
5380   if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5381     return 0;
5382   }
5383   combinedFlags = pA->flags | pB->flags;
5384   if( combinedFlags & EP_IntValue ){
5385     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5386       return 0;
5387     }
5388     return 2;
5389   }
5390   if( pA->op!=pB->op || pA->op==TK_RAISE ){
5391     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5392       return 1;
5393     }
5394     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5395       return 1;
5396     }
5397     return 2;
5398   }
5399   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
5400     if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5401       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5402 #ifndef SQLITE_OMIT_WINDOWFUNC
5403       assert( pA->op==pB->op );
5404       if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5405         return 2;
5406       }
5407       if( ExprHasProperty(pA,EP_WinFunc) ){
5408         if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5409           return 2;
5410         }
5411       }
5412 #endif
5413     }else if( pA->op==TK_NULL ){
5414       return 0;
5415     }else if( pA->op==TK_COLLATE ){
5416       if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5417     }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
5418       return 2;
5419     }
5420   }
5421   if( (pA->flags & (EP_Distinct|EP_Commuted))
5422      != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5423   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
5424     if( combinedFlags & EP_xIsSelect ) return 2;
5425     if( (combinedFlags & EP_FixedCol)==0
5426      && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5427     if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5428     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5429     if( pA->op!=TK_STRING
5430      && pA->op!=TK_TRUEFALSE
5431      && ALWAYS((combinedFlags & EP_Reduced)==0)
5432     ){
5433       if( pA->iColumn!=pB->iColumn ) return 2;
5434       if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
5435       if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
5436         return 2;
5437       }
5438     }
5439   }
5440   return 0;
5441 }
5442 
5443 /*
5444 ** Compare two ExprList objects.  Return 0 if they are identical, 1
5445 ** if they are certainly different, or 2 if it is not possible to
5446 ** determine if they are identical or not.
5447 **
5448 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5449 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5450 **
5451 ** This routine might return non-zero for equivalent ExprLists.  The
5452 ** only consequence will be disabled optimizations.  But this routine
5453 ** must never return 0 if the two ExprList objects are different, or
5454 ** a malfunction will result.
5455 **
5456 ** Two NULL pointers are considered to be the same.  But a NULL pointer
5457 ** always differs from a non-NULL pointer.
5458 */
5459 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
5460   int i;
5461   if( pA==0 && pB==0 ) return 0;
5462   if( pA==0 || pB==0 ) return 1;
5463   if( pA->nExpr!=pB->nExpr ) return 1;
5464   for(i=0; i<pA->nExpr; i++){
5465     int res;
5466     Expr *pExprA = pA->a[i].pExpr;
5467     Expr *pExprB = pB->a[i].pExpr;
5468     if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
5469     if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
5470   }
5471   return 0;
5472 }
5473 
5474 /*
5475 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5476 ** are ignored.
5477 */
5478 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
5479   return sqlite3ExprCompare(0,
5480              sqlite3ExprSkipCollateAndLikely(pA),
5481              sqlite3ExprSkipCollateAndLikely(pB),
5482              iTab);
5483 }
5484 
5485 /*
5486 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5487 **
5488 ** Or if seenNot is true, return non-zero if Expr p can only be
5489 ** non-NULL if pNN is not NULL
5490 */
5491 static int exprImpliesNotNull(
5492   Parse *pParse,      /* Parsing context */
5493   Expr *p,            /* The expression to be checked */
5494   Expr *pNN,          /* The expression that is NOT NULL */
5495   int iTab,           /* Table being evaluated */
5496   int seenNot         /* Return true only if p can be any non-NULL value */
5497 ){
5498   assert( p );
5499   assert( pNN );
5500   if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
5501     return pNN->op!=TK_NULL;
5502   }
5503   switch( p->op ){
5504     case TK_IN: {
5505       if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
5506       assert( ExprHasProperty(p,EP_xIsSelect)
5507            || (p->x.pList!=0 && p->x.pList->nExpr>0) );
5508       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5509     }
5510     case TK_BETWEEN: {
5511       ExprList *pList = p->x.pList;
5512       assert( pList!=0 );
5513       assert( pList->nExpr==2 );
5514       if( seenNot ) return 0;
5515       if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
5516        || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
5517       ){
5518         return 1;
5519       }
5520       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5521     }
5522     case TK_EQ:
5523     case TK_NE:
5524     case TK_LT:
5525     case TK_LE:
5526     case TK_GT:
5527     case TK_GE:
5528     case TK_PLUS:
5529     case TK_MINUS:
5530     case TK_BITOR:
5531     case TK_LSHIFT:
5532     case TK_RSHIFT:
5533     case TK_CONCAT:
5534       seenNot = 1;
5535       /* no break */ deliberate_fall_through
5536     case TK_STAR:
5537     case TK_REM:
5538     case TK_BITAND:
5539     case TK_SLASH: {
5540       if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
5541       /* no break */ deliberate_fall_through
5542     }
5543     case TK_SPAN:
5544     case TK_COLLATE:
5545     case TK_UPLUS:
5546     case TK_UMINUS: {
5547       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
5548     }
5549     case TK_TRUTH: {
5550       if( seenNot ) return 0;
5551       if( p->op2!=TK_IS ) return 0;
5552       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5553     }
5554     case TK_BITNOT:
5555     case TK_NOT: {
5556       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5557     }
5558   }
5559   return 0;
5560 }
5561 
5562 /*
5563 ** Return true if we can prove the pE2 will always be true if pE1 is
5564 ** true.  Return false if we cannot complete the proof or if pE2 might
5565 ** be false.  Examples:
5566 **
5567 **     pE1: x==5       pE2: x==5             Result: true
5568 **     pE1: x>0        pE2: x==5             Result: false
5569 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
5570 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
5571 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
5572 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
5573 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
5574 **
5575 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5576 ** Expr.iTable<0 then assume a table number given by iTab.
5577 **
5578 ** If pParse is not NULL, then the values of bound variables in pE1 are
5579 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5580 ** modified to record which bound variables are referenced.  If pParse
5581 ** is NULL, then false will be returned if pE1 contains any bound variables.
5582 **
5583 ** When in doubt, return false.  Returning true might give a performance
5584 ** improvement.  Returning false might cause a performance reduction, but
5585 ** it will always give the correct answer and is hence always safe.
5586 */
5587 int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
5588   if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5589     return 1;
5590   }
5591   if( pE2->op==TK_OR
5592    && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
5593              || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5594   ){
5595     return 1;
5596   }
5597   if( pE2->op==TK_NOTNULL
5598    && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
5599   ){
5600     return 1;
5601   }
5602   return 0;
5603 }
5604 
5605 /*
5606 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
5607 ** If the expression node requires that the table at pWalker->iCur
5608 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5609 **
5610 ** This routine controls an optimization.  False positives (setting
5611 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
5612 ** (never setting pWalker->eCode) is a harmless missed optimization.
5613 */
5614 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
5615   testcase( pExpr->op==TK_AGG_COLUMN );
5616   testcase( pExpr->op==TK_AGG_FUNCTION );
5617   if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
5618   switch( pExpr->op ){
5619     case TK_ISNOT:
5620     case TK_ISNULL:
5621     case TK_NOTNULL:
5622     case TK_IS:
5623     case TK_OR:
5624     case TK_VECTOR:
5625     case TK_CASE:
5626     case TK_IN:
5627     case TK_FUNCTION:
5628     case TK_TRUTH:
5629       testcase( pExpr->op==TK_ISNOT );
5630       testcase( pExpr->op==TK_ISNULL );
5631       testcase( pExpr->op==TK_NOTNULL );
5632       testcase( pExpr->op==TK_IS );
5633       testcase( pExpr->op==TK_OR );
5634       testcase( pExpr->op==TK_VECTOR );
5635       testcase( pExpr->op==TK_CASE );
5636       testcase( pExpr->op==TK_IN );
5637       testcase( pExpr->op==TK_FUNCTION );
5638       testcase( pExpr->op==TK_TRUTH );
5639       return WRC_Prune;
5640     case TK_COLUMN:
5641       if( pWalker->u.iCur==pExpr->iTable ){
5642         pWalker->eCode = 1;
5643         return WRC_Abort;
5644       }
5645       return WRC_Prune;
5646 
5647     case TK_AND:
5648       if( pWalker->eCode==0 ){
5649         sqlite3WalkExpr(pWalker, pExpr->pLeft);
5650         if( pWalker->eCode ){
5651           pWalker->eCode = 0;
5652           sqlite3WalkExpr(pWalker, pExpr->pRight);
5653         }
5654       }
5655       return WRC_Prune;
5656 
5657     case TK_BETWEEN:
5658       if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
5659         assert( pWalker->eCode );
5660         return WRC_Abort;
5661       }
5662       return WRC_Prune;
5663 
5664     /* Virtual tables are allowed to use constraints like x=NULL.  So
5665     ** a term of the form x=y does not prove that y is not null if x
5666     ** is the column of a virtual table */
5667     case TK_EQ:
5668     case TK_NE:
5669     case TK_LT:
5670     case TK_LE:
5671     case TK_GT:
5672     case TK_GE: {
5673       Expr *pLeft = pExpr->pLeft;
5674       Expr *pRight = pExpr->pRight;
5675       testcase( pExpr->op==TK_EQ );
5676       testcase( pExpr->op==TK_NE );
5677       testcase( pExpr->op==TK_LT );
5678       testcase( pExpr->op==TK_LE );
5679       testcase( pExpr->op==TK_GT );
5680       testcase( pExpr->op==TK_GE );
5681       /* The y.pTab=0 assignment in wherecode.c always happens after the
5682       ** impliesNotNullRow() test */
5683       if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
5684                                && IsVirtual(pLeft->y.pTab))
5685        || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
5686                                && IsVirtual(pRight->y.pTab))
5687       ){
5688         return WRC_Prune;
5689       }
5690       /* no break */ deliberate_fall_through
5691     }
5692     default:
5693       return WRC_Continue;
5694   }
5695 }
5696 
5697 /*
5698 ** Return true (non-zero) if expression p can only be true if at least
5699 ** one column of table iTab is non-null.  In other words, return true
5700 ** if expression p will always be NULL or false if every column of iTab
5701 ** is NULL.
5702 **
5703 ** False negatives are acceptable.  In other words, it is ok to return
5704 ** zero even if expression p will never be true of every column of iTab
5705 ** is NULL.  A false negative is merely a missed optimization opportunity.
5706 **
5707 ** False positives are not allowed, however.  A false positive may result
5708 ** in an incorrect answer.
5709 **
5710 ** Terms of p that are marked with EP_FromJoin (and hence that come from
5711 ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
5712 **
5713 ** This routine is used to check if a LEFT JOIN can be converted into
5714 ** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
5715 ** clause requires that some column of the right table of the LEFT JOIN
5716 ** be non-NULL, then the LEFT JOIN can be safely converted into an
5717 ** ordinary join.
5718 */
5719 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
5720   Walker w;
5721   p = sqlite3ExprSkipCollateAndLikely(p);
5722   if( p==0 ) return 0;
5723   if( p->op==TK_NOTNULL ){
5724     p = p->pLeft;
5725   }else{
5726     while( p->op==TK_AND ){
5727       if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
5728       p = p->pRight;
5729     }
5730   }
5731   w.xExprCallback = impliesNotNullRow;
5732   w.xSelectCallback = 0;
5733   w.xSelectCallback2 = 0;
5734   w.eCode = 0;
5735   w.u.iCur = iTab;
5736   sqlite3WalkExpr(&w, p);
5737   return w.eCode;
5738 }
5739 
5740 /*
5741 ** An instance of the following structure is used by the tree walker
5742 ** to determine if an expression can be evaluated by reference to the
5743 ** index only, without having to do a search for the corresponding
5744 ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
5745 ** is the cursor for the table.
5746 */
5747 struct IdxCover {
5748   Index *pIdx;     /* The index to be tested for coverage */
5749   int iCur;        /* Cursor number for the table corresponding to the index */
5750 };
5751 
5752 /*
5753 ** Check to see if there are references to columns in table
5754 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
5755 ** pWalker->u.pIdxCover->pIdx.
5756 */
5757 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
5758   if( pExpr->op==TK_COLUMN
5759    && pExpr->iTable==pWalker->u.pIdxCover->iCur
5760    && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
5761   ){
5762     pWalker->eCode = 1;
5763     return WRC_Abort;
5764   }
5765   return WRC_Continue;
5766 }
5767 
5768 /*
5769 ** Determine if an index pIdx on table with cursor iCur contains will
5770 ** the expression pExpr.  Return true if the index does cover the
5771 ** expression and false if the pExpr expression references table columns
5772 ** that are not found in the index pIdx.
5773 **
5774 ** An index covering an expression means that the expression can be
5775 ** evaluated using only the index and without having to lookup the
5776 ** corresponding table entry.
5777 */
5778 int sqlite3ExprCoveredByIndex(
5779   Expr *pExpr,        /* The index to be tested */
5780   int iCur,           /* The cursor number for the corresponding table */
5781   Index *pIdx         /* The index that might be used for coverage */
5782 ){
5783   Walker w;
5784   struct IdxCover xcov;
5785   memset(&w, 0, sizeof(w));
5786   xcov.iCur = iCur;
5787   xcov.pIdx = pIdx;
5788   w.xExprCallback = exprIdxCover;
5789   w.u.pIdxCover = &xcov;
5790   sqlite3WalkExpr(&w, pExpr);
5791   return !w.eCode;
5792 }
5793 
5794 
5795 /*
5796 ** An instance of the following structure is used by the tree walker
5797 ** to count references to table columns in the arguments of an
5798 ** aggregate function, in order to implement the
5799 ** sqlite3FunctionThisSrc() routine.
5800 */
5801 struct SrcCount {
5802   SrcList *pSrc;   /* One particular FROM clause in a nested query */
5803   int iSrcInner;   /* Smallest cursor number in this context */
5804   int nThis;       /* Number of references to columns in pSrcList */
5805   int nOther;      /* Number of references to columns in other FROM clauses */
5806 };
5807 
5808 /*
5809 ** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first
5810 ** SELECT with a FROM clause encountered during this iteration, set
5811 ** SrcCount.iSrcInner to the cursor number of the leftmost object in
5812 ** the FROM cause.
5813 */
5814 static int selectSrcCount(Walker *pWalker, Select *pSel){
5815   struct SrcCount *p = pWalker->u.pSrcCount;
5816   if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){
5817     pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;
5818   }
5819   return WRC_Continue;
5820 }
5821 
5822 /*
5823 ** Count the number of references to columns.
5824 */
5825 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
5826   /* There was once a NEVER() on the second term on the grounds that
5827   ** sqlite3FunctionUsesThisSrc() was always called before
5828   ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
5829   ** been converted into TK_AGG_COLUMN. But this is no longer true due
5830   ** to window functions - sqlite3WindowRewrite() may now indirectly call
5831   ** FunctionUsesThisSrc() when creating a new sub-select. */
5832   if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
5833     int i;
5834     struct SrcCount *p = pWalker->u.pSrcCount;
5835     SrcList *pSrc = p->pSrc;
5836     int nSrc = pSrc ? pSrc->nSrc : 0;
5837     for(i=0; i<nSrc; i++){
5838       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
5839     }
5840     if( i<nSrc ){
5841       p->nThis++;
5842     }else if( pExpr->iTable<p->iSrcInner ){
5843       /* In a well-formed parse tree (no name resolution errors),
5844       ** TK_COLUMN nodes with smaller Expr.iTable values are in an
5845       ** outer context.  Those are the only ones to count as "other" */
5846       p->nOther++;
5847     }
5848   }
5849   return WRC_Continue;
5850 }
5851 
5852 /*
5853 ** Determine if any of the arguments to the pExpr Function reference
5854 ** pSrcList.  Return true if they do.  Also return true if the function
5855 ** has no arguments or has only constant arguments.  Return false if pExpr
5856 ** references columns but not columns of tables found in pSrcList.
5857 */
5858 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
5859   Walker w;
5860   struct SrcCount cnt;
5861   assert( pExpr->op==TK_AGG_FUNCTION );
5862   memset(&w, 0, sizeof(w));
5863   w.xExprCallback = exprSrcCount;
5864   w.xSelectCallback = selectSrcCount;
5865   w.u.pSrcCount = &cnt;
5866   cnt.pSrc = pSrcList;
5867   cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;
5868   cnt.nThis = 0;
5869   cnt.nOther = 0;
5870   sqlite3WalkExprList(&w, pExpr->x.pList);
5871 #ifndef SQLITE_OMIT_WINDOWFUNC
5872   if( ExprHasProperty(pExpr, EP_WinFunc) ){
5873     sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
5874   }
5875 #endif
5876   return cnt.nThis>0 || cnt.nOther==0;
5877 }
5878 
5879 /*
5880 ** This is a Walker expression node callback.
5881 **
5882 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
5883 ** object that is referenced does not refer directly to the Expr.  If
5884 ** it does, make a copy.  This is done because the pExpr argument is
5885 ** subject to change.
5886 **
5887 ** The copy is stored on pParse->pConstExpr with a register number of 0.
5888 ** This will cause the expression to be deleted automatically when the
5889 ** Parse object is destroyed, but the zero register number means that it
5890 ** will not generate any code in the preamble.
5891 */
5892 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
5893   if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
5894    && pExpr->pAggInfo!=0
5895   ){
5896     AggInfo *pAggInfo = pExpr->pAggInfo;
5897     int iAgg = pExpr->iAgg;
5898     Parse *pParse = pWalker->pParse;
5899     sqlite3 *db = pParse->db;
5900     assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION );
5901     if( pExpr->op==TK_AGG_COLUMN ){
5902       assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
5903       if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){
5904         pExpr = sqlite3ExprDup(db, pExpr, 0);
5905         if( pExpr ){
5906           pAggInfo->aCol[iAgg].pCExpr = pExpr;
5907           sqlite3ExprDeferredDelete(pParse, pExpr);
5908         }
5909       }
5910     }else{
5911       assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
5912       if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){
5913         pExpr = sqlite3ExprDup(db, pExpr, 0);
5914         if( pExpr ){
5915           pAggInfo->aFunc[iAgg].pFExpr = pExpr;
5916           sqlite3ExprDeferredDelete(pParse, pExpr);
5917         }
5918       }
5919     }
5920   }
5921   return WRC_Continue;
5922 }
5923 
5924 /*
5925 ** Initialize a Walker object so that will persist AggInfo entries referenced
5926 ** by the tree that is walked.
5927 */
5928 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
5929   memset(pWalker, 0, sizeof(*pWalker));
5930   pWalker->pParse = pParse;
5931   pWalker->xExprCallback = agginfoPersistExprCb;
5932   pWalker->xSelectCallback = sqlite3SelectWalkNoop;
5933 }
5934 
5935 /*
5936 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
5937 ** the new element.  Return a negative number if malloc fails.
5938 */
5939 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
5940   int i;
5941   pInfo->aCol = sqlite3ArrayAllocate(
5942        db,
5943        pInfo->aCol,
5944        sizeof(pInfo->aCol[0]),
5945        &pInfo->nColumn,
5946        &i
5947   );
5948   return i;
5949 }
5950 
5951 /*
5952 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
5953 ** the new element.  Return a negative number if malloc fails.
5954 */
5955 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
5956   int i;
5957   pInfo->aFunc = sqlite3ArrayAllocate(
5958        db,
5959        pInfo->aFunc,
5960        sizeof(pInfo->aFunc[0]),
5961        &pInfo->nFunc,
5962        &i
5963   );
5964   return i;
5965 }
5966 
5967 /*
5968 ** This is the xExprCallback for a tree walker.  It is used to
5969 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
5970 ** for additional information.
5971 */
5972 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
5973   int i;
5974   NameContext *pNC = pWalker->u.pNC;
5975   Parse *pParse = pNC->pParse;
5976   SrcList *pSrcList = pNC->pSrcList;
5977   AggInfo *pAggInfo = pNC->uNC.pAggInfo;
5978 
5979   assert( pNC->ncFlags & NC_UAggInfo );
5980   switch( pExpr->op ){
5981     case TK_AGG_COLUMN:
5982     case TK_COLUMN: {
5983       testcase( pExpr->op==TK_AGG_COLUMN );
5984       testcase( pExpr->op==TK_COLUMN );
5985       /* Check to see if the column is in one of the tables in the FROM
5986       ** clause of the aggregate query */
5987       if( ALWAYS(pSrcList!=0) ){
5988         SrcItem *pItem = pSrcList->a;
5989         for(i=0; i<pSrcList->nSrc; i++, pItem++){
5990           struct AggInfo_col *pCol;
5991           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5992           if( pExpr->iTable==pItem->iCursor ){
5993             /* If we reach this point, it means that pExpr refers to a table
5994             ** that is in the FROM clause of the aggregate query.
5995             **
5996             ** Make an entry for the column in pAggInfo->aCol[] if there
5997             ** is not an entry there already.
5998             */
5999             int k;
6000             pCol = pAggInfo->aCol;
6001             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6002               if( pCol->iTable==pExpr->iTable &&
6003                   pCol->iColumn==pExpr->iColumn ){
6004                 break;
6005               }
6006             }
6007             if( (k>=pAggInfo->nColumn)
6008              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
6009             ){
6010               pCol = &pAggInfo->aCol[k];
6011               pCol->pTab = pExpr->y.pTab;
6012               pCol->iTable = pExpr->iTable;
6013               pCol->iColumn = pExpr->iColumn;
6014               pCol->iMem = ++pParse->nMem;
6015               pCol->iSorterColumn = -1;
6016               pCol->pCExpr = pExpr;
6017               if( pAggInfo->pGroupBy ){
6018                 int j, n;
6019                 ExprList *pGB = pAggInfo->pGroupBy;
6020                 struct ExprList_item *pTerm = pGB->a;
6021                 n = pGB->nExpr;
6022                 for(j=0; j<n; j++, pTerm++){
6023                   Expr *pE = pTerm->pExpr;
6024                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
6025                       pE->iColumn==pExpr->iColumn ){
6026                     pCol->iSorterColumn = j;
6027                     break;
6028                   }
6029                 }
6030               }
6031               if( pCol->iSorterColumn<0 ){
6032                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
6033               }
6034             }
6035             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
6036             ** because it was there before or because we just created it).
6037             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
6038             ** pAggInfo->aCol[] entry.
6039             */
6040             ExprSetVVAProperty(pExpr, EP_NoReduce);
6041             pExpr->pAggInfo = pAggInfo;
6042             pExpr->op = TK_AGG_COLUMN;
6043             pExpr->iAgg = (i16)k;
6044             break;
6045           } /* endif pExpr->iTable==pItem->iCursor */
6046         } /* end loop over pSrcList */
6047       }
6048       return WRC_Prune;
6049     }
6050     case TK_AGG_FUNCTION: {
6051       if( (pNC->ncFlags & NC_InAggFunc)==0
6052        && pWalker->walkerDepth==pExpr->op2
6053       ){
6054         /* Check to see if pExpr is a duplicate of another aggregate
6055         ** function that is already in the pAggInfo structure
6056         */
6057         struct AggInfo_func *pItem = pAggInfo->aFunc;
6058         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
6059           if( pItem->pFExpr==pExpr ) break;
6060           if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
6061             break;
6062           }
6063         }
6064         if( i>=pAggInfo->nFunc ){
6065           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
6066           */
6067           u8 enc = ENC(pParse->db);
6068           i = addAggInfoFunc(pParse->db, pAggInfo);
6069           if( i>=0 ){
6070             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
6071             pItem = &pAggInfo->aFunc[i];
6072             pItem->pFExpr = pExpr;
6073             pItem->iMem = ++pParse->nMem;
6074             assert( !ExprHasProperty(pExpr, EP_IntValue) );
6075             pItem->pFunc = sqlite3FindFunction(pParse->db,
6076                    pExpr->u.zToken,
6077                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
6078             if( pExpr->flags & EP_Distinct ){
6079               pItem->iDistinct = pParse->nTab++;
6080             }else{
6081               pItem->iDistinct = -1;
6082             }
6083           }
6084         }
6085         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6086         */
6087         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6088         ExprSetVVAProperty(pExpr, EP_NoReduce);
6089         pExpr->iAgg = (i16)i;
6090         pExpr->pAggInfo = pAggInfo;
6091         return WRC_Prune;
6092       }else{
6093         return WRC_Continue;
6094       }
6095     }
6096   }
6097   return WRC_Continue;
6098 }
6099 
6100 /*
6101 ** Analyze the pExpr expression looking for aggregate functions and
6102 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6103 ** points to.  Additional entries are made on the AggInfo object as
6104 ** necessary.
6105 **
6106 ** This routine should only be called after the expression has been
6107 ** analyzed by sqlite3ResolveExprNames().
6108 */
6109 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
6110   Walker w;
6111   w.xExprCallback = analyzeAggregate;
6112   w.xSelectCallback = sqlite3WalkerDepthIncrease;
6113   w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
6114   w.walkerDepth = 0;
6115   w.u.pNC = pNC;
6116   w.pParse = 0;
6117   assert( pNC->pSrcList!=0 );
6118   sqlite3WalkExpr(&w, pExpr);
6119 }
6120 
6121 /*
6122 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6123 ** expression list.  Return the number of errors.
6124 **
6125 ** If an error is found, the analysis is cut short.
6126 */
6127 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
6128   struct ExprList_item *pItem;
6129   int i;
6130   if( pList ){
6131     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
6132       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
6133     }
6134   }
6135 }
6136 
6137 /*
6138 ** Allocate a single new register for use to hold some intermediate result.
6139 */
6140 int sqlite3GetTempReg(Parse *pParse){
6141   if( pParse->nTempReg==0 ){
6142     return ++pParse->nMem;
6143   }
6144   return pParse->aTempReg[--pParse->nTempReg];
6145 }
6146 
6147 /*
6148 ** Deallocate a register, making available for reuse for some other
6149 ** purpose.
6150 */
6151 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6152   if( iReg ){
6153     sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
6154     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
6155       pParse->aTempReg[pParse->nTempReg++] = iReg;
6156     }
6157   }
6158 }
6159 
6160 /*
6161 ** Allocate or deallocate a block of nReg consecutive registers.
6162 */
6163 int sqlite3GetTempRange(Parse *pParse, int nReg){
6164   int i, n;
6165   if( nReg==1 ) return sqlite3GetTempReg(pParse);
6166   i = pParse->iRangeReg;
6167   n = pParse->nRangeReg;
6168   if( nReg<=n ){
6169     pParse->iRangeReg += nReg;
6170     pParse->nRangeReg -= nReg;
6171   }else{
6172     i = pParse->nMem+1;
6173     pParse->nMem += nReg;
6174   }
6175   return i;
6176 }
6177 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
6178   if( nReg==1 ){
6179     sqlite3ReleaseTempReg(pParse, iReg);
6180     return;
6181   }
6182   sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
6183   if( nReg>pParse->nRangeReg ){
6184     pParse->nRangeReg = nReg;
6185     pParse->iRangeReg = iReg;
6186   }
6187 }
6188 
6189 /*
6190 ** Mark all temporary registers as being unavailable for reuse.
6191 **
6192 ** Always invoke this procedure after coding a subroutine or co-routine
6193 ** that might be invoked from other parts of the code, to ensure that
6194 ** the sub/co-routine does not use registers in common with the code that
6195 ** invokes the sub/co-routine.
6196 */
6197 void sqlite3ClearTempRegCache(Parse *pParse){
6198   pParse->nTempReg = 0;
6199   pParse->nRangeReg = 0;
6200 }
6201 
6202 /*
6203 ** Validate that no temporary register falls within the range of
6204 ** iFirst..iLast, inclusive.  This routine is only call from within assert()
6205 ** statements.
6206 */
6207 #ifdef SQLITE_DEBUG
6208 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
6209   int i;
6210   if( pParse->nRangeReg>0
6211    && pParse->iRangeReg+pParse->nRangeReg > iFirst
6212    && pParse->iRangeReg <= iLast
6213   ){
6214      return 0;
6215   }
6216   for(i=0; i<pParse->nTempReg; i++){
6217     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
6218       return 0;
6219     }
6220   }
6221   return 1;
6222 }
6223 #endif /* SQLITE_DEBUG */
6224