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