LCOV - code coverage report
Current view: top level - src/backend/executor - execExpr.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta1 Lines: 1256 1296 96.9 %
Date: 2019-06-16 14:06:46 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * execExpr.c
       4             :  *    Expression evaluation infrastructure.
       5             :  *
       6             :  *  During executor startup, we compile each expression tree (which has
       7             :  *  previously been processed by the parser and planner) into an ExprState,
       8             :  *  using ExecInitExpr() et al.  This converts the tree into a flat array
       9             :  *  of ExprEvalSteps, which may be thought of as instructions in a program.
      10             :  *  At runtime, we'll execute steps, starting with the first, until we reach
      11             :  *  an EEOP_DONE opcode.
      12             :  *
      13             :  *  This file contains the "compilation" logic.  It is independent of the
      14             :  *  specific execution technology we use (switch statement, computed goto,
      15             :  *  JIT compilation, etc).
      16             :  *
      17             :  *  See src/backend/executor/README for some background, specifically the
      18             :  *  "Expression Trees and ExprState nodes", "Expression Initialization",
      19             :  *  and "Expression Evaluation" sections.
      20             :  *
      21             :  *
      22             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      23             :  * Portions Copyright (c) 1994, Regents of the University of California
      24             :  *
      25             :  *
      26             :  * IDENTIFICATION
      27             :  *    src/backend/executor/execExpr.c
      28             :  *
      29             :  *-------------------------------------------------------------------------
      30             :  */
      31             : #include "postgres.h"
      32             : 
      33             : #include "access/nbtree.h"
      34             : #include "catalog/objectaccess.h"
      35             : #include "catalog/pg_type.h"
      36             : #include "executor/execExpr.h"
      37             : #include "executor/nodeSubplan.h"
      38             : #include "funcapi.h"
      39             : #include "jit/jit.h"
      40             : #include "miscadmin.h"
      41             : #include "nodes/makefuncs.h"
      42             : #include "nodes/nodeFuncs.h"
      43             : #include "optimizer/optimizer.h"
      44             : #include "pgstat.h"
      45             : #include "utils/builtins.h"
      46             : #include "utils/datum.h"
      47             : #include "utils/lsyscache.h"
      48             : #include "utils/typcache.h"
      49             : 
      50             : 
      51             : typedef struct LastAttnumInfo
      52             : {
      53             :     AttrNumber  last_inner;
      54             :     AttrNumber  last_outer;
      55             :     AttrNumber  last_scan;
      56             : } LastAttnumInfo;
      57             : 
      58             : static void ExecReadyExpr(ExprState *state);
      59             : static void ExecInitExprRec(Expr *node, ExprState *state,
      60             :                             Datum *resv, bool *resnull);
      61             : static void ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args,
      62             :                          Oid funcid, Oid inputcollid,
      63             :                          ExprState *state);
      64             : static void ExecInitExprSlots(ExprState *state, Node *node);
      65             : static void ExecPushExprSlots(ExprState *state, LastAttnumInfo *info);
      66             : static bool get_last_attnums_walker(Node *node, LastAttnumInfo *info);
      67             : static void ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op);
      68             : static void ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable,
      69             :                                 ExprState *state);
      70             : static void ExecInitSubscriptingRef(ExprEvalStep *scratch,
      71             :                                     SubscriptingRef *sbsref,
      72             :                                     ExprState *state,
      73             :                                     Datum *resv, bool *resnull);
      74             : static bool isAssignmentIndirectionExpr(Expr *expr);
      75             : static void ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
      76             :                                    ExprState *state,
      77             :                                    Datum *resv, bool *resnull);
      78             : static void ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
      79             :                                   ExprEvalStep *scratch,
      80             :                                   FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
      81             :                                   int transno, int setno, int setoff, bool ishash);
      82             : 
      83             : 
      84             : /*
      85             :  * ExecInitExpr: prepare an expression tree for execution
      86             :  *
      87             :  * This function builds and returns an ExprState implementing the given
      88             :  * Expr node tree.  The return ExprState can then be handed to ExecEvalExpr
      89             :  * for execution.  Because the Expr tree itself is read-only as far as
      90             :  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
      91             :  * of the same plan tree can occur concurrently.  (But note that an ExprState
      92             :  * does mutate at runtime, so it can't be re-used concurrently.)
      93             :  *
      94             :  * This must be called in a memory context that will last as long as repeated
      95             :  * executions of the expression are needed.  Typically the context will be
      96             :  * the same as the per-query context of the associated ExprContext.
      97             :  *
      98             :  * Any Aggref, WindowFunc, or SubPlan nodes found in the tree are added to
      99             :  * the lists of such nodes held by the parent PlanState (or more accurately,
     100             :  * the AggrefExprState etc. nodes created for them are added).
     101             :  *
     102             :  * Note: there is no ExecEndExpr function; we assume that any resource
     103             :  * cleanup needed will be handled by just releasing the memory context
     104             :  * in which the state tree is built.  Functions that require additional
     105             :  * cleanup work can register a shutdown callback in the ExprContext.
     106             :  *
     107             :  *  'node' is the root of the expression tree to compile.
     108             :  *  'parent' is the PlanState node that owns the expression.
     109             :  *
     110             :  * 'parent' may be NULL if we are preparing an expression that is not
     111             :  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
     112             :  * Such cases should usually come through ExecPrepareExpr, not directly here.
     113             :  *
     114             :  * Also, if 'node' is NULL, we just return NULL.  This is convenient for some
     115             :  * callers that may or may not have an expression that needs to be compiled.
     116             :  * Note that a NULL ExprState pointer *cannot* be handed to ExecEvalExpr,
     117             :  * although ExecQual and ExecCheck will accept one (and treat it as "true").
     118             :  */
     119             : ExprState *
     120      498838 : ExecInitExpr(Expr *node, PlanState *parent)
     121             : {
     122             :     ExprState  *state;
     123      498838 :     ExprEvalStep scratch = {0};
     124             : 
     125             :     /* Special case: NULL expression produces a NULL ExprState pointer */
     126      498838 :     if (node == NULL)
     127       54410 :         return NULL;
     128             : 
     129             :     /* Initialize ExprState with empty step list */
     130      444428 :     state = makeNode(ExprState);
     131      444428 :     state->expr = node;
     132      444428 :     state->parent = parent;
     133      444428 :     state->ext_params = NULL;
     134             : 
     135             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     136      444428 :     ExecInitExprSlots(state, (Node *) node);
     137             : 
     138             :     /* Compile the expression proper */
     139      444428 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     140             : 
     141             :     /* Finally, append a DONE step */
     142      444416 :     scratch.opcode = EEOP_DONE;
     143      444416 :     ExprEvalPushStep(state, &scratch);
     144             : 
     145      444416 :     ExecReadyExpr(state);
     146             : 
     147      444416 :     return state;
     148             : }
     149             : 
     150             : /*
     151             :  * ExecInitExprWithParams: prepare a standalone expression tree for execution
     152             :  *
     153             :  * This is the same as ExecInitExpr, except that there is no parent PlanState,
     154             :  * and instead we may have a ParamListInfo describing PARAM_EXTERN Params.
     155             :  */
     156             : ExprState *
     157       35460 : ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
     158             : {
     159             :     ExprState  *state;
     160       35460 :     ExprEvalStep scratch = {0};
     161             : 
     162             :     /* Special case: NULL expression produces a NULL ExprState pointer */
     163       35460 :     if (node == NULL)
     164           0 :         return NULL;
     165             : 
     166             :     /* Initialize ExprState with empty step list */
     167       35460 :     state = makeNode(ExprState);
     168       35460 :     state->expr = node;
     169       35460 :     state->parent = NULL;
     170       35460 :     state->ext_params = ext_params;
     171             : 
     172             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     173       35460 :     ExecInitExprSlots(state, (Node *) node);
     174             : 
     175             :     /* Compile the expression proper */
     176       35460 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     177             : 
     178             :     /* Finally, append a DONE step */
     179       35460 :     scratch.opcode = EEOP_DONE;
     180       35460 :     ExprEvalPushStep(state, &scratch);
     181             : 
     182       35460 :     ExecReadyExpr(state);
     183             : 
     184       35460 :     return state;
     185             : }
     186             : 
     187             : /*
     188             :  * ExecInitQual: prepare a qual for execution by ExecQual
     189             :  *
     190             :  * Prepares for the evaluation of a conjunctive boolean expression (qual list
     191             :  * with implicit AND semantics) that returns true if none of the
     192             :  * subexpressions are false.
     193             :  *
     194             :  * We must return true if the list is empty.  Since that's a very common case,
     195             :  * we optimize it a bit further by translating to a NULL ExprState pointer
     196             :  * rather than setting up an ExprState that computes constant TRUE.  (Some
     197             :  * especially hot-spot callers of ExecQual detect this and avoid calling
     198             :  * ExecQual at all.)
     199             :  *
     200             :  * If any of the subexpressions yield NULL, then the result of the conjunction
     201             :  * is false.  This makes ExecQual primarily useful for evaluating WHERE
     202             :  * clauses, since SQL specifies that tuples with null WHERE results do not
     203             :  * get selected.
     204             :  */
     205             : ExprState *
     206      919056 : ExecInitQual(List *qual, PlanState *parent)
     207             : {
     208             :     ExprState  *state;
     209      919056 :     ExprEvalStep scratch = {0};
     210      919056 :     List       *adjust_jumps = NIL;
     211             :     ListCell   *lc;
     212             : 
     213             :     /* short-circuit (here and in ExecQual) for empty restriction list */
     214      919056 :     if (qual == NIL)
     215      679686 :         return NULL;
     216             : 
     217             :     Assert(IsA(qual, List));
     218             : 
     219      239370 :     state = makeNode(ExprState);
     220      239370 :     state->expr = (Expr *) qual;
     221      239370 :     state->parent = parent;
     222      239370 :     state->ext_params = NULL;
     223             : 
     224             :     /* mark expression as to be used with ExecQual() */
     225      239370 :     state->flags = EEO_FLAG_IS_QUAL;
     226             : 
     227             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     228      239370 :     ExecInitExprSlots(state, (Node *) qual);
     229             : 
     230             :     /*
     231             :      * ExecQual() needs to return false for an expression returning NULL. That
     232             :      * allows us to short-circuit the evaluation the first time a NULL is
     233             :      * encountered.  As qual evaluation is a hot-path this warrants using a
     234             :      * special opcode for qual evaluation that's simpler than BOOL_AND (which
     235             :      * has more complex NULL handling).
     236             :      */
     237      239370 :     scratch.opcode = EEOP_QUAL;
     238             : 
     239             :     /*
     240             :      * We can use ExprState's resvalue/resnull as target for each qual expr.
     241             :      */
     242      239370 :     scratch.resvalue = &state->resvalue;
     243      239370 :     scratch.resnull = &state->resnull;
     244             : 
     245      531050 :     foreach(lc, qual)
     246             :     {
     247      291680 :         Expr       *node = (Expr *) lfirst(lc);
     248             : 
     249             :         /* first evaluate expression */
     250      291680 :         ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     251             : 
     252             :         /* then emit EEOP_QUAL to detect if it's false (or null) */
     253      291680 :         scratch.d.qualexpr.jumpdone = -1;
     254      291680 :         ExprEvalPushStep(state, &scratch);
     255      291680 :         adjust_jumps = lappend_int(adjust_jumps,
     256      291680 :                                    state->steps_len - 1);
     257             :     }
     258             : 
     259             :     /* adjust jump targets */
     260      531050 :     foreach(lc, adjust_jumps)
     261             :     {
     262      291680 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
     263             : 
     264             :         Assert(as->opcode == EEOP_QUAL);
     265             :         Assert(as->d.qualexpr.jumpdone == -1);
     266      291680 :         as->d.qualexpr.jumpdone = state->steps_len;
     267             :     }
     268             : 
     269             :     /*
     270             :      * At the end, we don't need to do anything more.  The last qual expr must
     271             :      * have yielded TRUE, and since its result is stored in the desired output
     272             :      * location, we're done.
     273             :      */
     274      239370 :     scratch.opcode = EEOP_DONE;
     275      239370 :     ExprEvalPushStep(state, &scratch);
     276             : 
     277      239370 :     ExecReadyExpr(state);
     278             : 
     279      239370 :     return state;
     280             : }
     281             : 
     282             : /*
     283             :  * ExecInitCheck: prepare a check constraint for execution by ExecCheck
     284             :  *
     285             :  * This is much like ExecInitQual/ExecQual, except that a null result from
     286             :  * the conjunction is treated as TRUE.  This behavior is appropriate for
     287             :  * evaluating CHECK constraints, since SQL specifies that NULL constraint
     288             :  * conditions are not failures.
     289             :  *
     290             :  * Note that like ExecInitQual, this expects input in implicit-AND format.
     291             :  * Users of ExecCheck that have expressions in normal explicit-AND format
     292             :  * can just apply ExecInitExpr to produce suitable input for ExecCheck.
     293             :  */
     294             : ExprState *
     295        1060 : ExecInitCheck(List *qual, PlanState *parent)
     296             : {
     297             :     /* short-circuit (here and in ExecCheck) for empty restriction list */
     298        1060 :     if (qual == NIL)
     299           0 :         return NULL;
     300             : 
     301             :     Assert(IsA(qual, List));
     302             : 
     303             :     /*
     304             :      * Just convert the implicit-AND list to an explicit AND (if there's more
     305             :      * than one entry), and compile normally.  Unlike ExecQual, we can't
     306             :      * short-circuit on NULL results, so the regular AND behavior is needed.
     307             :      */
     308        1060 :     return ExecInitExpr(make_ands_explicit(qual), parent);
     309             : }
     310             : 
     311             : /*
     312             :  * Call ExecInitExpr() on a list of expressions, return a list of ExprStates.
     313             :  */
     314             : List *
     315      294178 : ExecInitExprList(List *nodes, PlanState *parent)
     316             : {
     317      294178 :     List       *result = NIL;
     318             :     ListCell   *lc;
     319             : 
     320      505318 :     foreach(lc, nodes)
     321             :     {
     322      211140 :         Expr       *e = lfirst(lc);
     323             : 
     324      211140 :         result = lappend(result, ExecInitExpr(e, parent));
     325             :     }
     326             : 
     327      294178 :     return result;
     328             : }
     329             : 
     330             : /*
     331             :  *      ExecBuildProjectionInfo
     332             :  *
     333             :  * Build a ProjectionInfo node for evaluating the given tlist in the given
     334             :  * econtext, and storing the result into the tuple slot.  (Caller must have
     335             :  * ensured that tuple slot has a descriptor matching the tlist!)
     336             :  *
     337             :  * inputDesc can be NULL, but if it is not, we check to see whether simple
     338             :  * Vars in the tlist match the descriptor.  It is important to provide
     339             :  * inputDesc for relation-scan plan nodes, as a cross check that the relation
     340             :  * hasn't been changed since the plan was made.  At higher levels of a plan,
     341             :  * there is no need to recheck.
     342             :  *
     343             :  * This is implemented by internally building an ExprState that performs the
     344             :  * whole projection in one go.
     345             :  *
     346             :  * Caution: before PG v10, the targetList was a list of ExprStates; now it
     347             :  * should be the planner-created targetlist, since we do the compilation here.
     348             :  */
     349             : ProjectionInfo *
     350      379144 : ExecBuildProjectionInfo(List *targetList,
     351             :                         ExprContext *econtext,
     352             :                         TupleTableSlot *slot,
     353             :                         PlanState *parent,
     354             :                         TupleDesc inputDesc)
     355             : {
     356      379144 :     ProjectionInfo *projInfo = makeNode(ProjectionInfo);
     357             :     ExprState  *state;
     358      379144 :     ExprEvalStep scratch = {0};
     359             :     ListCell   *lc;
     360             : 
     361      379144 :     projInfo->pi_exprContext = econtext;
     362             :     /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
     363      379144 :     projInfo->pi_state.tag.type = T_ExprState;
     364      379144 :     state = &projInfo->pi_state;
     365      379144 :     state->expr = (Expr *) targetList;
     366      379144 :     state->parent = parent;
     367      379144 :     state->ext_params = NULL;
     368             : 
     369      379144 :     state->resultslot = slot;
     370             : 
     371             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     372      379144 :     ExecInitExprSlots(state, (Node *) targetList);
     373             : 
     374             :     /* Now compile each tlist column */
     375     1660420 :     foreach(lc, targetList)
     376             :     {
     377     1281306 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     378     1281306 :         Var        *variable = NULL;
     379     1281306 :         AttrNumber  attnum = 0;
     380     1281306 :         bool        isSafeVar = false;
     381             : 
     382             :         /*
     383             :          * If tlist expression is a safe non-system Var, use the fast-path
     384             :          * ASSIGN_*_VAR opcodes.  "Safe" means that we don't need to apply
     385             :          * CheckVarSlotCompatibility() during plan startup.  If a source slot
     386             :          * was provided, we make the equivalent tests here; if a slot was not
     387             :          * provided, we assume that no check is needed because we're dealing
     388             :          * with a non-relation-scan-level expression.
     389             :          */
     390     2562612 :         if (tle->expr != NULL &&
     391     2060836 :             IsA(tle->expr, Var) &&
     392      779530 :             ((Var *) tle->expr)->varattno > 0)
     393             :         {
     394             :             /* Non-system Var, but how safe is it? */
     395      721450 :             variable = (Var *) tle->expr;
     396      721450 :             attnum = variable->varattno;
     397             : 
     398      721450 :             if (inputDesc == NULL)
     399      346476 :                 isSafeVar = true;   /* can't check, just assume OK */
     400      374974 :             else if (attnum <= inputDesc->natts)
     401             :             {
     402      374696 :                 Form_pg_attribute attr = TupleDescAttr(inputDesc, attnum - 1);
     403             : 
     404             :                 /*
     405             :                  * If user attribute is dropped or has a type mismatch, don't
     406             :                  * use ASSIGN_*_VAR.  Instead let the normal expression
     407             :                  * machinery handle it (which'll possibly error out).
     408             :                  */
     409      374696 :                 if (!attr->attisdropped && variable->vartype == attr->atttypid)
     410             :                 {
     411      374668 :                     isSafeVar = true;
     412             :                 }
     413             :             }
     414             :         }
     415             : 
     416     1281306 :         if (isSafeVar)
     417             :         {
     418             :             /* Fast-path: just generate an EEOP_ASSIGN_*_VAR step */
     419      721144 :             switch (variable->varno)
     420             :             {
     421             :                 case INNER_VAR:
     422             :                     /* get the tuple from the inner node */
     423       98520 :                     scratch.opcode = EEOP_ASSIGN_INNER_VAR;
     424       98520 :                     break;
     425             : 
     426             :                 case OUTER_VAR:
     427             :                     /* get the tuple from the outer node */
     428      247582 :                     scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
     429      247582 :                     break;
     430             : 
     431             :                     /* INDEX_VAR is handled by default case */
     432             : 
     433             :                 default:
     434             :                     /* get the tuple from the relation being scanned */
     435      375042 :                     scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
     436      375042 :                     break;
     437             :             }
     438             : 
     439      721144 :             scratch.d.assign_var.attnum = attnum - 1;
     440      721144 :             scratch.d.assign_var.resultnum = tle->resno - 1;
     441      721144 :             ExprEvalPushStep(state, &scratch);
     442             :         }
     443             :         else
     444             :         {
     445             :             /*
     446             :              * Otherwise, compile the column expression normally.
     447             :              *
     448             :              * We can't tell the expression to evaluate directly into the
     449             :              * result slot, as the result slot (and the exprstate for that
     450             :              * matter) can change between executions.  We instead evaluate
     451             :              * into the ExprState's resvalue/resnull and then move.
     452             :              */
     453      560162 :             ExecInitExprRec(tle->expr, state,
     454             :                             &state->resvalue, &state->resnull);
     455             : 
     456             :             /*
     457             :              * Column might be referenced multiple times in upper nodes, so
     458             :              * force value to R/O - but only if it could be an expanded datum.
     459             :              */
     460      560132 :             if (get_typlen(exprType((Node *) tle->expr)) == -1)
     461      242750 :                 scratch.opcode = EEOP_ASSIGN_TMP_MAKE_RO;
     462             :             else
     463      317382 :                 scratch.opcode = EEOP_ASSIGN_TMP;
     464      560132 :             scratch.d.assign_tmp.resultnum = tle->resno - 1;
     465      560132 :             ExprEvalPushStep(state, &scratch);
     466             :         }
     467             :     }
     468             : 
     469      379114 :     scratch.opcode = EEOP_DONE;
     470      379114 :     ExprEvalPushStep(state, &scratch);
     471             : 
     472      379114 :     ExecReadyExpr(state);
     473             : 
     474      379114 :     return projInfo;
     475             : }
     476             : 
     477             : /*
     478             :  * ExecPrepareExpr --- initialize for expression execution outside a normal
     479             :  * Plan tree context.
     480             :  *
     481             :  * This differs from ExecInitExpr in that we don't assume the caller is
     482             :  * already running in the EState's per-query context.  Also, we run the
     483             :  * passed expression tree through expression_planner() to prepare it for
     484             :  * execution.  (In ordinary Plan trees the regular planning process will have
     485             :  * made the appropriate transformations on expressions, but for standalone
     486             :  * expressions this won't have happened.)
     487             :  */
     488             : ExprState *
     489        5692 : ExecPrepareExpr(Expr *node, EState *estate)
     490             : {
     491             :     ExprState  *result;
     492             :     MemoryContext oldcontext;
     493             : 
     494        5692 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     495             : 
     496        5692 :     node = expression_planner(node);
     497             : 
     498        5692 :     result = ExecInitExpr(node, NULL);
     499             : 
     500        5692 :     MemoryContextSwitchTo(oldcontext);
     501             : 
     502        5692 :     return result;
     503             : }
     504             : 
     505             : /*
     506             :  * ExecPrepareQual --- initialize for qual execution outside a normal
     507             :  * Plan tree context.
     508             :  *
     509             :  * This differs from ExecInitQual in that we don't assume the caller is
     510             :  * already running in the EState's per-query context.  Also, we run the
     511             :  * passed expression tree through expression_planner() to prepare it for
     512             :  * execution.  (In ordinary Plan trees the regular planning process will have
     513             :  * made the appropriate transformations on expressions, but for standalone
     514             :  * expressions this won't have happened.)
     515             :  */
     516             : ExprState *
     517       72356 : ExecPrepareQual(List *qual, EState *estate)
     518             : {
     519             :     ExprState  *result;
     520             :     MemoryContext oldcontext;
     521             : 
     522       72356 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     523             : 
     524       72356 :     qual = (List *) expression_planner((Expr *) qual);
     525             : 
     526       72356 :     result = ExecInitQual(qual, NULL);
     527             : 
     528       72356 :     MemoryContextSwitchTo(oldcontext);
     529             : 
     530       72356 :     return result;
     531             : }
     532             : 
     533             : /*
     534             :  * ExecPrepareCheck -- initialize check constraint for execution outside a
     535             :  * normal Plan tree context.
     536             :  *
     537             :  * See ExecPrepareExpr() and ExecInitCheck() for details.
     538             :  */
     539             : ExprState *
     540        1060 : ExecPrepareCheck(List *qual, EState *estate)
     541             : {
     542             :     ExprState  *result;
     543             :     MemoryContext oldcontext;
     544             : 
     545        1060 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     546             : 
     547        1060 :     qual = (List *) expression_planner((Expr *) qual);
     548             : 
     549        1060 :     result = ExecInitCheck(qual, NULL);
     550             : 
     551        1060 :     MemoryContextSwitchTo(oldcontext);
     552             : 
     553        1060 :     return result;
     554             : }
     555             : 
     556             : /*
     557             :  * Call ExecPrepareExpr() on each member of a list of Exprs, and return
     558             :  * a list of ExprStates.
     559             :  *
     560             :  * See ExecPrepareExpr() for details.
     561             :  */
     562             : List *
     563        1848 : ExecPrepareExprList(List *nodes, EState *estate)
     564             : {
     565        1848 :     List       *result = NIL;
     566             :     MemoryContext oldcontext;
     567             :     ListCell   *lc;
     568             : 
     569             :     /* Ensure that the list cell nodes are in the right context too */
     570        1848 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     571             : 
     572        4212 :     foreach(lc, nodes)
     573             :     {
     574        2364 :         Expr       *e = (Expr *) lfirst(lc);
     575             : 
     576        2364 :         result = lappend(result, ExecPrepareExpr(e, estate));
     577             :     }
     578             : 
     579        1848 :     MemoryContextSwitchTo(oldcontext);
     580             : 
     581        1848 :     return result;
     582             : }
     583             : 
     584             : /*
     585             :  * ExecCheck - evaluate a check constraint
     586             :  *
     587             :  * For check constraints, a null result is taken as TRUE, ie the constraint
     588             :  * passes.
     589             :  *
     590             :  * The check constraint may have been prepared with ExecInitCheck
     591             :  * (possibly via ExecPrepareCheck) if the caller had it in implicit-AND
     592             :  * format, but a regular boolean expression prepared with ExecInitExpr or
     593             :  * ExecPrepareExpr works too.
     594             :  */
     595             : bool
     596      240136 : ExecCheck(ExprState *state, ExprContext *econtext)
     597             : {
     598             :     Datum       ret;
     599             :     bool        isnull;
     600             : 
     601             :     /* short-circuit (here and in ExecInitCheck) for empty restriction list */
     602      240136 :     if (state == NULL)
     603           0 :         return true;
     604             : 
     605             :     /* verify that expression was not compiled using ExecInitQual */
     606             :     Assert(!(state->flags & EEO_FLAG_IS_QUAL));
     607             : 
     608      240136 :     ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
     609             : 
     610      240136 :     if (isnull)
     611        1868 :         return true;
     612             : 
     613      238268 :     return DatumGetBool(ret);
     614             : }
     615             : 
     616             : /*
     617             :  * Prepare a compiled expression for execution.  This has to be called for
     618             :  * every ExprState before it can be executed.
     619             :  *
     620             :  * NB: While this currently only calls ExecReadyInterpretedExpr(),
     621             :  * this will likely get extended to further expression evaluation methods.
     622             :  * Therefore this should be used instead of directly calling
     623             :  * ExecReadyInterpretedExpr().
     624             :  */
     625             : static void
     626     1135832 : ExecReadyExpr(ExprState *state)
     627             : {
     628     1135832 :     if (jit_compile_expr(state))
     629        4622 :         return;
     630             : 
     631     1131210 :     ExecReadyInterpretedExpr(state);
     632             : }
     633             : 
     634             : /*
     635             :  * Append the steps necessary for the evaluation of node to ExprState->steps,
     636             :  * possibly recursing into sub-expressions of node.
     637             :  *
     638             :  * node - expression to evaluate
     639             :  * state - ExprState to whose ->steps to append the necessary operations
     640             :  * resv / resnull - where to store the result of the node into
     641             :  */
     642             : static void
     643     2453820 : ExecInitExprRec(Expr *node, ExprState *state,
     644             :                 Datum *resv, bool *resnull)
     645             : {
     646     2453820 :     ExprEvalStep scratch = {0};
     647             : 
     648             :     /* Guard against stack overflow due to overly complex expressions */
     649     2453820 :     check_stack_depth();
     650             : 
     651             :     /* Step's output location is always what the caller gave us */
     652             :     Assert(resv != NULL && resnull != NULL);
     653     2453820 :     scratch.resvalue = resv;
     654     2453820 :     scratch.resnull = resnull;
     655             : 
     656             :     /* cases should be ordered as they are in enum NodeTag */
     657     2453820 :     switch (nodeTag(node))
     658             :     {
     659             :         case T_Var:
     660             :             {
     661      765988 :                 Var        *variable = (Var *) node;
     662             : 
     663      765988 :                 if (variable->varattno == InvalidAttrNumber)
     664             :                 {
     665             :                     /* whole-row Var */
     666        2358 :                     ExecInitWholeRowVar(&scratch, variable, state);
     667             :                 }
     668      763630 :                 else if (variable->varattno <= 0)
     669             :                 {
     670             :                     /* system column */
     671       57952 :                     scratch.d.var.attnum = variable->varattno;
     672       57952 :                     scratch.d.var.vartype = variable->vartype;
     673       57952 :                     switch (variable->varno)
     674             :                     {
     675             :                         case INNER_VAR:
     676           4 :                             scratch.opcode = EEOP_INNER_SYSVAR;
     677           4 :                             break;
     678             :                         case OUTER_VAR:
     679           8 :                             scratch.opcode = EEOP_OUTER_SYSVAR;
     680           8 :                             break;
     681             : 
     682             :                             /* INDEX_VAR is handled by default case */
     683             : 
     684             :                         default:
     685       57940 :                             scratch.opcode = EEOP_SCAN_SYSVAR;
     686       57940 :                             break;
     687             :                     }
     688             :                 }
     689             :                 else
     690             :                 {
     691             :                     /* regular user column */
     692      705678 :                     scratch.d.var.attnum = variable->varattno - 1;
     693      705678 :                     scratch.d.var.vartype = variable->vartype;
     694      705678 :                     switch (variable->varno)
     695             :                     {
     696             :                         case INNER_VAR:
     697      141634 :                             scratch.opcode = EEOP_INNER_VAR;
     698      141634 :                             break;
     699             :                         case OUTER_VAR:
     700      190176 :                             scratch.opcode = EEOP_OUTER_VAR;
     701      190176 :                             break;
     702             : 
     703             :                             /* INDEX_VAR is handled by default case */
     704             : 
     705             :                         default:
     706      373868 :                             scratch.opcode = EEOP_SCAN_VAR;
     707      373868 :                             break;
     708             :                     }
     709             :                 }
     710             : 
     711      765988 :                 ExprEvalPushStep(state, &scratch);
     712      765988 :                 break;
     713             :             }
     714             : 
     715             :         case T_Const:
     716             :             {
     717      462748 :                 Const      *con = (Const *) node;
     718             : 
     719      462748 :                 scratch.opcode = EEOP_CONST;
     720      462748 :                 scratch.d.constval.value = con->constvalue;
     721      462748 :                 scratch.d.constval.isnull = con->constisnull;
     722             : 
     723      462748 :                 ExprEvalPushStep(state, &scratch);
     724      462748 :                 break;
     725             :             }
     726             : 
     727             :         case T_Param:
     728             :             {
     729      269366 :                 Param      *param = (Param *) node;
     730             :                 ParamListInfo params;
     731             : 
     732      269366 :                 switch (param->paramkind)
     733             :                 {
     734             :                     case PARAM_EXEC:
     735      161080 :                         scratch.opcode = EEOP_PARAM_EXEC;
     736      161080 :                         scratch.d.param.paramid = param->paramid;
     737      161080 :                         scratch.d.param.paramtype = param->paramtype;
     738      161080 :                         ExprEvalPushStep(state, &scratch);
     739      161080 :                         break;
     740             :                     case PARAM_EXTERN:
     741             : 
     742             :                         /*
     743             :                          * If we have a relevant ParamCompileHook, use it;
     744             :                          * otherwise compile a standard EEOP_PARAM_EXTERN
     745             :                          * step.  ext_params, if supplied, takes precedence
     746             :                          * over info from the parent node's EState (if any).
     747             :                          */
     748      108286 :                         if (state->ext_params)
     749       32712 :                             params = state->ext_params;
     750      151008 :                         else if (state->parent &&
     751       75434 :                                  state->parent->state)
     752       75434 :                             params = state->parent->state->es_param_list_info;
     753             :                         else
     754         140 :                             params = NULL;
     755      108286 :                         if (params && params->paramCompile)
     756             :                         {
     757       50164 :                             params->paramCompile(params, param, state,
     758             :                                                  resv, resnull);
     759             :                         }
     760             :                         else
     761             :                         {
     762       58122 :                             scratch.opcode = EEOP_PARAM_EXTERN;
     763       58122 :                             scratch.d.param.paramid = param->paramid;
     764       58122 :                             scratch.d.param.paramtype = param->paramtype;
     765       58122 :                             ExprEvalPushStep(state, &scratch);
     766             :                         }
     767      108286 :                         break;
     768             :                     default:
     769           0 :                         elog(ERROR, "unrecognized paramkind: %d",
     770             :                              (int) param->paramkind);
     771             :                         break;
     772             :                 }
     773      269366 :                 break;
     774             :             }
     775             : 
     776             :         case T_Aggref:
     777             :             {
     778       31372 :                 Aggref     *aggref = (Aggref *) node;
     779       31372 :                 AggrefExprState *astate = makeNode(AggrefExprState);
     780             : 
     781       31372 :                 scratch.opcode = EEOP_AGGREF;
     782       31372 :                 scratch.d.aggref.astate = astate;
     783       31372 :                 astate->aggref = aggref;
     784             : 
     785       31372 :                 if (state->parent && IsA(state->parent, AggState))
     786       31372 :                 {
     787       31372 :                     AggState   *aggstate = (AggState *) state->parent;
     788             : 
     789       31372 :                     aggstate->aggs = lcons(astate, aggstate->aggs);
     790       31372 :                     aggstate->numaggs++;
     791             :                 }
     792             :                 else
     793             :                 {
     794             :                     /* planner messed up */
     795           0 :                     elog(ERROR, "Aggref found in non-Agg plan node");
     796             :                 }
     797             : 
     798       31372 :                 ExprEvalPushStep(state, &scratch);
     799       31372 :                 break;
     800             :             }
     801             : 
     802             :         case T_GroupingFunc:
     803             :             {
     804         168 :                 GroupingFunc *grp_node = (GroupingFunc *) node;
     805             :                 Agg        *agg;
     806             : 
     807         336 :                 if (!state->parent || !IsA(state->parent, AggState) ||
     808         168 :                     !IsA(state->parent->plan, Agg))
     809           0 :                     elog(ERROR, "GroupingFunc found in non-Agg plan node");
     810             : 
     811         168 :                 scratch.opcode = EEOP_GROUPING_FUNC;
     812         168 :                 scratch.d.grouping_func.parent = (AggState *) state->parent;
     813             : 
     814         168 :                 agg = (Agg *) (state->parent->plan);
     815             : 
     816         168 :                 if (agg->groupingSets)
     817         132 :                     scratch.d.grouping_func.clauses = grp_node->cols;
     818             :                 else
     819          36 :                     scratch.d.grouping_func.clauses = NIL;
     820             : 
     821         168 :                 ExprEvalPushStep(state, &scratch);
     822         168 :                 break;
     823             :             }
     824             : 
     825             :         case T_WindowFunc:
     826             :             {
     827        1372 :                 WindowFunc *wfunc = (WindowFunc *) node;
     828        1372 :                 WindowFuncExprState *wfstate = makeNode(WindowFuncExprState);
     829             : 
     830        1372 :                 wfstate->wfunc = wfunc;
     831             : 
     832        1372 :                 if (state->parent && IsA(state->parent, WindowAggState))
     833        1372 :                 {
     834        1372 :                     WindowAggState *winstate = (WindowAggState *) state->parent;
     835             :                     int         nfuncs;
     836             : 
     837        1372 :                     winstate->funcs = lcons(wfstate, winstate->funcs);
     838        1372 :                     nfuncs = ++winstate->numfuncs;
     839        1372 :                     if (wfunc->winagg)
     840         732 :                         winstate->numaggs++;
     841             : 
     842             :                     /* for now initialize agg using old style expressions */
     843        1372 :                     wfstate->args = ExecInitExprList(wfunc->args,
     844        1372 :                                                      state->parent);
     845        1372 :                     wfstate->aggfilter = ExecInitExpr(wfunc->aggfilter,
     846        1372 :                                                       state->parent);
     847             : 
     848             :                     /*
     849             :                      * Complain if the windowfunc's arguments contain any
     850             :                      * windowfuncs; nested window functions are semantically
     851             :                      * nonsensical.  (This should have been caught earlier,
     852             :                      * but we defend against it here anyway.)
     853             :                      */
     854        1372 :                     if (nfuncs != winstate->numfuncs)
     855           0 :                         ereport(ERROR,
     856             :                                 (errcode(ERRCODE_WINDOWING_ERROR),
     857             :                                  errmsg("window function calls cannot be nested")));
     858             :                 }
     859             :                 else
     860             :                 {
     861             :                     /* planner messed up */
     862           0 :                     elog(ERROR, "WindowFunc found in non-WindowAgg plan node");
     863             :                 }
     864             : 
     865        1372 :                 scratch.opcode = EEOP_WINDOW_FUNC;
     866        1372 :                 scratch.d.window_func.wfstate = wfstate;
     867        1372 :                 ExprEvalPushStep(state, &scratch);
     868        1372 :                 break;
     869             :             }
     870             : 
     871             :         case T_SubscriptingRef:
     872             :             {
     873        6416 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
     874             : 
     875        6416 :                 ExecInitSubscriptingRef(&scratch, sbsref, state, resv, resnull);
     876        6412 :                 break;
     877             :             }
     878             : 
     879             :         case T_FuncExpr:
     880             :             {
     881      258590 :                 FuncExpr   *func = (FuncExpr *) node;
     882             : 
     883      258590 :                 ExecInitFunc(&scratch, node,
     884             :                              func->args, func->funcid, func->inputcollid,
     885             :                              state);
     886      258552 :                 ExprEvalPushStep(state, &scratch);
     887      258552 :                 break;
     888             :             }
     889             : 
     890             :         case T_OpExpr:
     891             :             {
     892      381490 :                 OpExpr     *op = (OpExpr *) node;
     893             : 
     894      381490 :                 ExecInitFunc(&scratch, node,
     895             :                              op->args, op->opfuncid, op->inputcollid,
     896             :                              state);
     897      381490 :                 ExprEvalPushStep(state, &scratch);
     898      381490 :                 break;
     899             :             }
     900             : 
     901             :         case T_DistinctExpr:
     902             :             {
     903         510 :                 DistinctExpr *op = (DistinctExpr *) node;
     904             : 
     905         510 :                 ExecInitFunc(&scratch, node,
     906             :                              op->args, op->opfuncid, op->inputcollid,
     907             :                              state);
     908             : 
     909             :                 /*
     910             :                  * Change opcode of call instruction to EEOP_DISTINCT.
     911             :                  *
     912             :                  * XXX: historically we've not called the function usage
     913             :                  * pgstat infrastructure - that seems inconsistent given that
     914             :                  * we do so for normal function *and* operator evaluation.  If
     915             :                  * we decided to do that here, we'd probably want separate
     916             :                  * opcodes for FUSAGE or not.
     917             :                  */
     918         510 :                 scratch.opcode = EEOP_DISTINCT;
     919         510 :                 ExprEvalPushStep(state, &scratch);
     920         510 :                 break;
     921             :             }
     922             : 
     923             :         case T_NullIfExpr:
     924             :             {
     925          68 :                 NullIfExpr *op = (NullIfExpr *) node;
     926             : 
     927          68 :                 ExecInitFunc(&scratch, node,
     928             :                              op->args, op->opfuncid, op->inputcollid,
     929             :                              state);
     930             : 
     931             :                 /*
     932             :                  * Change opcode of call instruction to EEOP_NULLIF.
     933             :                  *
     934             :                  * XXX: historically we've not called the function usage
     935             :                  * pgstat infrastructure - that seems inconsistent given that
     936             :                  * we do so for normal function *and* operator evaluation.  If
     937             :                  * we decided to do that here, we'd probably want separate
     938             :                  * opcodes for FUSAGE or not.
     939             :                  */
     940          68 :                 scratch.opcode = EEOP_NULLIF;
     941          68 :                 ExprEvalPushStep(state, &scratch);
     942          68 :                 break;
     943             :             }
     944             : 
     945             :         case T_ScalarArrayOpExpr:
     946             :             {
     947       25174 :                 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
     948             :                 Expr       *scalararg;
     949             :                 Expr       *arrayarg;
     950             :                 FmgrInfo   *finfo;
     951             :                 FunctionCallInfo fcinfo;
     952             :                 AclResult   aclresult;
     953             : 
     954             :                 Assert(list_length(opexpr->args) == 2);
     955       25174 :                 scalararg = (Expr *) linitial(opexpr->args);
     956       25174 :                 arrayarg = (Expr *) lsecond(opexpr->args);
     957             : 
     958             :                 /* Check permission to call function */
     959       25174 :                 aclresult = pg_proc_aclcheck(opexpr->opfuncid,
     960             :                                              GetUserId(),
     961             :                                              ACL_EXECUTE);
     962       25174 :                 if (aclresult != ACLCHECK_OK)
     963           0 :                     aclcheck_error(aclresult, OBJECT_FUNCTION,
     964           0 :                                    get_func_name(opexpr->opfuncid));
     965       25174 :                 InvokeFunctionExecuteHook(opexpr->opfuncid);
     966             : 
     967             :                 /* Set up the primary fmgr lookup information */
     968       25174 :                 finfo = palloc0(sizeof(FmgrInfo));
     969       25174 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
     970       25174 :                 fmgr_info(opexpr->opfuncid, finfo);
     971       25174 :                 fmgr_info_set_expr((Node *) node, finfo);
     972       25174 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
     973             :                                          opexpr->inputcollid, NULL, NULL);
     974             : 
     975             :                 /* Evaluate scalar directly into left function argument */
     976       25174 :                 ExecInitExprRec(scalararg, state,
     977             :                                 &fcinfo->args[0].value, &fcinfo->args[0].isnull);
     978             : 
     979             :                 /*
     980             :                  * Evaluate array argument into our return value.  There's no
     981             :                  * danger in that, because the return value is guaranteed to
     982             :                  * be overwritten by EEOP_SCALARARRAYOP, and will not be
     983             :                  * passed to any other expression.
     984             :                  */
     985       25174 :                 ExecInitExprRec(arrayarg, state, resv, resnull);
     986             : 
     987             :                 /* And perform the operation */
     988       25174 :                 scratch.opcode = EEOP_SCALARARRAYOP;
     989       25174 :                 scratch.d.scalararrayop.element_type = InvalidOid;
     990       25174 :                 scratch.d.scalararrayop.useOr = opexpr->useOr;
     991       25174 :                 scratch.d.scalararrayop.finfo = finfo;
     992       25174 :                 scratch.d.scalararrayop.fcinfo_data = fcinfo;
     993       25174 :                 scratch.d.scalararrayop.fn_addr = finfo->fn_addr;
     994       25174 :                 ExprEvalPushStep(state, &scratch);
     995       25174 :                 break;
     996             :             }
     997             : 
     998             :         case T_BoolExpr:
     999             :             {
    1000       28324 :                 BoolExpr   *boolexpr = (BoolExpr *) node;
    1001       28324 :                 int         nargs = list_length(boolexpr->args);
    1002       28324 :                 List       *adjust_jumps = NIL;
    1003             :                 int         off;
    1004             :                 ListCell   *lc;
    1005             : 
    1006             :                 /* allocate scratch memory used by all steps of AND/OR */
    1007       28324 :                 if (boolexpr->boolop != NOT_EXPR)
    1008       16664 :                     scratch.d.boolexpr.anynull = (bool *) palloc(sizeof(bool));
    1009             : 
    1010             :                 /*
    1011             :                  * For each argument evaluate the argument itself, then
    1012             :                  * perform the bool operation's appropriate handling.
    1013             :                  *
    1014             :                  * We can evaluate each argument into our result area, since
    1015             :                  * the short-circuiting logic means we only need to remember
    1016             :                  * previous NULL values.
    1017             :                  *
    1018             :                  * AND/OR is split into separate STEP_FIRST (one) / STEP (zero
    1019             :                  * or more) / STEP_LAST (one) steps, as each of those has to
    1020             :                  * perform different work.  The FIRST/LAST split is valid
    1021             :                  * because AND/OR have at least two arguments.
    1022             :                  */
    1023       28324 :                 off = 0;
    1024       80050 :                 foreach(lc, boolexpr->args)
    1025             :                 {
    1026       51726 :                     Expr       *arg = (Expr *) lfirst(lc);
    1027             : 
    1028             :                     /* Evaluate argument into our output variable */
    1029       51726 :                     ExecInitExprRec(arg, state, resv, resnull);
    1030             : 
    1031             :                     /* Perform the appropriate step type */
    1032       51726 :                     switch (boolexpr->boolop)
    1033             :                     {
    1034             :                         case AND_EXPR:
    1035             :                             Assert(nargs >= 2);
    1036             : 
    1037       24872 :                             if (off == 0)
    1038       10408 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_FIRST;
    1039       14464 :                             else if (off + 1 == nargs)
    1040       10408 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_LAST;
    1041             :                             else
    1042        4056 :                                 scratch.opcode = EEOP_BOOL_AND_STEP;
    1043       24872 :                             break;
    1044             :                         case OR_EXPR:
    1045             :                             Assert(nargs >= 2);
    1046             : 
    1047       15194 :                             if (off == 0)
    1048        6256 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_FIRST;
    1049        8938 :                             else if (off + 1 == nargs)
    1050        6256 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_LAST;
    1051             :                             else
    1052        2682 :                                 scratch.opcode = EEOP_BOOL_OR_STEP;
    1053       15194 :                             break;
    1054             :                         case NOT_EXPR:
    1055             :                             Assert(nargs == 1);
    1056             : 
    1057       11660 :                             scratch.opcode = EEOP_BOOL_NOT_STEP;
    1058       11660 :                             break;
    1059             :                         default:
    1060           0 :                             elog(ERROR, "unrecognized boolop: %d",
    1061             :                                  (int) boolexpr->boolop);
    1062             :                             break;
    1063             :                     }
    1064             : 
    1065       51726 :                     scratch.d.boolexpr.jumpdone = -1;
    1066       51726 :                     ExprEvalPushStep(state, &scratch);
    1067       51726 :                     adjust_jumps = lappend_int(adjust_jumps,
    1068       51726 :                                                state->steps_len - 1);
    1069       51726 :                     off++;
    1070             :                 }
    1071             : 
    1072             :                 /* adjust jump targets */
    1073       80050 :                 foreach(lc, adjust_jumps)
    1074             :                 {
    1075       51726 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1076             : 
    1077             :                     Assert(as->d.boolexpr.jumpdone == -1);
    1078       51726 :                     as->d.boolexpr.jumpdone = state->steps_len;
    1079             :                 }
    1080             : 
    1081       28324 :                 break;
    1082             :             }
    1083             : 
    1084             :         case T_SubPlan:
    1085             :             {
    1086       34334 :                 SubPlan    *subplan = (SubPlan *) node;
    1087             :                 SubPlanState *sstate;
    1088             : 
    1089       34334 :                 if (!state->parent)
    1090           0 :                     elog(ERROR, "SubPlan found with no parent plan");
    1091             : 
    1092       34334 :                 sstate = ExecInitSubPlan(subplan, state->parent);
    1093             : 
    1094             :                 /* add SubPlanState nodes to state->parent->subPlan */
    1095       34334 :                 state->parent->subPlan = lappend(state->parent->subPlan,
    1096             :                                                  sstate);
    1097             : 
    1098       34334 :                 scratch.opcode = EEOP_SUBPLAN;
    1099       34334 :                 scratch.d.subplan.sstate = sstate;
    1100             : 
    1101       34334 :                 ExprEvalPushStep(state, &scratch);
    1102       34334 :                 break;
    1103             :             }
    1104             : 
    1105             :         case T_AlternativeSubPlan:
    1106             :             {
    1107        1166 :                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
    1108             :                 AlternativeSubPlanState *asstate;
    1109             : 
    1110        1166 :                 if (!state->parent)
    1111           0 :                     elog(ERROR, "AlternativeSubPlan found with no parent plan");
    1112             : 
    1113        1166 :                 asstate = ExecInitAlternativeSubPlan(asplan, state->parent);
    1114             : 
    1115        1166 :                 scratch.opcode = EEOP_ALTERNATIVE_SUBPLAN;
    1116        1166 :                 scratch.d.alternative_subplan.asstate = asstate;
    1117             : 
    1118        1166 :                 ExprEvalPushStep(state, &scratch);
    1119        1166 :                 break;
    1120             :             }
    1121             : 
    1122             :         case T_FieldSelect:
    1123             :             {
    1124        3636 :                 FieldSelect *fselect = (FieldSelect *) node;
    1125             : 
    1126             :                 /* evaluate row/record argument into result area */
    1127        3636 :                 ExecInitExprRec(fselect->arg, state, resv, resnull);
    1128             : 
    1129             :                 /* and extract field */
    1130        3636 :                 scratch.opcode = EEOP_FIELDSELECT;
    1131        3636 :                 scratch.d.fieldselect.fieldnum = fselect->fieldnum;
    1132        3636 :                 scratch.d.fieldselect.resulttype = fselect->resulttype;
    1133        3636 :                 scratch.d.fieldselect.argdesc = NULL;
    1134             : 
    1135        3636 :                 ExprEvalPushStep(state, &scratch);
    1136        3636 :                 break;
    1137             :             }
    1138             : 
    1139             :         case T_FieldStore:
    1140             :             {
    1141         152 :                 FieldStore *fstore = (FieldStore *) node;
    1142             :                 TupleDesc   tupDesc;
    1143             :                 TupleDesc  *descp;
    1144             :                 Datum      *values;
    1145             :                 bool       *nulls;
    1146             :                 int         ncolumns;
    1147             :                 ListCell   *l1,
    1148             :                            *l2;
    1149             : 
    1150             :                 /* find out the number of columns in the composite type */
    1151         152 :                 tupDesc = lookup_rowtype_tupdesc(fstore->resulttype, -1);
    1152         152 :                 ncolumns = tupDesc->natts;
    1153         152 :                 DecrTupleDescRefCount(tupDesc);
    1154             : 
    1155             :                 /* create workspace for column values */
    1156         152 :                 values = (Datum *) palloc(sizeof(Datum) * ncolumns);
    1157         152 :                 nulls = (bool *) palloc(sizeof(bool) * ncolumns);
    1158             : 
    1159             :                 /* create workspace for runtime tupdesc cache */
    1160         152 :                 descp = (TupleDesc *) palloc(sizeof(TupleDesc));
    1161         152 :                 *descp = NULL;
    1162             : 
    1163             :                 /* emit code to evaluate the composite input value */
    1164         152 :                 ExecInitExprRec(fstore->arg, state, resv, resnull);
    1165             : 
    1166             :                 /* next, deform the input tuple into our workspace */
    1167         152 :                 scratch.opcode = EEOP_FIELDSTORE_DEFORM;
    1168         152 :                 scratch.d.fieldstore.fstore = fstore;
    1169         152 :                 scratch.d.fieldstore.argdesc = descp;
    1170         152 :                 scratch.d.fieldstore.values = values;
    1171         152 :                 scratch.d.fieldstore.nulls = nulls;
    1172         152 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1173         152 :                 ExprEvalPushStep(state, &scratch);
    1174             : 
    1175             :                 /* evaluate new field values, store in workspace columns */
    1176         348 :                 forboth(l1, fstore->newvals, l2, fstore->fieldnums)
    1177             :                 {
    1178         196 :                     Expr       *e = (Expr *) lfirst(l1);
    1179         196 :                     AttrNumber  fieldnum = lfirst_int(l2);
    1180             :                     Datum      *save_innermost_caseval;
    1181             :                     bool       *save_innermost_casenull;
    1182             : 
    1183         196 :                     if (fieldnum <= 0 || fieldnum > ncolumns)
    1184           0 :                         elog(ERROR, "field number %d is out of range in FieldStore",
    1185             :                              fieldnum);
    1186             : 
    1187             :                     /*
    1188             :                      * Use the CaseTestExpr mechanism to pass down the old
    1189             :                      * value of the field being replaced; this is needed in
    1190             :                      * case the newval is itself a FieldStore or
    1191             :                      * SubscriptingRef that has to obtain and modify the old
    1192             :                      * value.  It's safe to reuse the CASE mechanism because
    1193             :                      * there cannot be a CASE between here and where the value
    1194             :                      * would be needed, and a field assignment can't be within
    1195             :                      * a CASE either.  (So saving and restoring
    1196             :                      * innermost_caseval is just paranoia, but let's do it
    1197             :                      * anyway.)
    1198             :                      *
    1199             :                      * Another non-obvious point is that it's safe to use the
    1200             :                      * field's values[]/nulls[] entries as both the caseval
    1201             :                      * source and the result address for this subexpression.
    1202             :                      * That's okay only because (1) both FieldStore and
    1203             :                      * ArrayRef evaluate their arg or refexpr inputs first,
    1204             :                      * and (2) any such CaseTestExpr is directly the arg or
    1205             :                      * refexpr input.  So any read of the caseval will occur
    1206             :                      * before there's a chance to overwrite it.  Also, if
    1207             :                      * multiple entries in the newvals/fieldnums lists target
    1208             :                      * the same field, they'll effectively be applied
    1209             :                      * left-to-right which is what we want.
    1210             :                      */
    1211         196 :                     save_innermost_caseval = state->innermost_caseval;
    1212         196 :                     save_innermost_casenull = state->innermost_casenull;
    1213         196 :                     state->innermost_caseval = &values[fieldnum - 1];
    1214         196 :                     state->innermost_casenull = &nulls[fieldnum - 1];
    1215             : 
    1216         392 :                     ExecInitExprRec(e, state,
    1217         196 :                                     &values[fieldnum - 1],
    1218         196 :                                     &nulls[fieldnum - 1]);
    1219             : 
    1220         196 :                     state->innermost_caseval = save_innermost_caseval;
    1221         196 :                     state->innermost_casenull = save_innermost_casenull;
    1222             :                 }
    1223             : 
    1224             :                 /* finally, form result tuple */
    1225         152 :                 scratch.opcode = EEOP_FIELDSTORE_FORM;
    1226         152 :                 scratch.d.fieldstore.fstore = fstore;
    1227         152 :                 scratch.d.fieldstore.argdesc = descp;
    1228         152 :                 scratch.d.fieldstore.values = values;
    1229         152 :                 scratch.d.fieldstore.nulls = nulls;
    1230         152 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1231         152 :                 ExprEvalPushStep(state, &scratch);
    1232         152 :                 break;
    1233             :             }
    1234             : 
    1235             :         case T_RelabelType:
    1236             :             {
    1237             :                 /* relabel doesn't need to do anything at runtime */
    1238       36090 :                 RelabelType *relabel = (RelabelType *) node;
    1239             : 
    1240       36090 :                 ExecInitExprRec(relabel->arg, state, resv, resnull);
    1241       36090 :                 break;
    1242             :             }
    1243             : 
    1244             :         case T_CoerceViaIO:
    1245             :             {
    1246        8050 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
    1247             :                 Oid         iofunc;
    1248             :                 bool        typisvarlena;
    1249             :                 Oid         typioparam;
    1250             :                 FunctionCallInfo fcinfo_in;
    1251             : 
    1252             :                 /* evaluate argument into step's result area */
    1253        8050 :                 ExecInitExprRec(iocoerce->arg, state, resv, resnull);
    1254             : 
    1255             :                 /*
    1256             :                  * Prepare both output and input function calls, to be
    1257             :                  * evaluated inside a single evaluation step for speed - this
    1258             :                  * can be a very common operation.
    1259             :                  *
    1260             :                  * We don't check permissions here as a type's input/output
    1261             :                  * function are assumed to be executable by everyone.
    1262             :                  */
    1263        8050 :                 scratch.opcode = EEOP_IOCOERCE;
    1264             : 
    1265             :                 /* lookup the source type's output function */
    1266        8050 :                 scratch.d.iocoerce.finfo_out = palloc0(sizeof(FmgrInfo));
    1267        8050 :                 scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
    1268             : 
    1269        8050 :                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
    1270             :                                   &iofunc, &typisvarlena);
    1271        8050 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_out);
    1272        8050 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_out);
    1273        8050 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_out,
    1274             :                                          scratch.d.iocoerce.finfo_out,
    1275             :                                          1, InvalidOid, NULL, NULL);
    1276             : 
    1277             :                 /* lookup the result type's input function */
    1278        8050 :                 scratch.d.iocoerce.finfo_in = palloc0(sizeof(FmgrInfo));
    1279        8050 :                 scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
    1280             : 
    1281        8050 :                 getTypeInputInfo(iocoerce->resulttype,
    1282             :                                  &iofunc, &typioparam);
    1283        8050 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_in);
    1284        8050 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_in);
    1285        8050 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_in,
    1286             :                                          scratch.d.iocoerce.finfo_in,
    1287             :                                          3, InvalidOid, NULL, NULL);
    1288             : 
    1289             :                 /*
    1290             :                  * We can preload the second and third arguments for the input
    1291             :                  * function, since they're constants.
    1292             :                  */
    1293        8050 :                 fcinfo_in = scratch.d.iocoerce.fcinfo_data_in;
    1294        8050 :                 fcinfo_in->args[1].value = ObjectIdGetDatum(typioparam);
    1295        8050 :                 fcinfo_in->args[1].isnull = false;
    1296        8050 :                 fcinfo_in->args[2].value = Int32GetDatum(-1);
    1297        8050 :                 fcinfo_in->args[2].isnull = false;
    1298             : 
    1299        8050 :                 ExprEvalPushStep(state, &scratch);
    1300        8050 :                 break;
    1301             :             }
    1302             : 
    1303             :         case T_ArrayCoerceExpr:
    1304             :             {
    1305        1618 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    1306             :                 Oid         resultelemtype;
    1307             :                 ExprState  *elemstate;
    1308             : 
    1309             :                 /* evaluate argument into step's result area */
    1310        1618 :                 ExecInitExprRec(acoerce->arg, state, resv, resnull);
    1311             : 
    1312        1618 :                 resultelemtype = get_element_type(acoerce->resulttype);
    1313        1618 :                 if (!OidIsValid(resultelemtype))
    1314           0 :                     ereport(ERROR,
    1315             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1316             :                              errmsg("target type is not an array")));
    1317             : 
    1318             :                 /*
    1319             :                  * Construct a sub-expression for the per-element expression;
    1320             :                  * but don't ready it until after we check it for triviality.
    1321             :                  * We assume it hasn't any Var references, but does have a
    1322             :                  * CaseTestExpr representing the source array element values.
    1323             :                  */
    1324        1618 :                 elemstate = makeNode(ExprState);
    1325        1618 :                 elemstate->expr = acoerce->elemexpr;
    1326        1618 :                 elemstate->parent = state->parent;
    1327        1618 :                 elemstate->ext_params = state->ext_params;
    1328             : 
    1329        1618 :                 elemstate->innermost_caseval = (Datum *) palloc(sizeof(Datum));
    1330        1618 :                 elemstate->innermost_casenull = (bool *) palloc(sizeof(bool));
    1331             : 
    1332        1618 :                 ExecInitExprRec(acoerce->elemexpr, elemstate,
    1333             :                                 &elemstate->resvalue, &elemstate->resnull);
    1334             : 
    1335        2990 :                 if (elemstate->steps_len == 1 &&
    1336        1376 :                     elemstate->steps[0].opcode == EEOP_CASE_TESTVAL)
    1337             :                 {
    1338             :                     /* Trivial, so we need no per-element work at runtime */
    1339        1376 :                     elemstate = NULL;
    1340             :                 }
    1341             :                 else
    1342             :                 {
    1343             :                     /* Not trivial, so append a DONE step */
    1344         238 :                     scratch.opcode = EEOP_DONE;
    1345         238 :                     ExprEvalPushStep(elemstate, &scratch);
    1346             :                     /* and ready the subexpression */
    1347         238 :                     ExecReadyExpr(elemstate);
    1348             :                 }
    1349             : 
    1350        1614 :                 scratch.opcode = EEOP_ARRAYCOERCE;
    1351        1614 :                 scratch.d.arraycoerce.elemexprstate = elemstate;
    1352        1614 :                 scratch.d.arraycoerce.resultelemtype = resultelemtype;
    1353             : 
    1354        1614 :                 if (elemstate)
    1355             :                 {
    1356             :                     /* Set up workspace for array_map */
    1357         238 :                     scratch.d.arraycoerce.amstate =
    1358         238 :                         (ArrayMapState *) palloc0(sizeof(ArrayMapState));
    1359             :                 }
    1360             :                 else
    1361             :                 {
    1362             :                     /* Don't need workspace if there's no subexpression */
    1363        1376 :                     scratch.d.arraycoerce.amstate = NULL;
    1364             :                 }
    1365             : 
    1366        1614 :                 ExprEvalPushStep(state, &scratch);
    1367        1614 :                 break;
    1368             :             }
    1369             : 
    1370             :         case T_ConvertRowtypeExpr:
    1371             :             {
    1372         500 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
    1373             : 
    1374             :                 /* evaluate argument into step's result area */
    1375         500 :                 ExecInitExprRec(convert->arg, state, resv, resnull);
    1376             : 
    1377             :                 /* and push conversion step */
    1378         500 :                 scratch.opcode = EEOP_CONVERT_ROWTYPE;
    1379         500 :                 scratch.d.convert_rowtype.convert = convert;
    1380         500 :                 scratch.d.convert_rowtype.indesc = NULL;
    1381         500 :                 scratch.d.convert_rowtype.outdesc = NULL;
    1382         500 :                 scratch.d.convert_rowtype.map = NULL;
    1383         500 :                 scratch.d.convert_rowtype.initialized = false;
    1384             : 
    1385         500 :                 ExprEvalPushStep(state, &scratch);
    1386         500 :                 break;
    1387             :             }
    1388             : 
    1389             :             /* note that CaseWhen expressions are handled within this block */
    1390             :         case T_CaseExpr:
    1391             :             {
    1392       25986 :                 CaseExpr   *caseExpr = (CaseExpr *) node;
    1393       25986 :                 List       *adjust_jumps = NIL;
    1394       25986 :                 Datum      *caseval = NULL;
    1395       25986 :                 bool       *casenull = NULL;
    1396             :                 ListCell   *lc;
    1397             : 
    1398             :                 /*
    1399             :                  * If there's a test expression, we have to evaluate it and
    1400             :                  * save the value where the CaseTestExpr placeholders can find
    1401             :                  * it.
    1402             :                  */
    1403       25986 :                 if (caseExpr->arg != NULL)
    1404             :                 {
    1405             :                     /* Evaluate testexpr into caseval/casenull workspace */
    1406        1374 :                     caseval = palloc(sizeof(Datum));
    1407        1374 :                     casenull = palloc(sizeof(bool));
    1408             : 
    1409        1374 :                     ExecInitExprRec(caseExpr->arg, state,
    1410             :                                     caseval, casenull);
    1411             : 
    1412             :                     /*
    1413             :                      * Since value might be read multiple times, force to R/O
    1414             :                      * - but only if it could be an expanded datum.
    1415             :                      */
    1416        1374 :                     if (get_typlen(exprType((Node *) caseExpr->arg)) == -1)
    1417             :                     {
    1418             :                         /* change caseval in-place */
    1419          32 :                         scratch.opcode = EEOP_MAKE_READONLY;
    1420          32 :                         scratch.resvalue = caseval;
    1421          32 :                         scratch.resnull = casenull;
    1422          32 :                         scratch.d.make_readonly.value = caseval;
    1423          32 :                         scratch.d.make_readonly.isnull = casenull;
    1424          32 :                         ExprEvalPushStep(state, &scratch);
    1425             :                         /* restore normal settings of scratch fields */
    1426          32 :                         scratch.resvalue = resv;
    1427          32 :                         scratch.resnull = resnull;
    1428             :                     }
    1429             :                 }
    1430             : 
    1431             :                 /*
    1432             :                  * Prepare to evaluate each of the WHEN clauses in turn; as
    1433             :                  * soon as one is true we return the value of the
    1434             :                  * corresponding THEN clause.  If none are true then we return
    1435             :                  * the value of the ELSE clause, or NULL if there is none.
    1436             :                  */
    1437       56658 :                 foreach(lc, caseExpr->args)
    1438             :                 {
    1439       30672 :                     CaseWhen   *when = (CaseWhen *) lfirst(lc);
    1440             :                     Datum      *save_innermost_caseval;
    1441             :                     bool       *save_innermost_casenull;
    1442             :                     int         whenstep;
    1443             : 
    1444             :                     /*
    1445             :                      * Make testexpr result available to CaseTestExpr nodes
    1446             :                      * within the condition.  We must save and restore prior
    1447             :                      * setting of innermost_caseval fields, in case this node
    1448             :                      * is itself within a larger CASE.
    1449             :                      *
    1450             :                      * If there's no test expression, we don't actually need
    1451             :                      * to save and restore these fields; but it's less code to
    1452             :                      * just do so unconditionally.
    1453             :                      */
    1454       30672 :                     save_innermost_caseval = state->innermost_caseval;
    1455       30672 :                     save_innermost_casenull = state->innermost_casenull;
    1456       30672 :                     state->innermost_caseval = caseval;
    1457       30672 :                     state->innermost_casenull = casenull;
    1458             : 
    1459             :                     /* evaluate condition into CASE's result variables */
    1460       30672 :                     ExecInitExprRec(when->expr, state, resv, resnull);
    1461             : 
    1462       30672 :                     state->innermost_caseval = save_innermost_caseval;
    1463       30672 :                     state->innermost_casenull = save_innermost_casenull;
    1464             : 
    1465             :                     /* If WHEN result isn't true, jump to next CASE arm */
    1466       30672 :                     scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    1467       30672 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1468       30672 :                     ExprEvalPushStep(state, &scratch);
    1469       30672 :                     whenstep = state->steps_len - 1;
    1470             : 
    1471             :                     /*
    1472             :                      * If WHEN result is true, evaluate THEN result, storing
    1473             :                      * it into the CASE's result variables.
    1474             :                      */
    1475       30672 :                     ExecInitExprRec(when->result, state, resv, resnull);
    1476             : 
    1477             :                     /* Emit JUMP step to jump to end of CASE's code */
    1478       30672 :                     scratch.opcode = EEOP_JUMP;
    1479       30672 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1480       30672 :                     ExprEvalPushStep(state, &scratch);
    1481             : 
    1482             :                     /*
    1483             :                      * Don't know address for that jump yet, compute once the
    1484             :                      * whole CASE expression is built.
    1485             :                      */
    1486       30672 :                     adjust_jumps = lappend_int(adjust_jumps,
    1487       30672 :                                                state->steps_len - 1);
    1488             : 
    1489             :                     /*
    1490             :                      * But we can set WHEN test's jump target now, to make it
    1491             :                      * jump to the next WHEN subexpression or the ELSE.
    1492             :                      */
    1493       30672 :                     state->steps[whenstep].d.jump.jumpdone = state->steps_len;
    1494             :                 }
    1495             : 
    1496             :                 /* transformCaseExpr always adds a default */
    1497             :                 Assert(caseExpr->defresult);
    1498             : 
    1499             :                 /* evaluate ELSE expr into CASE's result variables */
    1500       25986 :                 ExecInitExprRec(caseExpr->defresult, state,
    1501             :                                 resv, resnull);
    1502             : 
    1503             :                 /* adjust jump targets */
    1504       56658 :                 foreach(lc, adjust_jumps)
    1505             :                 {
    1506       30672 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1507             : 
    1508             :                     Assert(as->opcode == EEOP_JUMP);
    1509             :                     Assert(as->d.jump.jumpdone == -1);
    1510       30672 :                     as->d.jump.jumpdone = state->steps_len;
    1511             :                 }
    1512             : 
    1513       25986 :                 break;
    1514             :             }
    1515             : 
    1516             :         case T_CaseTestExpr:
    1517             :             {
    1518             :                 /*
    1519             :                  * Read from location identified by innermost_caseval.  Note
    1520             :                  * that innermost_caseval could be NULL, if this node isn't
    1521             :                  * actually within a CaseExpr, ArrayCoerceExpr, etc structure.
    1522             :                  * That can happen because some parts of the system abuse
    1523             :                  * CaseTestExpr to cause a read of a value externally supplied
    1524             :                  * in econtext->caseValue_datum.  We'll take care of that
    1525             :                  * scenario at runtime.
    1526             :                  */
    1527        8296 :                 scratch.opcode = EEOP_CASE_TESTVAL;
    1528        8296 :                 scratch.d.casetest.value = state->innermost_caseval;
    1529        8296 :                 scratch.d.casetest.isnull = state->innermost_casenull;
    1530             : 
    1531        8296 :                 ExprEvalPushStep(state, &scratch);
    1532        8296 :                 break;
    1533             :             }
    1534             : 
    1535             :         case T_ArrayExpr:
    1536             :             {
    1537       11998 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
    1538       11998 :                 int         nelems = list_length(arrayexpr->elements);
    1539             :                 ListCell   *lc;
    1540             :                 int         elemoff;
    1541             : 
    1542             :                 /*
    1543             :                  * Evaluate by computing each element, and then forming the
    1544             :                  * array.  Elements are computed into scratch arrays
    1545             :                  * associated with the ARRAYEXPR step.
    1546             :                  */
    1547       11998 :                 scratch.opcode = EEOP_ARRAYEXPR;
    1548       11998 :                 scratch.d.arrayexpr.elemvalues =
    1549       11998 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    1550       11998 :                 scratch.d.arrayexpr.elemnulls =
    1551       11998 :                     (bool *) palloc(sizeof(bool) * nelems);
    1552       11998 :                 scratch.d.arrayexpr.nelems = nelems;
    1553             : 
    1554             :                 /* fill remaining fields of step */
    1555       11998 :                 scratch.d.arrayexpr.multidims = arrayexpr->multidims;
    1556       11998 :                 scratch.d.arrayexpr.elemtype = arrayexpr->element_typeid;
    1557             : 
    1558             :                 /* do one-time catalog lookup for type info */
    1559       11998 :                 get_typlenbyvalalign(arrayexpr->element_typeid,
    1560             :                                      &scratch.d.arrayexpr.elemlength,
    1561             :                                      &scratch.d.arrayexpr.elembyval,
    1562             :                                      &scratch.d.arrayexpr.elemalign);
    1563             : 
    1564             :                 /* prepare to evaluate all arguments */
    1565       11998 :                 elemoff = 0;
    1566       45816 :                 foreach(lc, arrayexpr->elements)
    1567             :                 {
    1568       33818 :                     Expr       *e = (Expr *) lfirst(lc);
    1569             : 
    1570       67636 :                     ExecInitExprRec(e, state,
    1571       33818 :                                     &scratch.d.arrayexpr.elemvalues[elemoff],
    1572       33818 :                                     &scratch.d.arrayexpr.elemnulls[elemoff]);
    1573       33818 :                     elemoff++;
    1574             :                 }
    1575             : 
    1576             :                 /* and then collect all into an array */
    1577       11998 :                 ExprEvalPushStep(state, &scratch);
    1578       11998 :                 break;
    1579             :             }
    1580             : 
    1581             :         case T_RowExpr:
    1582             :             {
    1583        2894 :                 RowExpr    *rowexpr = (RowExpr *) node;
    1584        2894 :                 int         nelems = list_length(rowexpr->args);
    1585             :                 TupleDesc   tupdesc;
    1586             :                 int         i;
    1587             :                 ListCell   *l;
    1588             : 
    1589             :                 /* Build tupdesc to describe result tuples */
    1590        2894 :                 if (rowexpr->row_typeid == RECORDOID)
    1591             :                 {
    1592             :                     /* generic record, use types of given expressions */
    1593        1336 :                     tupdesc = ExecTypeFromExprList(rowexpr->args);
    1594             :                 }
    1595             :                 else
    1596             :                 {
    1597             :                     /* it's been cast to a named type, use that */
    1598        1558 :                     tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
    1599             :                 }
    1600             :                 /* In either case, adopt RowExpr's column aliases */
    1601        2894 :                 ExecTypeSetColNames(tupdesc, rowexpr->colnames);
    1602             :                 /* Bless the tupdesc in case it's now of type RECORD */
    1603        2894 :                 BlessTupleDesc(tupdesc);
    1604             : 
    1605             :                 /*
    1606             :                  * In the named-type case, the tupdesc could have more columns
    1607             :                  * than are in the args list, since the type might have had
    1608             :                  * columns added since the ROW() was parsed.  We want those
    1609             :                  * extra columns to go to nulls, so we make sure that the
    1610             :                  * workspace arrays are large enough and then initialize any
    1611             :                  * extra columns to read as NULLs.
    1612             :                  */
    1613             :                 Assert(nelems <= tupdesc->natts);
    1614        2894 :                 nelems = Max(nelems, tupdesc->natts);
    1615             : 
    1616             :                 /*
    1617             :                  * Evaluate by first building datums for each field, and then
    1618             :                  * a final step forming the composite datum.
    1619             :                  */
    1620        2894 :                 scratch.opcode = EEOP_ROW;
    1621        2894 :                 scratch.d.row.tupdesc = tupdesc;
    1622             : 
    1623             :                 /* space for the individual field datums */
    1624        2894 :                 scratch.d.row.elemvalues =
    1625        2894 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    1626        2894 :                 scratch.d.row.elemnulls =
    1627        2894 :                     (bool *) palloc(sizeof(bool) * nelems);
    1628             :                 /* as explained above, make sure any extra columns are null */
    1629        2894 :                 memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
    1630             : 
    1631             :                 /* Set up evaluation, skipping any deleted columns */
    1632        2894 :                 i = 0;
    1633       10810 :                 foreach(l, rowexpr->args)
    1634             :                 {
    1635        7916 :                     Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    1636        7916 :                     Expr       *e = (Expr *) lfirst(l);
    1637             : 
    1638        7916 :                     if (!att->attisdropped)
    1639             :                     {
    1640             :                         /*
    1641             :                          * Guard against ALTER COLUMN TYPE on rowtype since
    1642             :                          * the RowExpr was created.  XXX should we check
    1643             :                          * typmod too?  Not sure we can be sure it'll be the
    1644             :                          * same.
    1645             :                          */
    1646        7898 :                         if (exprType((Node *) e) != att->atttypid)
    1647           0 :                             ereport(ERROR,
    1648             :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1649             :                                      errmsg("ROW() column has type %s instead of type %s",
    1650             :                                             format_type_be(exprType((Node *) e)),
    1651             :                                             format_type_be(att->atttypid))));
    1652             :                     }
    1653             :                     else
    1654             :                     {
    1655             :                         /*
    1656             :                          * Ignore original expression and insert a NULL. We
    1657             :                          * don't really care what type of NULL it is, so
    1658             :                          * always make an int4 NULL.
    1659             :                          */
    1660          18 :                         e = (Expr *) makeNullConst(INT4OID, -1, InvalidOid);
    1661             :                     }
    1662             : 
    1663             :                     /* Evaluate column expr into appropriate workspace slot */
    1664       15832 :                     ExecInitExprRec(e, state,
    1665        7916 :                                     &scratch.d.row.elemvalues[i],
    1666        7916 :                                     &scratch.d.row.elemnulls[i]);
    1667        7916 :                     i++;
    1668             :                 }
    1669             : 
    1670             :                 /* And finally build the row value */
    1671        2894 :                 ExprEvalPushStep(state, &scratch);
    1672        2894 :                 break;
    1673             :             }
    1674             : 
    1675             :         case T_RowCompareExpr:
    1676             :             {
    1677         112 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
    1678         112 :                 int         nopers = list_length(rcexpr->opnos);
    1679         112 :                 List       *adjust_jumps = NIL;
    1680             :                 ListCell   *l_left_expr,
    1681             :                            *l_right_expr,
    1682             :                            *l_opno,
    1683             :                            *l_opfamily,
    1684             :                            *l_inputcollid;
    1685             :                 ListCell   *lc;
    1686             : 
    1687             :                 /*
    1688             :                  * Iterate over each field, prepare comparisons.  To handle
    1689             :                  * NULL results, prepare jumps to after the expression.  If a
    1690             :                  * comparison yields a != 0 result, jump to the final step.
    1691             :                  */
    1692             :                 Assert(list_length(rcexpr->largs) == nopers);
    1693             :                 Assert(list_length(rcexpr->rargs) == nopers);
    1694             :                 Assert(list_length(rcexpr->opfamilies) == nopers);
    1695             :                 Assert(list_length(rcexpr->inputcollids) == nopers);
    1696             : 
    1697         372 :                 forfive(l_left_expr, rcexpr->largs,
    1698             :                         l_right_expr, rcexpr->rargs,
    1699             :                         l_opno, rcexpr->opnos,
    1700             :                         l_opfamily, rcexpr->opfamilies,
    1701             :                         l_inputcollid, rcexpr->inputcollids)
    1702             :                 {
    1703         260 :                     Expr       *left_expr = (Expr *) lfirst(l_left_expr);
    1704         260 :                     Expr       *right_expr = (Expr *) lfirst(l_right_expr);
    1705         260 :                     Oid         opno = lfirst_oid(l_opno);
    1706         260 :                     Oid         opfamily = lfirst_oid(l_opfamily);
    1707         260 :                     Oid         inputcollid = lfirst_oid(l_inputcollid);
    1708             :                     int         strategy;
    1709             :                     Oid         lefttype;
    1710             :                     Oid         righttype;
    1711             :                     Oid         proc;
    1712             :                     FmgrInfo   *finfo;
    1713             :                     FunctionCallInfo fcinfo;
    1714             : 
    1715         260 :                     get_op_opfamily_properties(opno, opfamily, false,
    1716             :                                                &strategy,
    1717             :                                                &lefttype,
    1718             :                                                &righttype);
    1719         260 :                     proc = get_opfamily_proc(opfamily,
    1720             :                                              lefttype,
    1721             :                                              righttype,
    1722             :                                              BTORDER_PROC);
    1723         260 :                     if (!OidIsValid(proc))
    1724           0 :                         elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
    1725             :                              BTORDER_PROC, lefttype, righttype, opfamily);
    1726             : 
    1727             :                     /* Set up the primary fmgr lookup information */
    1728         260 :                     finfo = palloc0(sizeof(FmgrInfo));
    1729         260 :                     fcinfo = palloc0(SizeForFunctionCallInfo(2));
    1730         260 :                     fmgr_info(proc, finfo);
    1731         260 :                     fmgr_info_set_expr((Node *) node, finfo);
    1732         260 :                     InitFunctionCallInfoData(*fcinfo, finfo, 2,
    1733             :                                              inputcollid, NULL, NULL);
    1734             : 
    1735             :                     /*
    1736             :                      * If we enforced permissions checks on index support
    1737             :                      * functions, we'd need to make a check here.  But the
    1738             :                      * index support machinery doesn't do that, and thus
    1739             :                      * neither does this code.
    1740             :                      */
    1741             : 
    1742             :                     /* evaluate left and right args directly into fcinfo */
    1743         260 :                     ExecInitExprRec(left_expr, state,
    1744             :                                     &fcinfo->args[0].value, &fcinfo->args[0].isnull);
    1745         260 :                     ExecInitExprRec(right_expr, state,
    1746             :                                     &fcinfo->args[1].value, &fcinfo->args[1].isnull);
    1747             : 
    1748         260 :                     scratch.opcode = EEOP_ROWCOMPARE_STEP;
    1749         260 :                     scratch.d.rowcompare_step.finfo = finfo;
    1750         260 :                     scratch.d.rowcompare_step.fcinfo_data = fcinfo;
    1751         260 :                     scratch.d.rowcompare_step.fn_addr = finfo->fn_addr;
    1752             :                     /* jump targets filled below */
    1753         260 :                     scratch.d.rowcompare_step.jumpnull = -1;
    1754         260 :                     scratch.d.rowcompare_step.jumpdone = -1;
    1755             : 
    1756         260 :                     ExprEvalPushStep(state, &scratch);
    1757         260 :                     adjust_jumps = lappend_int(adjust_jumps,
    1758         260 :                                                state->steps_len - 1);
    1759             :                 }
    1760             : 
    1761             :                 /*
    1762             :                  * We could have a zero-column rowtype, in which case the rows
    1763             :                  * necessarily compare equal.
    1764             :                  */
    1765         112 :                 if (nopers == 0)
    1766             :                 {
    1767           0 :                     scratch.opcode = EEOP_CONST;
    1768           0 :                     scratch.d.constval.value = Int32GetDatum(0);
    1769           0 :                     scratch.d.constval.isnull = false;
    1770           0 :                     ExprEvalPushStep(state, &scratch);
    1771             :                 }
    1772             : 
    1773             :                 /* Finally, examine the last comparison result */
    1774         112 :                 scratch.opcode = EEOP_ROWCOMPARE_FINAL;
    1775         112 :                 scratch.d.rowcompare_final.rctype = rcexpr->rctype;
    1776         112 :                 ExprEvalPushStep(state, &scratch);
    1777             : 
    1778             :                 /* adjust jump targetss */
    1779         372 :                 foreach(lc, adjust_jumps)
    1780             :                 {
    1781         260 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1782             : 
    1783             :                     Assert(as->opcode == EEOP_ROWCOMPARE_STEP);
    1784             :                     Assert(as->d.rowcompare_step.jumpdone == -1);
    1785             :                     Assert(as->d.rowcompare_step.jumpnull == -1);
    1786             : 
    1787             :                     /* jump to comparison evaluation */
    1788         260 :                     as->d.rowcompare_step.jumpdone = state->steps_len - 1;
    1789             :                     /* jump to the following expression */
    1790         260 :                     as->d.rowcompare_step.jumpnull = state->steps_len;
    1791             :                 }
    1792             : 
    1793         112 :                 break;
    1794             :             }
    1795             : 
    1796             :         case T_CoalesceExpr:
    1797             :             {
    1798       12066 :                 CoalesceExpr *coalesce = (CoalesceExpr *) node;
    1799       12066 :                 List       *adjust_jumps = NIL;
    1800             :                 ListCell   *lc;
    1801             : 
    1802             :                 /* We assume there's at least one arg */
    1803             :                 Assert(coalesce->args != NIL);
    1804             : 
    1805             :                 /*
    1806             :                  * Prepare evaluation of all coalesced arguments, after each
    1807             :                  * one push a step that short-circuits if not null.
    1808             :                  */
    1809       36190 :                 foreach(lc, coalesce->args)
    1810             :                 {
    1811       24124 :                     Expr       *e = (Expr *) lfirst(lc);
    1812             : 
    1813             :                     /* evaluate argument, directly into result datum */
    1814       24124 :                     ExecInitExprRec(e, state, resv, resnull);
    1815             : 
    1816             :                     /* if it's not null, skip to end of COALESCE expr */
    1817       24124 :                     scratch.opcode = EEOP_JUMP_IF_NOT_NULL;
    1818       24124 :                     scratch.d.jump.jumpdone = -1;   /* adjust later */
    1819       24124 :                     ExprEvalPushStep(state, &scratch);
    1820             : 
    1821       24124 :                     adjust_jumps = lappend_int(adjust_jumps,
    1822       24124 :                                                state->steps_len - 1);
    1823             :                 }
    1824             : 
    1825             :                 /*
    1826             :                  * No need to add a constant NULL return - we only can get to
    1827             :                  * the end of the expression if a NULL already is being
    1828             :                  * returned.
    1829             :                  */
    1830             : 
    1831             :                 /* adjust jump targets */
    1832       36190 :                 foreach(lc, adjust_jumps)
    1833             :                 {
    1834       24124 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1835             : 
    1836             :                     Assert(as->opcode == EEOP_JUMP_IF_NOT_NULL);
    1837             :                     Assert(as->d.jump.jumpdone == -1);
    1838       24124 :                     as->d.jump.jumpdone = state->steps_len;
    1839             :                 }
    1840             : 
    1841       12066 :                 break;
    1842             :             }
    1843             : 
    1844             :         case T_MinMaxExpr:
    1845             :             {
    1846        2160 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
    1847        2160 :                 int         nelems = list_length(minmaxexpr->args);
    1848             :                 TypeCacheEntry *typentry;
    1849             :                 FmgrInfo   *finfo;
    1850             :                 FunctionCallInfo fcinfo;
    1851             :                 ListCell   *lc;
    1852             :                 int         off;
    1853             : 
    1854             :                 /* Look up the btree comparison function for the datatype */
    1855        2160 :                 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
    1856             :                                              TYPECACHE_CMP_PROC);
    1857        2160 :                 if (!OidIsValid(typentry->cmp_proc))
    1858           0 :                     ereport(ERROR,
    1859             :                             (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1860             :                              errmsg("could not identify a comparison function for type %s",
    1861             :                                     format_type_be(minmaxexpr->minmaxtype))));
    1862             : 
    1863             :                 /*
    1864             :                  * If we enforced permissions checks on index support
    1865             :                  * functions, we'd need to make a check here.  But the index
    1866             :                  * support machinery doesn't do that, and thus neither does
    1867             :                  * this code.
    1868             :                  */
    1869             : 
    1870             :                 /* Perform function lookup */
    1871        2160 :                 finfo = palloc0(sizeof(FmgrInfo));
    1872        2160 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
    1873        2160 :                 fmgr_info(typentry->cmp_proc, finfo);
    1874        2160 :                 fmgr_info_set_expr((Node *) node, finfo);
    1875        2160 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
    1876             :                                          minmaxexpr->inputcollid, NULL, NULL);
    1877             : 
    1878        2160 :                 scratch.opcode = EEOP_MINMAX;
    1879             :                 /* allocate space to store arguments */
    1880        2160 :                 scratch.d.minmax.values =
    1881        2160 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    1882        2160 :                 scratch.d.minmax.nulls =
    1883        2160 :                     (bool *) palloc(sizeof(bool) * nelems);
    1884        2160 :                 scratch.d.minmax.nelems = nelems;
    1885             : 
    1886        2160 :                 scratch.d.minmax.op = minmaxexpr->op;
    1887        2160 :                 scratch.d.minmax.finfo = finfo;
    1888        2160 :                 scratch.d.minmax.fcinfo_data = fcinfo;
    1889             : 
    1890             :                 /* evaluate expressions into minmax->values/nulls */
    1891        2160 :                 off = 0;
    1892        6552 :                 foreach(lc, minmaxexpr->args)
    1893             :                 {
    1894        4392 :                     Expr       *e = (Expr *) lfirst(lc);
    1895             : 
    1896        8784 :                     ExecInitExprRec(e, state,
    1897        4392 :                                     &scratch.d.minmax.values[off],
    1898        4392 :                                     &scratch.d.minmax.nulls[off]);
    1899        4392 :                     off++;
    1900             :                 }
    1901             : 
    1902             :                 /* and push the final comparison */
    1903        2160 :                 ExprEvalPushStep(state, &scratch);
    1904        2160 :                 break;
    1905             :             }
    1906             : 
    1907             :         case T_SQLValueFunction:
    1908             :             {
    1909        2212 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
    1910             : 
    1911        2212 :                 scratch.opcode = EEOP_SQLVALUEFUNCTION;
    1912        2212 :                 scratch.d.sqlvaluefunction.svf = svf;
    1913             : 
    1914        2212 :                 ExprEvalPushStep(state, &scratch);
    1915        2212 :                 break;
    1916             :             }
    1917             : 
    1918             :         case T_XmlExpr:
    1919             :             {
    1920         356 :                 XmlExpr    *xexpr = (XmlExpr *) node;
    1921         356 :                 int         nnamed = list_length(xexpr->named_args);
    1922         356 :                 int         nargs = list_length(xexpr->args);
    1923             :                 int         off;
    1924             :                 ListCell   *arg;
    1925             : 
    1926         356 :                 scratch.opcode = EEOP_XMLEXPR;
    1927         356 :                 scratch.d.xmlexpr.xexpr = xexpr;
    1928             : 
    1929             :                 /* allocate space for storing all the arguments */
    1930         356 :                 if (nnamed)
    1931             :                 {
    1932          40 :                     scratch.d.xmlexpr.named_argvalue =
    1933          40 :                         (Datum *) palloc(sizeof(Datum) * nnamed);
    1934          40 :                     scratch.d.xmlexpr.named_argnull =
    1935          40 :                         (bool *) palloc(sizeof(bool) * nnamed);
    1936             :                 }
    1937             :                 else
    1938             :                 {
    1939         316 :                     scratch.d.xmlexpr.named_argvalue = NULL;
    1940         316 :                     scratch.d.xmlexpr.named_argnull = NULL;
    1941             :                 }
    1942             : 
    1943         356 :                 if (nargs)
    1944             :                 {
    1945         300 :                     scratch.d.xmlexpr.argvalue =
    1946         300 :                         (Datum *) palloc(sizeof(Datum) * nargs);
    1947         300 :                     scratch.d.xmlexpr.argnull =
    1948         300 :                         (bool *) palloc(sizeof(bool) * nargs);
    1949             :                 }
    1950             :                 else
    1951             :                 {
    1952          56 :                     scratch.d.xmlexpr.argvalue = NULL;
    1953          56 :                     scratch.d.xmlexpr.argnull = NULL;
    1954             :                 }
    1955             : 
    1956             :                 /* prepare argument execution */
    1957         356 :                 off = 0;
    1958         468 :                 foreach(arg, xexpr->named_args)
    1959             :                 {
    1960         112 :                     Expr       *e = (Expr *) lfirst(arg);
    1961             : 
    1962         224 :                     ExecInitExprRec(e, state,
    1963         112 :                                     &scratch.d.xmlexpr.named_argvalue[off],
    1964         112 :                                     &scratch.d.xmlexpr.named_argnull[off]);
    1965         112 :                     off++;
    1966             :                 }
    1967             : 
    1968         356 :                 off = 0;
    1969         868 :                 foreach(arg, xexpr->args)
    1970             :                 {
    1971         512 :                     Expr       *e = (Expr *) lfirst(arg);
    1972             : 
    1973        1024 :                     ExecInitExprRec(e, state,
    1974         512 :                                     &scratch.d.xmlexpr.argvalue[off],
    1975         512 :                                     &scratch.d.xmlexpr.argnull[off]);
    1976         512 :                     off++;
    1977             :                 }
    1978             : 
    1979             :                 /* and evaluate the actual XML expression */
    1980         356 :                 ExprEvalPushStep(state, &scratch);
    1981         356 :                 break;
    1982             :             }
    1983             : 
    1984             :         case T_NullTest:
    1985             :             {
    1986       14014 :                 NullTest   *ntest = (NullTest *) node;
    1987             : 
    1988       14014 :                 if (ntest->nulltesttype == IS_NULL)
    1989             :                 {
    1990        4018 :                     if (ntest->argisrow)
    1991          94 :                         scratch.opcode = EEOP_NULLTEST_ROWISNULL;
    1992             :                     else
    1993        3924 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    1994             :                 }
    1995        9996 :                 else if (ntest->nulltesttype == IS_NOT_NULL)
    1996             :                 {
    1997        9996 :                     if (ntest->argisrow)
    1998          60 :                         scratch.opcode = EEOP_NULLTEST_ROWISNOTNULL;
    1999             :                     else
    2000        9936 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2001             :                 }
    2002             :                 else
    2003             :                 {
    2004           0 :                     elog(ERROR, "unrecognized nulltesttype: %d",
    2005             :                          (int) ntest->nulltesttype);
    2006             :                 }
    2007             :                 /* initialize cache in case it's a row test */
    2008       14014 :                 scratch.d.nulltest_row.argdesc = NULL;
    2009             : 
    2010             :                 /* first evaluate argument into result variable */
    2011       14014 :                 ExecInitExprRec(ntest->arg, state,
    2012             :                                 resv, resnull);
    2013             : 
    2014             :                 /* then push the test of that argument */
    2015       14014 :                 ExprEvalPushStep(state, &scratch);
    2016       14014 :                 break;
    2017             :             }
    2018             : 
    2019             :         case T_BooleanTest:
    2020             :             {
    2021         214 :                 BooleanTest *btest = (BooleanTest *) node;
    2022             : 
    2023             :                 /*
    2024             :                  * Evaluate argument, directly into result datum.  That's ok,
    2025             :                  * because resv/resnull is definitely not used anywhere else,
    2026             :                  * and will get overwritten by the below EEOP_BOOLTEST_IS_*
    2027             :                  * step.
    2028             :                  */
    2029         214 :                 ExecInitExprRec(btest->arg, state, resv, resnull);
    2030             : 
    2031         214 :                 switch (btest->booltesttype)
    2032             :                 {
    2033             :                     case IS_TRUE:
    2034          48 :                         scratch.opcode = EEOP_BOOLTEST_IS_TRUE;
    2035          48 :                         break;
    2036             :                     case IS_NOT_TRUE:
    2037          90 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_TRUE;
    2038          90 :                         break;
    2039             :                     case IS_FALSE:
    2040          24 :                         scratch.opcode = EEOP_BOOLTEST_IS_FALSE;
    2041          24 :                         break;
    2042             :                     case IS_NOT_FALSE:
    2043          16 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_FALSE;
    2044          16 :                         break;
    2045             :                     case IS_UNKNOWN:
    2046             :                         /* Same as scalar IS NULL test */
    2047          20 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    2048          20 :                         break;
    2049             :                     case IS_NOT_UNKNOWN:
    2050             :                         /* Same as scalar IS NOT NULL test */
    2051          16 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2052          16 :                         break;
    2053             :                     default:
    2054           0 :                         elog(ERROR, "unrecognized booltesttype: %d",
    2055             :                              (int) btest->booltesttype);
    2056             :                 }
    2057             : 
    2058         214 :                 ExprEvalPushStep(state, &scratch);
    2059         214 :                 break;
    2060             :             }
    2061             : 
    2062             :         case T_CoerceToDomain:
    2063             :             {
    2064       26546 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
    2065             : 
    2066       26546 :                 ExecInitCoerceToDomain(&scratch, ctest, state,
    2067             :                                        resv, resnull);
    2068       26546 :                 break;
    2069             :             }
    2070             : 
    2071             :         case T_CoerceToDomainValue:
    2072             :             {
    2073             :                 /*
    2074             :                  * Read from location identified by innermost_domainval.  Note
    2075             :                  * that innermost_domainval could be NULL, if we're compiling
    2076             :                  * a standalone domain check rather than one embedded in a
    2077             :                  * larger expression.  In that case we must read from
    2078             :                  * econtext->domainValue_datum.  We'll take care of that
    2079             :                  * scenario at runtime.
    2080             :                  */
    2081       29674 :                 scratch.opcode = EEOP_DOMAIN_TESTVAL;
    2082             :                 /* we share instruction union variant with case testval */
    2083       29674 :                 scratch.d.casetest.value = state->innermost_domainval;
    2084       29674 :                 scratch.d.casetest.isnull = state->innermost_domainnull;
    2085             : 
    2086       29674 :                 ExprEvalPushStep(state, &scratch);
    2087       29674 :                 break;
    2088             :             }
    2089             : 
    2090             :         case T_CurrentOfExpr:
    2091             :             {
    2092           2 :                 scratch.opcode = EEOP_CURRENTOFEXPR;
    2093           2 :                 ExprEvalPushStep(state, &scratch);
    2094           2 :                 break;
    2095             :             }
    2096             : 
    2097             :         case T_NextValueExpr:
    2098             :             {
    2099         158 :                 NextValueExpr *nve = (NextValueExpr *) node;
    2100             : 
    2101         158 :                 scratch.opcode = EEOP_NEXTVALUEEXPR;
    2102         158 :                 scratch.d.nextvalueexpr.seqid = nve->seqid;
    2103         158 :                 scratch.d.nextvalueexpr.seqtypid = nve->typeId;
    2104             : 
    2105         158 :                 ExprEvalPushStep(state, &scratch);
    2106         158 :                 break;
    2107             :             }
    2108             : 
    2109             :         default:
    2110           0 :             elog(ERROR, "unrecognized node type: %d",
    2111             :                  (int) nodeTag(node));
    2112             :             break;
    2113             :     }
    2114     2453774 : }
    2115             : 
    2116             : /*
    2117             :  * Add another expression evaluation step to ExprState->steps.
    2118             :  *
    2119             :  * Note that this potentially re-allocates es->steps, therefore no pointer
    2120             :  * into that array may be used while the expression is still being built.
    2121             :  */
    2122             : void
    2123     6026846 : ExprEvalPushStep(ExprState *es, const ExprEvalStep *s)
    2124             : {
    2125     6026846 :     if (es->steps_alloc == 0)
    2126             :     {
    2127     1137216 :         es->steps_alloc = 16;
    2128     1137216 :         es->steps = palloc(sizeof(ExprEvalStep) * es->steps_alloc);
    2129             :     }
    2130     4889630 :     else if (es->steps_alloc == es->steps_len)
    2131             :     {
    2132       46384 :         es->steps_alloc *= 2;
    2133       46384 :         es->steps = repalloc(es->steps,
    2134       46384 :                              sizeof(ExprEvalStep) * es->steps_alloc);
    2135             :     }
    2136             : 
    2137     6026846 :     memcpy(&es->steps[es->steps_len++], s, sizeof(ExprEvalStep));
    2138     6026846 : }
    2139             : 
    2140             : /*
    2141             :  * Perform setup necessary for the evaluation of a function-like expression,
    2142             :  * appending argument evaluation steps to the steps list in *state, and
    2143             :  * setting up *scratch so it is ready to be pushed.
    2144             :  *
    2145             :  * *scratch is not pushed here, so that callers may override the opcode,
    2146             :  * which is useful for function-like cases like DISTINCT.
    2147             :  */
    2148             : static void
    2149      640658 : ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args, Oid funcid,
    2150             :              Oid inputcollid, ExprState *state)
    2151             : {
    2152      640658 :     int         nargs = list_length(args);
    2153             :     AclResult   aclresult;
    2154             :     FmgrInfo   *flinfo;
    2155             :     FunctionCallInfo fcinfo;
    2156             :     int         argno;
    2157             :     ListCell   *lc;
    2158             : 
    2159             :     /* Check permission to call function */
    2160      640658 :     aclresult = pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE);
    2161      640658 :     if (aclresult != ACLCHECK_OK)
    2162          38 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(funcid));
    2163      640620 :     InvokeFunctionExecuteHook(funcid);
    2164             : 
    2165             :     /*
    2166             :      * Safety check on nargs.  Under normal circumstances this should never
    2167             :      * fail, as parser should check sooner.  But possibly it might fail if
    2168             :      * server has been compiled with FUNC_MAX_ARGS smaller than some functions
    2169             :      * declared in pg_proc?
    2170             :      */
    2171      640620 :     if (nargs > FUNC_MAX_ARGS)
    2172           0 :         ereport(ERROR,
    2173             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
    2174             :                  errmsg_plural("cannot pass more than %d argument to a function",
    2175             :                                "cannot pass more than %d arguments to a function",
    2176             :                                FUNC_MAX_ARGS,
    2177             :                                FUNC_MAX_ARGS)));
    2178             : 
    2179             :     /* Allocate function lookup data and parameter workspace for this call */
    2180      640620 :     scratch->d.func.finfo = palloc0(sizeof(FmgrInfo));
    2181      640620 :     scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
    2182      640620 :     flinfo = scratch->d.func.finfo;
    2183      640620 :     fcinfo = scratch->d.func.fcinfo_data;
    2184             : 
    2185             :     /* Set up the primary fmgr lookup information */
    2186      640620 :     fmgr_info(funcid, flinfo);
    2187      640620 :     fmgr_info_set_expr((Node *) node, flinfo);
    2188             : 
    2189             :     /* Initialize function call parameter structure too */
    2190      640620 :     InitFunctionCallInfoData(*fcinfo, flinfo,
    2191             :                              nargs, inputcollid, NULL, NULL);
    2192             : 
    2193             :     /* Keep extra copies of this info to save an indirection at runtime */
    2194      640620 :     scratch->d.func.fn_addr = flinfo->fn_addr;
    2195      640620 :     scratch->d.func.nargs = nargs;
    2196             : 
    2197             :     /* We only support non-set functions here */
    2198      640620 :     if (flinfo->fn_retset)
    2199           0 :         ereport(ERROR,
    2200             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2201             :                  errmsg("set-valued function called in context that cannot accept a set"),
    2202             :                  state->parent ?
    2203             :                  executor_errposition(state->parent->state,
    2204             :                                       exprLocation((Node *) node)) : 0));
    2205             : 
    2206             :     /* Build code to evaluate arguments directly into the fcinfo struct */
    2207      640620 :     argno = 0;
    2208     1807384 :     foreach(lc, args)
    2209             :     {
    2210     1166764 :         Expr       *arg = (Expr *) lfirst(lc);
    2211             : 
    2212     1166764 :         if (IsA(arg, Const))
    2213             :         {
    2214             :             /*
    2215             :              * Don't evaluate const arguments every round; especially
    2216             :              * interesting for constants in comparisons.
    2217             :              */
    2218      474640 :             Const      *con = (Const *) arg;
    2219             : 
    2220      474640 :             fcinfo->args[argno].value = con->constvalue;
    2221      474640 :             fcinfo->args[argno].isnull = con->constisnull;
    2222             :         }
    2223             :         else
    2224             :         {
    2225      692124 :             ExecInitExprRec(arg, state,
    2226             :                             &fcinfo->args[argno].value,
    2227             :                             &fcinfo->args[argno].isnull);
    2228             :         }
    2229     1166764 :         argno++;
    2230             :     }
    2231             : 
    2232             :     /* Insert appropriate opcode depending on strictness and stats level */
    2233      640620 :     if (pgstat_track_functions <= flinfo->fn_stats)
    2234             :     {
    2235      640620 :         if (flinfo->fn_strict && nargs > 0)
    2236      598696 :             scratch->opcode = EEOP_FUNCEXPR_STRICT;
    2237             :         else
    2238       41924 :             scratch->opcode = EEOP_FUNCEXPR;
    2239             :     }
    2240             :     else
    2241             :     {
    2242           0 :         if (flinfo->fn_strict && nargs > 0)
    2243           0 :             scratch->opcode = EEOP_FUNCEXPR_STRICT_FUSAGE;
    2244             :         else
    2245           0 :             scratch->opcode = EEOP_FUNCEXPR_FUSAGE;
    2246             :     }
    2247      640620 : }
    2248             : 
    2249             : /*
    2250             :  * Add expression steps deforming the ExprState's inner/outer/scan slots
    2251             :  * as much as required by the expression.
    2252             :  */
    2253             : static void
    2254     1098402 : ExecInitExprSlots(ExprState *state, Node *node)
    2255             : {
    2256     1098402 :     LastAttnumInfo info = {0, 0, 0};
    2257             : 
    2258             :     /*
    2259             :      * Figure out which attributes we're going to need.
    2260             :      */
    2261     1098402 :     get_last_attnums_walker(node, &info);
    2262             : 
    2263     1098402 :     ExecPushExprSlots(state, &info);
    2264     1098402 : }
    2265             : 
    2266             : /*
    2267             :  * Add steps deforming the ExprState's inner/out/scan slots as much as
    2268             :  * indicated by info. This is useful when building an ExprState covering more
    2269             :  * than one expression.
    2270             :  */
    2271             : static void
    2272     1127256 : ExecPushExprSlots(ExprState *state, LastAttnumInfo *info)
    2273             : {
    2274     1127256 :     ExprEvalStep scratch = {0};
    2275             : 
    2276     1127256 :     scratch.resvalue = NULL;
    2277     1127256 :     scratch.resnull = NULL;
    2278             : 
    2279             :     /* Emit steps as needed */
    2280     1127256 :     if (info->last_inner > 0)
    2281             :     {
    2282      148182 :         scratch.opcode = EEOP_INNER_FETCHSOME;
    2283      148182 :         scratch.d.fetch.last_var = info->last_inner;
    2284      148182 :         scratch.d.fetch.fixed = false;
    2285      148182 :         scratch.d.fetch.kind = NULL;
    2286      148182 :         scratch.d.fetch.known_desc = NULL;
    2287      148182 :         ExecComputeSlotInfo(state, &scratch);
    2288      148182 :         ExprEvalPushStep(state, &scratch);
    2289             :     }
    2290     1127256 :     if (info->last_outer > 0)
    2291             :     {
    2292      186078 :         scratch.opcode = EEOP_OUTER_FETCHSOME;
    2293      186078 :         scratch.d.fetch.last_var = info->last_outer;
    2294      186078 :         scratch.d.fetch.fixed = false;
    2295      186078 :         scratch.d.fetch.kind = NULL;
    2296      186078 :         scratch.d.fetch.known_desc = NULL;
    2297      186078 :         ExecComputeSlotInfo(state, &scratch);
    2298      186078 :         ExprEvalPushStep(state, &scratch);
    2299             :     }
    2300     1127256 :     if (info->last_scan > 0)
    2301             :     {
    2302      354986 :         scratch.opcode = EEOP_SCAN_FETCHSOME;
    2303      354986 :         scratch.d.fetch.last_var = info->last_scan;
    2304      354986 :         scratch.d.fetch.fixed = false;
    2305      354986 :         scratch.d.fetch.kind = NULL;
    2306      354986 :         scratch.d.fetch.known_desc = NULL;
    2307      354986 :         ExecComputeSlotInfo(state, &scratch);
    2308      354986 :         ExprEvalPushStep(state, &scratch);
    2309             :     }
    2310     1127256 : }
    2311             : 
    2312             : /*
    2313             :  * get_last_attnums_walker: expression walker for ExecInitExprSlots
    2314             :  */
    2315             : static bool
    2316     5814326 : get_last_attnums_walker(Node *node, LastAttnumInfo *info)
    2317             : {
    2318     5814326 :     if (node == NULL)
    2319      197632 :         return false;
    2320     5616694 :     if (IsA(node, Var))
    2321             :     {
    2322     1541784 :         Var        *variable = (Var *) node;
    2323     1541784 :         AttrNumber  attnum = variable->varattno;
    2324             : 
    2325     1541784 :         switch (variable->varno)
    2326             :         {
    2327             :             case INNER_VAR:
    2328      247866 :                 info->last_inner = Max(info->last_inner, attnum);
    2329      247866 :                 break;
    2330             : 
    2331             :             case OUTER_VAR:
    2332      464080 :                 info->last_outer = Max(info->last_outer, attnum);
    2333      464080 :                 break;
    2334             : 
    2335             :                 /* INDEX_VAR is handled by default case */
    2336             : 
    2337             :             default:
    2338      829838 :                 info->last_scan = Max(info->last_scan, attnum);
    2339      829838 :                 break;
    2340             :         }
    2341     1541784 :         return false;
    2342             :     }
    2343             : 
    2344             :     /*
    2345             :      * Don't examine the arguments or filters of Aggrefs or WindowFuncs,
    2346             :      * because those do not represent expressions to be evaluated within the
    2347             :      * calling expression's econtext.  GroupingFunc arguments are never
    2348             :      * evaluated at all.
    2349             :      */
    2350     4074910 :     if (IsA(node, Aggref))
    2351       31412 :         return false;
    2352     4043498 :     if (IsA(node, WindowFunc))
    2353        1372 :         return false;
    2354     4042126 :     if (IsA(node, GroupingFunc))
    2355         184 :         return false;
    2356     4041942 :     return expression_tree_walker(node, get_last_attnums_walker,
    2357             :                                   (void *) info);
    2358             : }
    2359             : 
    2360             : /*
    2361             :  * Compute additional information for EEOP_*_FETCHSOME ops.
    2362             :  *
    2363             :  * The goal is to determine whether a slot is 'fixed', that is, every
    2364             :  * evaluation of the expression will have the same type of slot, with an
    2365             :  * equivalent descriptor.
    2366             :  */
    2367             : static void
    2368      706006 : ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op)
    2369             : {
    2370      706006 :     PlanState  *parent = state->parent;
    2371      706006 :     TupleDesc   desc = NULL;
    2372      706006 :     const TupleTableSlotOps *tts_ops = NULL;
    2373      706006 :     bool        isfixed = false;
    2374             : 
    2375      706006 :     if (op->d.fetch.known_desc != NULL)
    2376             :     {
    2377       16760 :         desc = op->d.fetch.known_desc;
    2378       16760 :         tts_ops = op->d.fetch.kind;
    2379       16760 :         isfixed = op->d.fetch.kind != NULL;
    2380             :     }
    2381      689246 :     else if (!parent)
    2382             :     {
    2383        5968 :         isfixed = false;
    2384             :     }
    2385      683278 :     else if (op->opcode == EEOP_INNER_FETCHSOME)
    2386             :     {
    2387      148126 :         PlanState  *is = innerPlanState(parent);
    2388             : 
    2389      148126 :         if (parent->inneropsset && !parent->inneropsfixed)
    2390             :         {
    2391           0 :             isfixed = false;
    2392             :         }
    2393      148126 :         else if (parent->inneropsset && parent->innerops)
    2394             :         {
    2395           0 :             isfixed = true;
    2396           0 :             tts_ops = parent->innerops;
    2397             :         }
    2398      148126 :         else if (is)
    2399             :         {
    2400      119566 :             tts_ops = ExecGetResultSlotOps(is, &isfixed);
    2401      119566 :             desc = ExecGetResultType(is);
    2402             :         }
    2403             :     }
    2404      535152 :     else if (op->opcode == EEOP_OUTER_FETCHSOME)
    2405             :     {
    2406      185954 :         PlanState  *os = outerPlanState(parent);
    2407             : 
    2408      185954 :         if (parent->outeropsset && !parent->outeropsfixed)
    2409             :         {
    2410          12 :             isfixed = false;
    2411             :         }
    2412      185942 :         else if (parent->outeropsset && parent->outerops)
    2413             :         {
    2414        2304 :             isfixed = true;
    2415        2304 :             tts_ops = parent->outerops;
    2416             :         }
    2417      183638 :         else if (os)
    2418             :         {
    2419      183506 :             tts_ops = ExecGetResultSlotOps(os, &isfixed);
    2420      183506 :             desc = ExecGetResultType(os);
    2421             :         }
    2422             :     }
    2423      349198 :     else if (op->opcode == EEOP_SCAN_FETCHSOME)
    2424             :     {
    2425      349198 :         desc = parent->scandesc;
    2426             : 
    2427      349198 :         if (parent && parent->scanops)
    2428      345296 :             tts_ops = parent->scanops;
    2429             : 
    2430      349198 :         if (parent->scanopsset)
    2431      345296 :             isfixed = parent->scanopsfixed;
    2432             :     }
    2433             : 
    2434      706006 :     if (isfixed && desc != NULL && tts_ops != NULL)
    2435             :     {
    2436      653510 :         op->d.fetch.fixed = true;
    2437      653510 :         op->d.fetch.kind = tts_ops;
    2438      653510 :         op->d.fetch.known_desc = desc;
    2439             :     }
    2440             :     else
    2441             :     {
    2442       52496 :         op->d.fetch.fixed = false;
    2443       52496 :         op->d.fetch.kind = NULL;
    2444       52496 :         op->d.fetch.known_desc = NULL;
    2445             :     }
    2446      706006 : }
    2447             : 
    2448             : /*
    2449             :  * Prepare step for the evaluation of a whole-row variable.
    2450             :  * The caller still has to push the step.
    2451             :  */
    2452             : static void
    2453        2358 : ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state)
    2454             : {
    2455        2358 :     PlanState  *parent = state->parent;
    2456             : 
    2457             :     /* fill in all but the target */
    2458        2358 :     scratch->opcode = EEOP_WHOLEROW;
    2459        2358 :     scratch->d.wholerow.var = variable;
    2460        2358 :     scratch->d.wholerow.first = true;
    2461        2358 :     scratch->d.wholerow.slow = false;
    2462        2358 :     scratch->d.wholerow.tupdesc = NULL; /* filled at runtime */
    2463        2358 :     scratch->d.wholerow.junkFilter = NULL;
    2464             : 
    2465             :     /*
    2466             :      * If the input tuple came from a subquery, it might contain "resjunk"
    2467             :      * columns (such as GROUP BY or ORDER BY columns), which we don't want to
    2468             :      * keep in the whole-row result.  We can get rid of such columns by
    2469             :      * passing the tuple through a JunkFilter --- but to make one, we have to
    2470             :      * lay our hands on the subquery's targetlist.  Fortunately, there are not
    2471             :      * very many cases where this can happen, and we can identify all of them
    2472             :      * by examining our parent PlanState.  We assume this is not an issue in
    2473             :      * standalone expressions that don't have parent plans.  (Whole-row Vars
    2474             :      * can occur in such expressions, but they will always be referencing
    2475             :      * table rows.)
    2476             :      */
    2477        2358 :     if (parent)
    2478             :     {
    2479        2336 :         PlanState  *subplan = NULL;
    2480             : 
    2481        2336 :         switch (nodeTag(parent))
    2482             :         {
    2483             :             case T_SubqueryScanState:
    2484         228 :                 subplan = ((SubqueryScanState *) parent)->subplan;
    2485         228 :                 break;
    2486             :             case T_CteScanState:
    2487         116 :                 subplan = ((CteScanState *) parent)->cteplanstate;
    2488         116 :                 break;
    2489             :             default:
    2490        1992 :                 break;
    2491             :         }
    2492             : 
    2493        2336 :         if (subplan)
    2494             :         {
    2495         344 :             bool        junk_filter_needed = false;
    2496             :             ListCell   *tlist;
    2497             : 
    2498             :             /* Detect whether subplan tlist actually has any junk columns */
    2499         940 :             foreach(tlist, subplan->plan->targetlist)
    2500             :             {
    2501         604 :                 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
    2502             : 
    2503         604 :                 if (tle->resjunk)
    2504             :                 {
    2505           8 :                     junk_filter_needed = true;
    2506           8 :                     break;
    2507             :                 }
    2508             :             }
    2509             : 
    2510             :             /* If so, build the junkfilter now */
    2511         344 :             if (junk_filter_needed)
    2512             :             {
    2513           8 :                 scratch->d.wholerow.junkFilter =
    2514           8 :                     ExecInitJunkFilter(subplan->plan->targetlist,
    2515             :                                        ExecInitExtraTupleSlot(parent->state, NULL,
    2516             :                                                               &TTSOpsVirtual));
    2517             :             }
    2518             :         }
    2519             :     }
    2520        2358 : }
    2521             : 
    2522             : /*
    2523             :  * Prepare evaluation of a SubscriptingRef expression.
    2524             :  */
    2525             : static void
    2526        6416 : ExecInitSubscriptingRef(ExprEvalStep *scratch, SubscriptingRef *sbsref,
    2527             :                         ExprState *state, Datum *resv, bool *resnull)
    2528             : {
    2529        6416 :     bool        isAssignment = (sbsref->refassgnexpr != NULL);
    2530        6416 :     SubscriptingRefState *sbsrefstate = palloc0(sizeof(SubscriptingRefState));
    2531        6416 :     List       *adjust_jumps = NIL;
    2532             :     ListCell   *lc;
    2533             :     int         i;
    2534             : 
    2535             :     /* Fill constant fields of SubscriptingRefState */
    2536        6416 :     sbsrefstate->isassignment = isAssignment;
    2537        6416 :     sbsrefstate->refelemtype = sbsref->refelemtype;
    2538        6416 :     sbsrefstate->refattrlength = get_typlen(sbsref->refcontainertype);
    2539        6416 :     get_typlenbyvalalign(sbsref->refelemtype,
    2540             :                          &sbsrefstate->refelemlength,
    2541             :                          &sbsrefstate->refelembyval,
    2542             :                          &sbsrefstate->refelemalign);
    2543             : 
    2544             :     /*
    2545             :      * Evaluate array input.  It's safe to do so into resv/resnull, because we
    2546             :      * won't use that as target for any of the other subexpressions, and it'll
    2547             :      * be overwritten by the final EEOP_SBSREF_FETCH/ASSIGN step, which is
    2548             :      * pushed last.
    2549             :      */
    2550        6416 :     ExecInitExprRec(sbsref->refexpr, state, resv, resnull);
    2551             : 
    2552             :     /*
    2553             :      * If refexpr yields NULL, and it's a fetch, then result is NULL.  We can
    2554             :      * implement this with just JUMP_IF_NULL, since we evaluated the array
    2555             :      * into the desired target location.
    2556             :      */
    2557        6416 :     if (!isAssignment)
    2558             :     {
    2559        5934 :         scratch->opcode = EEOP_JUMP_IF_NULL;
    2560        5934 :         scratch->d.jump.jumpdone = -1;   /* adjust later */
    2561        5934 :         ExprEvalPushStep(state, scratch);
    2562        5934 :         adjust_jumps = lappend_int(adjust_jumps,
    2563        5934 :                                    state->steps_len - 1);
    2564             :     }
    2565             : 
    2566             :     /* Verify subscript list lengths are within limit */
    2567        6416 :     if (list_length(sbsref->refupperindexpr) > MAXDIM)
    2568           4 :         ereport(ERROR,
    2569             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2570             :                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    2571             :                         list_length(sbsref->refupperindexpr), MAXDIM)));
    2572             : 
    2573        6412 :     if (list_length(sbsref->reflowerindexpr) > MAXDIM)
    2574           0 :         ereport(ERROR,
    2575             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2576             :                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    2577             :                         list_length(sbsref->reflowerindexpr), MAXDIM)));
    2578             : 
    2579             :     /* Evaluate upper subscripts */
    2580        6412 :     i = 0;
    2581       12988 :     foreach(lc, sbsref->refupperindexpr)
    2582             :     {
    2583        6576 :         Expr       *e = (Expr *) lfirst(lc);
    2584             : 
    2585             :         /* When slicing, individual subscript bounds can be omitted */
    2586        6576 :         if (!e)
    2587             :         {
    2588          52 :             sbsrefstate->upperprovided[i] = false;
    2589          52 :             i++;
    2590          52 :             continue;
    2591             :         }
    2592             : 
    2593        6524 :         sbsrefstate->upperprovided[i] = true;
    2594             : 
    2595             :         /* Each subscript is evaluated into subscriptvalue/subscriptnull */
    2596        6524 :         ExecInitExprRec(e, state,
    2597             :                         &sbsrefstate->subscriptvalue, &sbsrefstate->subscriptnull);
    2598             : 
    2599             :         /* ... and then SBSREF_SUBSCRIPT saves it into step's workspace */
    2600        6524 :         scratch->opcode = EEOP_SBSREF_SUBSCRIPT;
    2601        6524 :         scratch->d.sbsref_subscript.state = sbsrefstate;
    2602        6524 :         scratch->d.sbsref_subscript.off = i;
    2603        6524 :         scratch->d.sbsref_subscript.isupper = true;
    2604        6524 :         scratch->d.sbsref_subscript.jumpdone = -1;   /* adjust later */
    2605        6524 :         ExprEvalPushStep(state, scratch);
    2606        6524 :         adjust_jumps = lappend_int(adjust_jumps,
    2607        6524 :                                    state->steps_len - 1);
    2608        6524 :         i++;
    2609             :     }
    2610        6412 :     sbsrefstate->numupper = i;
    2611             : 
    2612             :     /* Evaluate lower subscripts similarly */
    2613        6412 :     i = 0;
    2614        6756 :     foreach(lc, sbsref->reflowerindexpr)
    2615             :     {
    2616         344 :         Expr       *e = (Expr *) lfirst(lc);
    2617             : 
    2618             :         /* When slicing, individual subscript bounds can be omitted */
    2619         344 :         if (!e)
    2620             :         {
    2621          52 :             sbsrefstate->lowerprovided[i] = false;
    2622          52 :             i++;
    2623          52 :             continue;
    2624             :         }
    2625             : 
    2626         292 :         sbsrefstate->lowerprovided[i] = true;
    2627             : 
    2628             :         /* Each subscript is evaluated into subscriptvalue/subscriptnull */
    2629         292 :         ExecInitExprRec(e, state,
    2630             :                         &sbsrefstate->subscriptvalue, &sbsrefstate->subscriptnull);
    2631             : 
    2632             :         /* ... and then SBSREF_SUBSCRIPT saves it into step's workspace */
    2633         292 :         scratch->opcode = EEOP_SBSREF_SUBSCRIPT;
    2634         292 :         scratch->d.sbsref_subscript.state = sbsrefstate;
    2635         292 :         scratch->d.sbsref_subscript.off = i;
    2636         292 :         scratch->d.sbsref_subscript.isupper = false;
    2637         292 :         scratch->d.sbsref_subscript.jumpdone = -1;   /* adjust later */
    2638         292 :         ExprEvalPushStep(state, scratch);
    2639         292 :         adjust_jumps = lappend_int(adjust_jumps,
    2640         292 :                                    state->steps_len - 1);
    2641         292 :         i++;
    2642             :     }
    2643        6412 :     sbsrefstate->numlower = i;
    2644             : 
    2645             :     /* Should be impossible if parser is sane, but check anyway: */
    2646        6652 :     if (sbsrefstate->numlower != 0 &&
    2647         240 :         sbsrefstate->numupper != sbsrefstate->numlower)
    2648           0 :         elog(ERROR, "upper and lower index lists are not same length");
    2649             : 
    2650        6412 :     if (isAssignment)
    2651             :     {
    2652             :         Datum      *save_innermost_caseval;
    2653             :         bool       *save_innermost_casenull;
    2654             : 
    2655             :         /*
    2656             :          * We might have a nested-assignment situation, in which the
    2657             :          * refassgnexpr is itself a FieldStore or SubscriptingRef that needs
    2658             :          * to obtain and modify the previous value of the array element or
    2659             :          * slice being replaced.  If so, we have to extract that value from
    2660             :          * the array and pass it down via the CaseTestExpr mechanism.  It's
    2661             :          * safe to reuse the CASE mechanism because there cannot be a CASE
    2662             :          * between here and where the value would be needed, and an array
    2663             :          * assignment can't be within a CASE either.  (So saving and restoring
    2664             :          * innermost_caseval is just paranoia, but let's do it anyway.)
    2665             :          *
    2666             :          * Since fetching the old element might be a nontrivial expense, do it
    2667             :          * only if the argument actually needs it.
    2668             :          */
    2669         482 :         if (isAssignmentIndirectionExpr(sbsref->refassgnexpr))
    2670             :         {
    2671          80 :             scratch->opcode = EEOP_SBSREF_OLD;
    2672          80 :             scratch->d.sbsref.state = sbsrefstate;
    2673          80 :             ExprEvalPushStep(state, scratch);
    2674             :         }
    2675             : 
    2676             :         /* SBSREF_OLD puts extracted value into prevvalue/prevnull */
    2677         482 :         save_innermost_caseval = state->innermost_caseval;
    2678         482 :         save_innermost_casenull = state->innermost_casenull;
    2679         482 :         state->innermost_caseval = &sbsrefstate->prevvalue;
    2680         482 :         state->innermost_casenull = &sbsrefstate->prevnull;
    2681             : 
    2682             :         /* evaluate replacement value into replacevalue/replacenull */
    2683         482 :         ExecInitExprRec(sbsref->refassgnexpr, state,
    2684             :                         &sbsrefstate->replacevalue, &sbsrefstate->replacenull);
    2685             : 
    2686         482 :         state->innermost_caseval = save_innermost_caseval;
    2687         482 :         state->innermost_casenull = save_innermost_casenull;
    2688             : 
    2689             :         /* and perform the assignment */
    2690         482 :         scratch->opcode = EEOP_SBSREF_ASSIGN;
    2691         482 :         scratch->d.sbsref.state = sbsrefstate;
    2692         482 :         ExprEvalPushStep(state, scratch);
    2693             : 
    2694             :     }
    2695             :     else
    2696             :     {
    2697             :         /* array fetch is much simpler */
    2698        5930 :         scratch->opcode = EEOP_SBSREF_FETCH;
    2699        5930 :         scratch->d.sbsref.state = sbsrefstate;
    2700        5930 :         ExprEvalPushStep(state, scratch);
    2701             : 
    2702             :     }
    2703             : 
    2704             :     /* adjust jump targets */
    2705       19158 :     foreach(lc, adjust_jumps)
    2706             :     {
    2707       12746 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    2708             : 
    2709       12746 :         if (as->opcode == EEOP_SBSREF_SUBSCRIPT)
    2710             :         {
    2711             :             Assert(as->d.sbsref_subscript.jumpdone == -1);
    2712        6816 :             as->d.sbsref_subscript.jumpdone = state->steps_len;
    2713             :         }
    2714             :         else
    2715             :         {
    2716             :             Assert(as->opcode == EEOP_JUMP_IF_NULL);
    2717             :             Assert(as->d.jump.jumpdone == -1);
    2718        5930 :             as->d.jump.jumpdone = state->steps_len;
    2719             :         }
    2720             :     }
    2721        6412 : }
    2722             : 
    2723             : /*
    2724             :  * Helper for preparing SubscriptingRef expressions for evaluation: is expr
    2725             :  * a nested FieldStore or SubscriptingRef that needs the old element value
    2726             :  * passed down?
    2727             :  *
    2728             :  * (We could use this in FieldStore too, but in that case passing the old
    2729             :  * value is so cheap there's no need.)
    2730             :  *
    2731             :  * Note: it might seem that this needs to recurse, but it does not; the
    2732             :  * CaseTestExpr, if any, will be directly the arg or refexpr of the top-level
    2733             :  * node.  Nested-assignment situations give rise to expression trees in which
    2734             :  * each level of assignment has its own CaseTestExpr, and the recursive
    2735             :  * structure appears within the newvals or refassgnexpr field.
    2736             :  */
    2737             : static bool
    2738         482 : isAssignmentIndirectionExpr(Expr *expr)
    2739             : {
    2740         482 :     if (expr == NULL)
    2741           0 :         return false;           /* just paranoia */
    2742         482 :     if (IsA(expr, FieldStore))
    2743             :     {
    2744          80 :         FieldStore *fstore = (FieldStore *) expr;
    2745             : 
    2746          80 :         if (fstore->arg && IsA(fstore->arg, CaseTestExpr))
    2747          80 :             return true;
    2748             :     }
    2749         402 :     else if (IsA(expr, SubscriptingRef))
    2750             :     {
    2751          20 :         SubscriptingRef *sbsRef = (SubscriptingRef *) expr;
    2752             : 
    2753          20 :         if (sbsRef->refexpr && IsA(sbsRef->refexpr, CaseTestExpr))
    2754           0 :             return true;
    2755             :     }
    2756         402 :     return false;
    2757             : }
    2758             : 
    2759             : /*
    2760             :  * Prepare evaluation of a CoerceToDomain expression.
    2761             :  */
    2762             : static void
    2763       26546 : ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
    2764             :                        ExprState *state, Datum *resv, bool *resnull)
    2765             : {
    2766       26546 :     ExprEvalStep scratch2 = {0};
    2767             :     DomainConstraintRef *constraint_ref;
    2768       26546 :     Datum      *domainval = NULL;
    2769       26546 :     bool       *domainnull = NULL;
    2770             :     Datum      *save_innermost_domainval;
    2771             :     bool       *save_innermost_domainnull;
    2772             :     ListCell   *l;
    2773             : 
    2774       26546 :     scratch->d.domaincheck.resulttype = ctest->resulttype;
    2775             :     /* we'll allocate workspace only if needed */
    2776       26546 :     scratch->d.domaincheck.checkvalue = NULL;
    2777       26546 :     scratch->d.domaincheck.checknull = NULL;
    2778             : 
    2779             :     /*
    2780             :      * Evaluate argument - it's fine to directly store it into resv/resnull,
    2781             :      * if there's constraint failures there'll be errors, otherwise it's what
    2782             :      * needs to be returned.
    2783             :      */
    2784       26546 :     ExecInitExprRec(ctest->arg, state, resv, resnull);
    2785             : 
    2786             :     /*
    2787             :      * Note: if the argument is of varlena type, it could be a R/W expanded
    2788             :      * object.  We want to return the R/W pointer as the final result, but we
    2789             :      * have to pass a R/O pointer as the value to be tested by any functions
    2790             :      * in check expressions.  We don't bother to emit a MAKE_READONLY step
    2791             :      * unless there's actually at least one check expression, though.  Until
    2792             :      * we've tested that, domainval/domainnull are NULL.
    2793             :      */
    2794             : 
    2795             :     /*
    2796             :      * Collect the constraints associated with the domain.
    2797             :      *
    2798             :      * Note: before PG v10 we'd recheck the set of constraints during each
    2799             :      * evaluation of the expression.  Now we bake them into the ExprState
    2800             :      * during executor initialization.  That means we don't need typcache.c to
    2801             :      * provide compiled exprs.
    2802             :      */
    2803       26546 :     constraint_ref = (DomainConstraintRef *)
    2804             :         palloc(sizeof(DomainConstraintRef));
    2805       26546 :     InitDomainConstraintRef(ctest->resulttype,
    2806             :                             constraint_ref,
    2807             :                             CurrentMemoryContext,
    2808             :                             false);
    2809             : 
    2810             :     /*
    2811             :      * Compile code to check each domain constraint.  NOTNULL constraints can
    2812             :      * just be applied on the resv/resnull value, but for CHECK constraints we
    2813             :      * need more pushups.
    2814             :      */
    2815       53976 :     foreach(l, constraint_ref->constraints)
    2816             :     {
    2817       27430 :         DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
    2818             : 
    2819       27430 :         scratch->d.domaincheck.constraintname = con->name;
    2820             : 
    2821       27430 :         switch (con->constrainttype)
    2822             :         {
    2823             :             case DOM_CONSTRAINT_NOTNULL:
    2824         238 :                 scratch->opcode = EEOP_DOMAIN_NOTNULL;
    2825         238 :                 ExprEvalPushStep(state, scratch);
    2826         238 :                 break;
    2827             :             case DOM_CONSTRAINT_CHECK:
    2828             :                 /* Allocate workspace for CHECK output if we didn't yet */
    2829       27192 :                 if (scratch->d.domaincheck.checkvalue == NULL)
    2830             :                 {
    2831       26364 :                     scratch->d.domaincheck.checkvalue =
    2832       26364 :                         (Datum *) palloc(sizeof(Datum));
    2833       26364 :                     scratch->d.domaincheck.checknull =
    2834       26364 :                         (bool *) palloc(sizeof(bool));
    2835             :                 }
    2836             : 
    2837             :                 /*
    2838             :                  * If first time through, determine where CoerceToDomainValue
    2839             :                  * nodes should read from.
    2840             :                  */
    2841       27192 :                 if (domainval == NULL)
    2842             :                 {
    2843             :                     /*
    2844             :                      * Since value might be read multiple times, force to R/O
    2845             :                      * - but only if it could be an expanded datum.
    2846             :                      */
    2847       26364 :                     if (get_typlen(ctest->resulttype) == -1)
    2848             :                     {
    2849             :                         /* Yes, so make output workspace for MAKE_READONLY */
    2850        7240 :                         domainval = (Datum *) palloc(sizeof(Datum));
    2851        7240 :                         domainnull = (bool *) palloc(sizeof(bool));
    2852             : 
    2853             :                         /* Emit MAKE_READONLY */
    2854        7240 :                         scratch2.opcode = EEOP_MAKE_READONLY;
    2855        7240 :                         scratch2.resvalue = domainval;
    2856        7240 :                         scratch2.resnull = domainnull;
    2857        7240 :                         scratch2.d.make_readonly.value = resv;
    2858        7240 :                         scratch2.d.make_readonly.isnull = resnull;
    2859        7240 :                         ExprEvalPushStep(state, &scratch2);
    2860             :                     }
    2861             :                     else
    2862             :                     {
    2863             :                         /* No, so it's fine to read from resv/resnull */
    2864       19124 :                         domainval = resv;
    2865       19124 :                         domainnull = resnull;
    2866             :                     }
    2867             :                 }
    2868             : 
    2869             :                 /*
    2870             :                  * Set up value to be returned by CoerceToDomainValue nodes.
    2871             :                  * We must save and restore innermost_domainval/null fields,
    2872             :                  * in case this node is itself within a check expression for
    2873             :                  * another domain.
    2874             :                  */
    2875       27192 :                 save_innermost_domainval = state->innermost_domainval;
    2876       27192 :                 save_innermost_domainnull = state->innermost_domainnull;
    2877       27192 :                 state->innermost_domainval = domainval;
    2878       27192 :                 state->innermost_domainnull = domainnull;
    2879             : 
    2880             :                 /* evaluate check expression value */
    2881       27192 :                 ExecInitExprRec(con->check_expr, state,
    2882             :                                 scratch->d.domaincheck.checkvalue,
    2883             :                                 scratch->d.domaincheck.checknull);
    2884             : 
    2885       27192 :                 state->innermost_domainval = save_innermost_domainval;
    2886       27192 :                 state->innermost_domainnull = save_innermost_domainnull;
    2887             : 
    2888             :                 /* now test result */
    2889       27192 :                 scratch->opcode = EEOP_DOMAIN_CHECK;
    2890       27192 :                 ExprEvalPushStep(state, scratch);
    2891             : 
    2892       27192 :                 break;
    2893             :             default:
    2894           0 :                 elog(ERROR, "unrecognized constraint type: %d",
    2895             :                      (int) con->constrainttype);
    2896             :                 break;
    2897             :         }
    2898             :     }
    2899       26546 : }
    2900             : 
    2901             : /*
    2902             :  * Build transition/combine function invocations for all aggregate transition
    2903             :  * / combination function invocations in a grouping sets phase. This has to
    2904             :  * invoke all sort based transitions in a phase (if doSort is true), all hash
    2905             :  * based transitions (if doHash is true), or both (both true).
    2906             :  *
    2907             :  * The resulting expression will, for each set of transition values, first
    2908             :  * check for filters, evaluate aggregate input, check that that input is not
    2909             :  * NULL for a strict transition function, and then finally invoke the
    2910             :  * transition for each of the concurrently computed grouping sets.
    2911             :  */
    2912             : ExprState *
    2913       28854 : ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase,
    2914             :                   bool doSort, bool doHash)
    2915             : {
    2916       28854 :     ExprState  *state = makeNode(ExprState);
    2917       28854 :     PlanState  *parent = &aggstate->ss.ps;
    2918       28854 :     ExprEvalStep scratch = {0};
    2919       28854 :     int         transno = 0;
    2920       28854 :     int         setoff = 0;
    2921       28854 :     bool        isCombine = DO_AGGSPLIT_COMBINE(aggstate->aggsplit);
    2922       28854 :     LastAttnumInfo deform = {0, 0, 0};
    2923             : 
    2924       28854 :     state->expr = (Expr *) aggstate;
    2925       28854 :     state->parent = parent;
    2926             : 
    2927       28854 :     scratch.resvalue = &state->resvalue;
    2928       28854 :     scratch.resnull = &state->resnull;
    2929             : 
    2930             :     /*
    2931             :      * First figure out which slots, and how many columns from each, we're
    2932             :      * going to need.
    2933             :      */
    2934       60002 :     for (transno = 0; transno < aggstate->numtrans; transno++)
    2935             :     {
    2936       31148 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    2937             : 
    2938       31148 :         get_last_attnums_walker((Node *) pertrans->aggref->aggdirectargs,
    2939             :                                 &deform);
    2940       31148 :         get_last_attnums_walker((Node *) pertrans->aggref->args,
    2941             :                                 &deform);
    2942       31148 :         get_last_attnums_walker((Node *) pertrans->aggref->aggorder,
    2943             :                                 &deform);
    2944       31148 :         get_last_attnums_walker((Node *) pertrans->aggref->aggdistinct,
    2945             :                                 &deform);
    2946       31148 :         get_last_attnums_walker((Node *) pertrans->aggref->aggfilter,
    2947             :                                 &deform);
    2948             :     }
    2949       28854 :     ExecPushExprSlots(state, &deform);
    2950             : 
    2951             :     /*
    2952             :      * Emit instructions for each transition value / grouping set combination.
    2953             :      */
    2954       60002 :     for (transno = 0; transno < aggstate->numtrans; transno++)
    2955             :     {
    2956       31148 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    2957             :         int         argno;
    2958             :         int         setno;
    2959       31148 :         FunctionCallInfo trans_fcinfo = pertrans->transfn_fcinfo;
    2960             :         ListCell   *arg;
    2961             :         ListCell   *bail;
    2962       31148 :         List       *adjust_bailout = NIL;
    2963       31148 :         NullableDatum *strictargs = NULL;
    2964       31148 :         bool       *strictnulls = NULL;
    2965             : 
    2966             :         /*
    2967             :          * If filter present, emit. Do so before evaluating the input, to
    2968             :          * avoid potentially unneeded computations, or even worse, unintended
    2969             :          * side-effects.  When combining, all the necessary filtering has
    2970             :          * already been done.
    2971             :          */
    2972       31148 :         if (pertrans->aggref->aggfilter && !isCombine)
    2973             :         {
    2974             :             /* evaluate filter expression */
    2975         470 :             ExecInitExprRec(pertrans->aggref->aggfilter, state,
    2976             :                             &state->resvalue, &state->resnull);
    2977             :             /* and jump out if false */
    2978         470 :             scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    2979         470 :             scratch.d.jump.jumpdone = -1;   /* adjust later */
    2980         470 :             ExprEvalPushStep(state, &scratch);
    2981         470 :             adjust_bailout = lappend_int(adjust_bailout,
    2982         470 :                                          state->steps_len - 1);
    2983             :         }
    2984             : 
    2985             :         /*
    2986             :          * Evaluate arguments to aggregate/combine function.
    2987             :          */
    2988       31148 :         argno = 0;
    2989       31148 :         if (isCombine)
    2990             :         {
    2991             :             /*
    2992             :              * Combining two aggregate transition values. Instead of directly
    2993             :              * coming from a tuple the input is a, potentially deserialized,
    2994             :              * transition value.
    2995             :              */
    2996             :             TargetEntry *source_tle;
    2997             : 
    2998             :             Assert(pertrans->numSortCols == 0);
    2999             :             Assert(list_length(pertrans->aggref->args) == 1);
    3000             : 
    3001         812 :             strictargs = trans_fcinfo->args + 1;
    3002         812 :             source_tle = (TargetEntry *) linitial(pertrans->aggref->args);
    3003             : 
    3004             :             /*
    3005             :              * deserialfn_oid will be set if we must deserialize the input
    3006             :              * state before calling the combine function.
    3007             :              */
    3008         812 :             if (!OidIsValid(pertrans->deserialfn_oid))
    3009             :             {
    3010             :                 /*
    3011             :                  * Start from 1, since the 0th arg will be the transition
    3012             :                  * value
    3013             :                  */
    3014        1576 :                 ExecInitExprRec(source_tle->expr, state,
    3015         788 :                                 &trans_fcinfo->args[argno + 1].value,
    3016         788 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3017             :             }
    3018             :             else
    3019             :             {
    3020          24 :                 FunctionCallInfo ds_fcinfo = pertrans->deserialfn_fcinfo;
    3021             : 
    3022             :                 /* evaluate argument */
    3023          24 :                 ExecInitExprRec(source_tle->expr, state,
    3024             :                                 &ds_fcinfo->args[0].value,
    3025             :                                 &ds_fcinfo->args[0].isnull);
    3026             : 
    3027             :                 /* Dummy second argument for type-safety reasons */
    3028          24 :                 ds_fcinfo->args[1].value = PointerGetDatum(NULL);
    3029          24 :                 ds_fcinfo->args[1].isnull = false;
    3030             : 
    3031             :                 /*
    3032             :                  * Don't call a strict deserialization function with NULL
    3033             :                  * input
    3034             :                  */
    3035          24 :                 if (pertrans->deserialfn.fn_strict)
    3036          24 :                     scratch.opcode = EEOP_AGG_STRICT_DESERIALIZE;
    3037             :                 else
    3038           0 :                     scratch.opcode = EEOP_AGG_DESERIALIZE;
    3039             : 
    3040          24 :                 scratch.d.agg_deserialize.aggstate = aggstate;
    3041          24 :                 scratch.d.agg_deserialize.fcinfo_data = ds_fcinfo;
    3042          24 :                 scratch.d.agg_deserialize.jumpnull = -1;    /* adjust later */
    3043          24 :                 scratch.resvalue = &trans_fcinfo->args[argno + 1].value;
    3044          24 :                 scratch.resnull = &trans_fcinfo->args[argno + 1].isnull;
    3045             : 
    3046          24 :                 ExprEvalPushStep(state, &scratch);
    3047          24 :                 adjust_bailout = lappend_int(adjust_bailout,
    3048          24 :                                              state->steps_len - 1);
    3049             : 
    3050             :                 /* restore normal settings of scratch fields */
    3051          24 :                 scratch.resvalue = &state->resvalue;
    3052          24 :                 scratch.resnull = &state->resnull;
    3053             :             }
    3054         812 :             argno++;
    3055             :         }
    3056       30336 :         else if (pertrans->numSortCols == 0)
    3057             :         {
    3058             :             /*
    3059             :              * Normal transition function without ORDER BY / DISTINCT.
    3060             :              */
    3061       21084 :             strictargs = trans_fcinfo->args + 1;
    3062             : 
    3063       36784 :             foreach(arg, pertrans->aggref->args)
    3064             :             {
    3065       15700 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3066             : 
    3067             :                 /*
    3068             :                  * Start from 1, since the 0th arg will be the transition
    3069             :                  * value
    3070             :                  */
    3071       31400 :                 ExecInitExprRec(source_tle->expr, state,
    3072       15700 :                                 &trans_fcinfo->args[argno + 1].value,
    3073       15700 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3074       15700 :                 argno++;
    3075             :             }
    3076             :         }
    3077        9252 :         else if (pertrans->numInputs == 1)
    3078             :         {
    3079             :             /*
    3080             :              * DISTINCT and/or ORDER BY case, with a single column sorted on.
    3081             :              */
    3082        1616 :             TargetEntry *source_tle =
    3083        1616 :             (TargetEntry *) linitial(pertrans->aggref->args);
    3084             : 
    3085             :             Assert(list_length(pertrans->aggref->args) == 1);
    3086             : 
    3087        1616 :             ExecInitExprRec(source_tle->expr, state,
    3088             :                             &state->resvalue,
    3089             :                             &state->resnull);
    3090        1616 :             strictnulls = &state->resnull;
    3091        1616 :             argno++;
    3092             :         }
    3093             :         else
    3094             :         {
    3095             :             /*
    3096             :              * DISTINCT and/or ORDER BY case, with multiple columns sorted on.
    3097             :              */
    3098        7636 :             Datum      *values = pertrans->sortslot->tts_values;
    3099        7636 :             bool       *nulls = pertrans->sortslot->tts_isnull;
    3100             : 
    3101        7636 :             strictnulls = nulls;
    3102             : 
    3103       23292 :             foreach(arg, pertrans->aggref->args)
    3104             :             {
    3105       15656 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3106             : 
    3107       31312 :                 ExecInitExprRec(source_tle->expr, state,
    3108       15656 :                                 &values[argno], &nulls[argno]);
    3109       15656 :                 argno++;
    3110             :             }
    3111             :         }
    3112             :         Assert(pertrans->numInputs == argno);
    3113             : 
    3114             :         /*
    3115             :          * For a strict transfn, nothing happens when there's a NULL input; we
    3116             :          * just keep the prior transValue. This is true for both plain and
    3117             :          * sorted/distinct aggregates.
    3118             :          */
    3119       31148 :         if (trans_fcinfo->flinfo->fn_strict && pertrans->numTransInputs > 0)
    3120             :         {
    3121        6602 :             if (strictnulls)
    3122          50 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_NULLS;
    3123             :             else
    3124        6552 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_ARGS;
    3125        6602 :             scratch.d.agg_strict_input_check.nulls = strictnulls;
    3126        6602 :             scratch.d.agg_strict_input_check.args = strictargs;
    3127        6602 :             scratch.d.agg_strict_input_check.jumpnull = -1; /* adjust later */
    3128        6602 :             scratch.d.agg_strict_input_check.nargs = pertrans->numTransInputs;
    3129        6602 :             ExprEvalPushStep(state, &scratch);
    3130        6602 :             adjust_bailout = lappend_int(adjust_bailout,
    3131        6602 :                                          state->steps_len - 1);
    3132             :         }
    3133             : 
    3134             :         /*
    3135             :          * Call transition function (once for each concurrently evaluated
    3136             :          * grouping set). Do so for both sort and hash based computations, as
    3137             :          * applicable.
    3138             :          */
    3139       31148 :         setoff = 0;
    3140       31148 :         if (doSort)
    3141             :         {
    3142       27630 :             int         processGroupingSets = Max(phase->numsets, 1);
    3143             : 
    3144       55832 :             for (setno = 0; setno < processGroupingSets; setno++)
    3145             :             {
    3146       28202 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3147             :                                       pertrans, transno, setno, setoff, false);
    3148       28202 :                 setoff++;
    3149             :             }
    3150             :         }
    3151             : 
    3152       31148 :         if (doHash)
    3153             :         {
    3154        3726 :             int         numHashes = aggstate->num_hashes;
    3155             : 
    3156             :             /* in MIXED mode, there'll be preceding transition values */
    3157        3726 :             if (aggstate->aggstrategy != AGG_HASHED)
    3158         208 :                 setoff = aggstate->maxsets;
    3159             :             else
    3160        3518 :                 setoff = 0;
    3161             : 
    3162        7948 :             for (setno = 0; setno < numHashes; setno++)
    3163             :             {
    3164        4222 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3165             :                                       pertrans, transno, setno, setoff, true);
    3166        4222 :                 setoff++;
    3167             :             }
    3168             :         }
    3169             : 
    3170             :         /* adjust early bail out jump target(s) */
    3171       38244 :         foreach(bail, adjust_bailout)
    3172             :         {
    3173        7096 :             ExprEvalStep *as = &state->steps[lfirst_int(bail)];
    3174             : 
    3175        7096 :             if (as->opcode == EEOP_JUMP_IF_NOT_TRUE)
    3176             :             {
    3177             :                 Assert(as->d.jump.jumpdone == -1);
    3178         470 :                 as->d.jump.jumpdone = state->steps_len;
    3179             :             }
    3180        6700 :             else if (as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_ARGS ||
    3181          74 :                      as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_NULLS)
    3182             :             {
    3183             :                 Assert(as->d.agg_strict_input_check.jumpnull == -1);
    3184        6602 :                 as->d.agg_strict_input_check.jumpnull = state->steps_len;
    3185             :             }
    3186          24 :             else if (as->opcode == EEOP_AGG_STRICT_DESERIALIZE)
    3187             :             {
    3188             :                 Assert(as->d.agg_deserialize.jumpnull == -1);
    3189          24 :                 as->d.agg_deserialize.jumpnull = state->steps_len;
    3190             :             }
    3191             :         }
    3192             :     }
    3193             : 
    3194       28854 :     scratch.resvalue = NULL;
    3195       28854 :     scratch.resnull = NULL;
    3196       28854 :     scratch.opcode = EEOP_DONE;
    3197       28854 :     ExprEvalPushStep(state, &scratch);
    3198             : 
    3199       28854 :     ExecReadyExpr(state);
    3200             : 
    3201       28854 :     return state;
    3202             : }
    3203             : 
    3204             : /*
    3205             :  * Build transition/combine function invocation for a single transition
    3206             :  * value. This is separated from ExecBuildAggTrans() because there are
    3207             :  * multiple callsites (hash and sort in some grouping set cases).
    3208             :  */
    3209             : static void
    3210       32424 : ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
    3211             :                       ExprEvalStep *scratch,
    3212             :                       FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
    3213             :                       int transno, int setno, int setoff, bool ishash)
    3214             : {
    3215       32424 :     int         adjust_init_jumpnull = -1;
    3216       32424 :     int         adjust_strict_jumpnull = -1;
    3217             :     ExprContext *aggcontext;
    3218             : 
    3219       32424 :     if (ishash)
    3220        4222 :         aggcontext = aggstate->hashcontext;
    3221             :     else
    3222       28202 :         aggcontext = aggstate->aggcontexts[setno];
    3223             : 
    3224             :     /*
    3225             :      * If the initial value for the transition state doesn't exist in the
    3226             :      * pg_aggregate table then we will let the first non-NULL value returned
    3227             :      * from the outer procNode become the initial value. (This is useful for
    3228             :      * aggregates like max() and min().) The noTransValue flag signals that we
    3229             :      * still need to do this.
    3230             :      */
    3231       55564 :     if (pertrans->numSortCols == 0 &&
    3232       37168 :         fcinfo->flinfo->fn_strict &&
    3233       14028 :         pertrans->initValueIsNull)
    3234             :     {
    3235        3628 :         scratch->opcode = EEOP_AGG_INIT_TRANS;
    3236        3628 :         scratch->d.agg_init_trans.aggstate = aggstate;
    3237        3628 :         scratch->d.agg_init_trans.pertrans = pertrans;
    3238        3628 :         scratch->d.agg_init_trans.setno = setno;
    3239        3628 :         scratch->d.agg_init_trans.setoff = setoff;
    3240        3628 :         scratch->d.agg_init_trans.transno = transno;
    3241        3628 :         scratch->d.agg_init_trans.aggcontext = aggcontext;
    3242        3628 :         scratch->d.agg_init_trans.jumpnull = -1; /* adjust later */
    3243        3628 :         ExprEvalPushStep(state, scratch);
    3244             : 
    3245             :         /* see comment about jumping out below */
    3246        3628 :         adjust_init_jumpnull = state->steps_len - 1;
    3247             :     }
    3248             : 
    3249       55564 :     if (pertrans->numSortCols == 0 &&
    3250       23140 :         fcinfo->flinfo->fn_strict)
    3251             :     {
    3252       14028 :         scratch->opcode = EEOP_AGG_STRICT_TRANS_CHECK;
    3253       14028 :         scratch->d.agg_strict_trans_check.aggstate = aggstate;
    3254       14028 :         scratch->d.agg_strict_trans_check.setno = setno;
    3255       14028 :         scratch->d.agg_strict_trans_check.setoff = setoff;
    3256       14028 :         scratch->d.agg_strict_trans_check.transno = transno;
    3257       14028 :         scratch->d.agg_strict_trans_check.jumpnull = -1; /* adjust later */
    3258       14028 :         ExprEvalPushStep(state, scratch);
    3259             : 
    3260             :         /*
    3261             :          * Note, we don't push into adjust_bailout here - those jump to the
    3262             :          * end of all transition value computations. Here a single transition
    3263             :          * value is NULL, so just skip processing the individual value.
    3264             :          */
    3265       14028 :         adjust_strict_jumpnull = state->steps_len - 1;
    3266             :     }
    3267             : 
    3268             :     /* invoke appropriate transition implementation */
    3269       32424 :     if (pertrans->numSortCols == 0 && pertrans->transtypeByVal)
    3270       21108 :         scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYVAL;
    3271       11316 :     else if (pertrans->numSortCols == 0)
    3272        2032 :         scratch->opcode = EEOP_AGG_PLAIN_TRANS;
    3273        9284 :     else if (pertrans->numInputs == 1)
    3274        1640 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_DATUM;
    3275             :     else
    3276        7644 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_TUPLE;
    3277             : 
    3278       32424 :     scratch->d.agg_trans.aggstate = aggstate;
    3279       32424 :     scratch->d.agg_trans.pertrans = pertrans;
    3280       32424 :     scratch->d.agg_trans.setno = setno;
    3281       32424 :     scratch->d.agg_trans.setoff = setoff;
    3282       32424 :     scratch->d.agg_trans.transno = transno;
    3283       32424 :     scratch->d.agg_trans.aggcontext = aggcontext;
    3284       32424 :     ExprEvalPushStep(state, scratch);
    3285             : 
    3286             :     /* adjust jumps so they jump till after transition invocation */
    3287       32424 :     if (adjust_init_jumpnull != -1)
    3288             :     {
    3289        3628 :         ExprEvalStep *as = &state->steps[adjust_init_jumpnull];
    3290             : 
    3291             :         Assert(as->d.agg_init_trans.jumpnull == -1);
    3292        3628 :         as->d.agg_init_trans.jumpnull = state->steps_len;
    3293             :     }
    3294       32424 :     if (adjust_strict_jumpnull != -1)
    3295             :     {
    3296       14028 :         ExprEvalStep *as = &state->steps[adjust_strict_jumpnull];
    3297             : 
    3298             :         Assert(as->d.agg_strict_trans_check.jumpnull == -1);
    3299       14028 :         as->d.agg_strict_trans_check.jumpnull = state->steps_len;
    3300             :     }
    3301       32424 : }
    3302             : 
    3303             : /*
    3304             :  * Build equality expression that can be evaluated using ExecQual(), returning
    3305             :  * true if the expression context's inner/outer tuple are NOT DISTINCT. I.e
    3306             :  * two nulls match, a null and a not-null don't match.
    3307             :  *
    3308             :  * desc: tuple descriptor of the to-be-compared tuples
    3309             :  * numCols: the number of attributes to be examined
    3310             :  * keyColIdx: array of attribute column numbers
    3311             :  * eqFunctions: array of function oids of the equality functions to use
    3312             :  * parent: parent executor node
    3313             :  */
    3314             : ExprState *
    3315        8416 : ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc,
    3316             :                        const TupleTableSlotOps *lops, const TupleTableSlotOps *rops,
    3317             :                        int numCols,
    3318             :                        const AttrNumber *keyColIdx,
    3319             :                        const Oid *eqfunctions,
    3320             :                        const Oid *collations,
    3321             :                        PlanState *parent)
    3322             : {
    3323        8416 :     ExprState  *state = makeNode(ExprState);
    3324        8416 :     ExprEvalStep scratch = {0};
    3325             :     int         natt;
    3326        8416 :     int         maxatt = -1;
    3327        8416 :     List       *adjust_jumps = NIL;
    3328             :     ListCell   *lc;
    3329             : 
    3330             :     /*
    3331             :      * When no columns are actually compared, the result's always true. See
    3332             :      * special case in ExecQual().
    3333             :      */
    3334        8416 :     if (numCols == 0)
    3335          36 :         return NULL;
    3336             : 
    3337        8380 :     state->expr = NULL;
    3338        8380 :     state->flags = EEO_FLAG_IS_QUAL;
    3339        8380 :     state->parent = parent;
    3340             : 
    3341        8380 :     scratch.resvalue = &state->resvalue;
    3342        8380 :     scratch.resnull = &state->resnull;
    3343             : 
    3344             :     /* compute max needed attribute */
    3345       19624 :     for (natt = 0; natt < numCols; natt++)
    3346             :     {
    3347       11244 :         int         attno = keyColIdx[natt];
    3348             : 
    3349       11244 :         if (attno > maxatt)
    3350       11144 :             maxatt = attno;
    3351             :     }
    3352             :     Assert(maxatt >= 0);
    3353             : 
    3354             :     /* push deform steps */
    3355        8380 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    3356        8380 :     scratch.d.fetch.last_var = maxatt;
    3357        8380 :     scratch.d.fetch.fixed = false;
    3358        8380 :     scratch.d.fetch.known_desc = ldesc;
    3359        8380 :     scratch.d.fetch.kind = lops;
    3360        8380 :     ExecComputeSlotInfo(state, &scratch);
    3361        8380 :     ExprEvalPushStep(state, &scratch);
    3362             : 
    3363        8380 :     scratch.opcode = EEOP_OUTER_FETCHSOME;
    3364        8380 :     scratch.d.fetch.last_var = maxatt;
    3365        8380 :     scratch.d.fetch.fixed = false;
    3366        8380 :     scratch.d.fetch.known_desc = rdesc;
    3367        8380 :     scratch.d.fetch.kind = rops;
    3368        8380 :     ExecComputeSlotInfo(state, &scratch);
    3369        8380 :     ExprEvalPushStep(state, &scratch);
    3370             : 
    3371             :     /*
    3372             :      * Start comparing at the last field (least significant sort key). That's
    3373             :      * the most likely to be different if we are dealing with sorted input.
    3374             :      */
    3375       28004 :     for (natt = numCols; --natt >= 0;)
    3376             :     {
    3377       11244 :         int         attno = keyColIdx[natt];
    3378       11244 :         Form_pg_attribute latt = TupleDescAttr(ldesc, attno - 1);
    3379       11244 :         Form_pg_attribute ratt = TupleDescAttr(rdesc, attno - 1);
    3380       11244 :         Oid         foid = eqfunctions[natt];
    3381       11244 :         Oid         collid = collations[natt];
    3382             :         FmgrInfo   *finfo;
    3383             :         FunctionCallInfo fcinfo;
    3384             :         AclResult   aclresult;
    3385             : 
    3386             :         /* Check permission to call function */
    3387       11244 :         aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
    3388       11244 :         if (aclresult != ACLCHECK_OK)
    3389           0 :             aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
    3390             : 
    3391       11244 :         InvokeFunctionExecuteHook(foid);
    3392             : 
    3393             :         /* Set up the primary fmgr lookup information */
    3394       11244 :         finfo = palloc0(sizeof(FmgrInfo));
    3395       11244 :         fcinfo = palloc0(SizeForFunctionCallInfo(2));
    3396       11244 :         fmgr_info(foid, finfo);
    3397       11244 :         fmgr_info_set_expr(NULL, finfo);
    3398       11244 :         InitFunctionCallInfoData(*fcinfo, finfo, 2,
    3399             :                                  collid, NULL, NULL);
    3400             : 
    3401             :         /* left arg */
    3402       11244 :         scratch.opcode = EEOP_INNER_VAR;
    3403       11244 :         scratch.d.var.attnum = attno - 1;
    3404       11244 :         scratch.d.var.vartype = latt->atttypid;
    3405       11244 :         scratch.resvalue = &fcinfo->args[0].value;
    3406       11244 :         scratch.resnull = &fcinfo->args[0].isnull;
    3407       11244 :         ExprEvalPushStep(state, &scratch);
    3408             : 
    3409             :         /* right arg */
    3410       11244 :         scratch.opcode = EEOP_OUTER_VAR;
    3411       11244 :         scratch.d.var.attnum = attno - 1;
    3412       11244 :         scratch.d.var.vartype = ratt->atttypid;
    3413       11244 :         scratch.resvalue = &fcinfo->args[1].value;
    3414       11244 :         scratch.resnull = &fcinfo->args[1].isnull;
    3415       11244 :         ExprEvalPushStep(state, &scratch);
    3416             : 
    3417             :         /* evaluate distinctness */
    3418       11244 :         scratch.opcode = EEOP_NOT_DISTINCT;
    3419       11244 :         scratch.d.func.finfo = finfo;
    3420       11244 :         scratch.d.func.fcinfo_data = fcinfo;
    3421       11244 :         scratch.d.func.fn_addr = finfo->fn_addr;
    3422       11244 :         scratch.d.func.nargs = 2;
    3423       11244 :         scratch.resvalue = &state->resvalue;
    3424       11244 :         scratch.resnull = &state->resnull;
    3425       11244 :         ExprEvalPushStep(state, &scratch);
    3426             : 
    3427             :         /* then emit EEOP_QUAL to detect if result is false (or null) */
    3428       11244 :         scratch.opcode = EEOP_QUAL;
    3429       11244 :         scratch.d.qualexpr.jumpdone = -1;
    3430       11244 :         scratch.resvalue = &state->resvalue;
    3431       11244 :         scratch.resnull = &state->resnull;
    3432       11244 :         ExprEvalPushStep(state, &scratch);
    3433       11244 :         adjust_jumps = lappend_int(adjust_jumps,
    3434       11244 :                                    state->steps_len - 1);
    3435             :     }
    3436             : 
    3437             :     /* adjust jump targets */
    3438       19624 :     foreach(lc, adjust_jumps)
    3439             :     {
    3440       11244 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    3441             : 
    3442             :         Assert(as->opcode == EEOP_QUAL);
    3443             :         Assert(as->d.qualexpr.jumpdone == -1);
    3444       11244 :         as->d.qualexpr.jumpdone = state->steps_len;
    3445             :     }
    3446             : 
    3447        8380 :     scratch.resvalue = NULL;
    3448        8380 :     scratch.resnull = NULL;
    3449        8380 :     scratch.opcode = EEOP_DONE;
    3450        8380 :     ExprEvalPushStep(state, &scratch);
    3451             : 
    3452        8380 :     ExecReadyExpr(state);
    3453             : 
    3454        8380 :     return state;
    3455             : }

Generated by: LCOV version 1.13