]> granicus.if.org Git - postgresql/blobdiff - src/backend/optimizer/plan/createplan.c
Teach planner about some cases where a restriction clause can be
[postgresql] / src / backend / optimizer / plan / createplan.c
index 1b4c9d478097b538b353384f919c92f4381283d2..959c17206c082485d690fcf036c49b859d416ca0 100644 (file)
@@ -5,12 +5,12 @@
  *       Planning is complete, we just need to convert the selected
  *       Path into a Plan.
  *
- * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/backend/optimizer/plan/createplan.c,v 1.169 2004/04/25 18:23:56 neilc Exp $
+ *       $PostgreSQL: pgsql/src/backend/optimizer/plan/createplan.c,v 1.193 2005/07/02 23:00:41 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -22,9 +22,9 @@
 #include "nodes/nodeFuncs.h"
 #include "optimizer/clauses.h"
 #include "optimizer/cost.h"
-#include "optimizer/paths.h"
 #include "optimizer/plancat.h"
 #include "optimizer/planmain.h"
+#include "optimizer/predtest.h"
 #include "optimizer/restrictinfo.h"
 #include "optimizer/tlist.h"
 #include "optimizer/var.h"
 #include "utils/syscache.h"
 
 
-static Scan *create_scan_plan(Query *root, Path *best_path);
+static Scan *create_scan_plan(PlannerInfo *root, Path *best_path);
 static List *build_relation_tlist(RelOptInfo *rel);
 static bool use_physical_tlist(RelOptInfo *rel);
 static void disuse_physical_tlist(Plan *plan, Path *path);
-static Join *create_join_plan(Query *root, JoinPath *best_path);
-static Append *create_append_plan(Query *root, AppendPath *best_path);
-static Result *create_result_plan(Query *root, ResultPath *best_path);
-static Material *create_material_plan(Query *root, MaterialPath *best_path);
-static Plan *create_unique_plan(Query *root, UniquePath *best_path);
-static SeqScan *create_seqscan_plan(Query *root, Path *best_path,
-                                                                       List *tlist, List *scan_clauses);
-static IndexScan *create_indexscan_plan(Query *root, IndexPath *best_path,
-                                         List *tlist, List *scan_clauses);
-static TidScan *create_tidscan_plan(Query *root, TidPath *best_path,
-                                                                       List *tlist, List *scan_clauses);
-static SubqueryScan *create_subqueryscan_plan(Query *root, Path *best_path,
+static Join *create_join_plan(PlannerInfo *root, JoinPath *best_path);
+static Append *create_append_plan(PlannerInfo *root, AppendPath *best_path);
+static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
+static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
+static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
+static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
+                                       List *tlist, List *scan_clauses);
+static IndexScan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
+                                         List *tlist, List *scan_clauses,
+                                         List **nonlossy_clauses);
+static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
+                                                                                          BitmapHeapPath *best_path,
+                                                                                          List *tlist, List *scan_clauses);
+static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
+                                                                  List **qual, List **indexqual);
+static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
+                                       List *tlist, List *scan_clauses);
+static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
                                                 List *tlist, List *scan_clauses);
-static FunctionScan *create_functionscan_plan(Query *root, Path *best_path,
+static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
                                                 List *tlist, List *scan_clauses);
-static NestLoop *create_nestloop_plan(Query *root, NestPath *best_path,
+static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
                                         Plan *outer_plan, Plan *inner_plan);
-static MergeJoin *create_mergejoin_plan(Query *root, MergePath *best_path,
+static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
                                          Plan *outer_plan, Plan *inner_plan);
-static HashJoin *create_hashjoin_plan(Query *root, HashPath *best_path,
+static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
                                         Plan *outer_plan, Plan *inner_plan);
-static void fix_indxqual_references(List *indexquals, IndexPath *index_path,
-                                               List **fixed_indexquals,
-                                               List **indxstrategy,
-                                               List **indxsubtype,
-                                               List **indxlossy);
-static void fix_indxqual_sublist(List *indexqual,
-                                        Relids baserelids, int baserelid,
-                                        IndexOptInfo *index,
-                                        List **fixed_quals,
-                                        List **strategy,
-                                        List **subtype,
-                                        List **lossy);
-static Node *fix_indxqual_operand(Node *node, int baserelid,
-                                        IndexOptInfo *index,
-                                        Oid *opclass);
+static void fix_indexqual_references(List *indexquals, IndexPath *index_path,
+                                                List **fixed_indexquals,
+                                                List **nonlossy_indexquals,
+                                                List **indexstrategy,
+                                                List **indexsubtype);
+static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index,
+                                                                 Oid *opclass);
 static List *get_switched_clauses(List *clauses, Relids outerrelids);
-static List *order_qual_clauses(Query *root, List *clauses);
 static void copy_path_costsize(Plan *dest, Path *src);
 static void copy_plan_costsize(Plan *dest, Plan *src);
 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
-                          List *indxid, List *indxqual, List *indxqualorig,
-                          List *indxstrategy, List *indxsubtype, List *indxlossy,
+                          Oid indexid, List *indexqual, List *indexqualorig,
+                          List *indexstrategy, List *indexsubtype,
                           ScanDirection indexscandir);
+static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
+                                                                                         List *indexqual,
+                                                                                         List *indexqualorig,
+                                                                                         List *indexstrategy,
+                                                                                         List *indexsubtype);
+static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
+                                                                                       List *qpqual,
+                                                                                       Plan *lefttree,
+                                                                                       List *bitmapqualorig,
+                                                                                       Index scanrelid);
 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
                         List *tideval);
 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
                                  Index scanrelid);
+static BitmapAnd *make_bitmap_and(List *bitmapplans);
+static BitmapOr *make_bitmap_or(List *bitmapplans);
 static NestLoop *make_nestloop(List *tlist,
                          List *joinclauses, List *otherclauses,
                          Plan *lefttree, Plan *righttree,
@@ -103,9 +112,9 @@ static MergeJoin *make_mergejoin(List *tlist,
                           List *mergeclauses,
                           Plan *lefttree, Plan *righttree,
                           JoinType jointype);
-static Sort *make_sort(Query *root, Plan *lefttree, int numCols,
+static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
                  AttrNumber *sortColIdx, Oid *sortOperators);
-static Sort *make_sort_from_pathkeys(Query *root, Plan *lefttree,
+static Sort *make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree,
                                                List *pathkeys);
 
 
@@ -125,14 +134,15 @@ static Sort *make_sort_from_pathkeys(Query *root, Plan *lefttree,
  *       Returns a Plan tree.
  */
 Plan *
-create_plan(Query *root, Path *best_path)
+create_plan(PlannerInfo *root, Path *best_path)
 {
        Plan       *plan;
 
        switch (best_path->pathtype)
        {
-               case T_IndexScan:
                case T_SeqScan:
+               case T_IndexScan:
+               case T_BitmapHeapScan:
                case T_TidScan:
                case T_SubqueryScan:
                case T_FunctionScan:
@@ -177,7 +187,7 @@ create_plan(Query *root, Path *best_path)
  *      Returns a Plan node.
  */
 static Scan *
-create_scan_plan(Query *root, Path *best_path)
+create_scan_plan(PlannerInfo *root, Path *best_path)
 {
        RelOptInfo *rel = best_path->parent;
        List       *tlist;
@@ -221,7 +231,15 @@ create_scan_plan(Query *root, Path *best_path)
                        plan = (Scan *) create_indexscan_plan(root,
                                                                                                  (IndexPath *) best_path,
                                                                                                  tlist,
-                                                                                                 scan_clauses);
+                                                                                                 scan_clauses,
+                                                                                                 NULL);
+                       break;
+
+               case T_BitmapHeapScan:
+                       plan = (Scan *) create_bitmap_scan_plan(root,
+                                                                                                       (BitmapHeapPath *) best_path,
+                                                                                                       tlist,
+                                                                                                       scan_clauses);
                        break;
 
                case T_TidScan:
@@ -261,20 +279,22 @@ create_scan_plan(Query *root, Path *best_path)
 static List *
 build_relation_tlist(RelOptInfo *rel)
 {
-       FastList        tlist;
-       int                     resdomno = 1;
-       List       *v;
+       List       *tlist = NIL;
+       int                     resno = 1;
+       ListCell   *v;
 
-       FastListInit(&tlist);
-       foreach(v, FastListValue(&rel->reltargetlist))
+       foreach(v, rel->reltargetlist)
        {
                /* Do we really need to copy here?      Not sure */
                Var                *var = (Var *) copyObject(lfirst(v));
 
-               FastAppend(&tlist, create_tl_element(var, resdomno));
-               resdomno++;
+               tlist = lappend(tlist, makeTargetEntry((Expr *) var,
+                                                                                          resno,
+                                                                                          NULL,
+                                                                                          false));
+               resno++;
        }
-       return FastListValue(&tlist);
+       return tlist;
 }
 
 /*
@@ -288,12 +308,17 @@ use_physical_tlist(RelOptInfo *rel)
        int                     i;
 
        /*
-        * Currently, can't do this for subquery or function scans.  (This is
-        * mainly because we don't have an equivalent of build_physical_tlist
-        * for them; worth adding?)
+        * OK for subquery and function scans; otherwise, can't do it for
+        * anything except real relations.
         */
        if (rel->rtekind != RTE_RELATION)
+       {
+               if (rel->rtekind == RTE_SUBQUERY)
+                       return true;
+               if (rel->rtekind == RTE_FUNCTION)
+                       return true;
                return false;
+       }
 
        /*
         * Can't do it with inheritance cases either (mainly because Append
@@ -330,8 +355,9 @@ disuse_physical_tlist(Plan *plan, Path *path)
        /* Only need to undo it for path types handled by create_scan_plan() */
        switch (path->pathtype)
        {
-               case T_IndexScan:
                case T_SeqScan:
+               case T_IndexScan:
+               case T_BitmapHeapScan:
                case T_TidScan:
                case T_SubqueryScan:
                case T_FunctionScan:
@@ -350,7 +376,7 @@ disuse_physical_tlist(Plan *plan, Path *path)
  *       Returns a Plan node.
  */
 static Join *
-create_join_plan(Query *root, JoinPath *best_path)
+create_join_plan(PlannerInfo *root, JoinPath *best_path)
 {
        Plan       *outer_plan;
        Plan       *inner_plan;
@@ -395,7 +421,7 @@ create_join_plan(Query *root, JoinPath *best_path)
         */
        if (get_loc_restrictinfo(best_path) != NIL)
                set_qpqual((Plan) plan,
-                                  nconc(get_qpqual((Plan) plan),
+                                  list_concat(get_qpqual((Plan) plan),
                                   get_actual_clauses(get_loc_restrictinfo(best_path))));
 #endif
 
@@ -410,12 +436,12 @@ create_join_plan(Query *root, JoinPath *best_path)
  *       Returns a Plan node.
  */
 static Append *
-create_append_plan(Query *root, AppendPath *best_path)
+create_append_plan(PlannerInfo *root, AppendPath *best_path)
 {
        Append     *plan;
        List       *tlist = build_relation_tlist(best_path->path.parent);
        List       *subplans = NIL;
-       List       *subpaths;
+       ListCell   *subpaths;
 
        foreach(subpaths, best_path->subpaths)
        {
@@ -437,7 +463,7 @@ create_append_plan(Query *root, AppendPath *best_path)
  *       Returns a Plan node.
  */
 static Result *
-create_result_plan(Query *root, ResultPath *best_path)
+create_result_plan(PlannerInfo *root, ResultPath *best_path)
 {
        Result     *plan;
        List       *tlist;
@@ -469,7 +495,7 @@ create_result_plan(Query *root, ResultPath *best_path)
  *       Returns a Plan node.
  */
 static Material *
-create_material_plan(Query *root, MaterialPath *best_path)
+create_material_plan(PlannerInfo *root, MaterialPath *best_path)
 {
        Material   *plan;
        Plan       *subplan;
@@ -494,7 +520,7 @@ create_material_plan(Query *root, MaterialPath *best_path)
  *       Returns a Plan node.
  */
 static Plan *
-create_unique_plan(Query *root, UniquePath *best_path)
+create_unique_plan(PlannerInfo *root, UniquePath *best_path)
 {
        Plan       *plan;
        Plan       *subplan;
@@ -505,11 +531,11 @@ create_unique_plan(Query *root, UniquePath *best_path)
        List       *newtlist;
        int                     nextresno;
        bool            newitems;
-       List       *l;
+       ListCell   *l;
 
        subplan = create_plan(root, best_path->subpath);
 
-       /*
+       /*----------
         * As constructed, the subplan has a "flat" tlist containing just the
         * Vars needed here and at upper levels.  The values we are supposed
         * to unique-ify may be expressions in these variables.  We have to
@@ -519,19 +545,20 @@ create_unique_plan(Query *root, UniquePath *best_path)
         * existing subplan outputs, not all the output columns may be used
         * for grouping.)
         *
-        * Note: the reason we don't remove any subplan outputs is that there are
-        * scenarios where a Var is needed at higher levels even though it is
-        * not one of the nominal outputs of an IN clause.      Consider WHERE x
-        * IN (SELECT y FROM t1,t2 WHERE y = z) Implied equality deduction
-        * will generate an "x = z" clause, which may get used instead of "x =
-        * y" in the upper join step.  Therefore the sub-select had better
-        * deliver both y and z in its targetlist.      It is sufficient to
-        * unique-ify on y, however.
+        * Note: the reason we don't remove any subplan outputs is that there
+        * are scenarios where a Var is needed at higher levels even though
+        * it is not one of the nominal outputs of an IN clause.        Consider
+        *              WHERE x IN (SELECT y FROM t1,t2 WHERE y = z)
+        * Implied equality deduction will generate an "x = z" clause, which may
+        * get used instead of "x = y" in the upper join step.  Therefore the
+        * sub-select had better deliver both y and z in its targetlist.
+        * It is sufficient to unique-ify on y, however.
         *
         * To find the correct list of values to unique-ify, we look in the
         * information saved for IN expressions.  If this code is ever used in
         * other scenarios, some other way of finding what to unique-ify will
         * be needed.
+        *----------
         */
        uniq_exprs = NIL;                       /* just to keep compiler quiet */
        foreach(l, root->in_info_list)
@@ -544,16 +571,16 @@ create_unique_plan(Query *root, UniquePath *best_path)
                        break;
                }
        }
-       if (l == NIL)                           /* fell out of loop? */
+       if (l == NULL)                          /* fell out of loop? */
                elog(ERROR, "could not find UniquePath in in_info_list");
 
        /* set up to record positions of unique columns */
-       numGroupCols = length(uniq_exprs);
+       numGroupCols = list_length(uniq_exprs);
        groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
        groupColPos = 0;
        /* not sure if tlist might be shared with other nodes, so copy */
        newtlist = copyObject(subplan->targetlist);
-       nextresno = length(newtlist) + 1;
+       nextresno = list_length(newtlist) + 1;
        newitems = false;
 
        foreach(l, uniq_exprs)
@@ -561,20 +588,18 @@ create_unique_plan(Query *root, UniquePath *best_path)
                Node       *uniqexpr = lfirst(l);
                TargetEntry *tle;
 
-               tle = tlistentry_member(uniqexpr, newtlist);
+               tle = tlist_member(uniqexpr, newtlist);
                if (!tle)
                {
-                       tle = makeTargetEntry(makeResdom(nextresno,
-                                                                                        exprType(uniqexpr),
-                                                                                        exprTypmod(uniqexpr),
-                                                                                        NULL,
-                                                                                        false),
-                                                                 (Expr *) uniqexpr);
+                       tle = makeTargetEntry((Expr *) uniqexpr,
+                                                                 nextresno,
+                                                                 NULL,
+                                                                 false);
                        newtlist = lappend(newtlist, tle);
                        nextresno++;
                        newitems = true;
                }
-               groupColIdx[groupColPos++] = tle->resdom->resno;
+               groupColIdx[groupColPos++] = tle->resno;
        }
 
        if (newitems)
@@ -648,7 +673,7 @@ create_unique_plan(Query *root, UniquePath *best_path)
  *      with restriction clauses 'scan_clauses' and targetlist 'tlist'.
  */
 static SeqScan *
-create_seqscan_plan(Query *root, Path *best_path,
+create_seqscan_plan(PlannerInfo *root, Path *best_path,
                                        List *tlist, List *scan_clauses)
 {
        SeqScan    *scan_plan;
@@ -675,34 +700,33 @@ create_seqscan_plan(Query *root, Path *best_path,
 
 /*
  * create_indexscan_plan
- *       Returns a indexscan plan for the base relation scanned by 'best_path'
+ *       Returns an indexscan plan for the base relation scanned by 'best_path'
  *       with restriction clauses 'scan_clauses' and targetlist 'tlist'.
  *
- * The indexquals list of the path contains a sublist of implicitly-ANDed
- * qual conditions for each scan of the index(es); if there is more than one
- * scan then the retrieved tuple sets are ORed together.  The indexquals
- * and indexinfo lists must have the same length, ie, the number of scans
- * that will occur.  Note it is possible for a qual condition sublist
- * to be empty --- then no index restrictions will be applied during that
- * scan.
+ * The indexquals list of the path contains implicitly-ANDed qual conditions.
+ * The list can be empty --- then no index restrictions will be applied during
+ * the scan.
+ *
+ * If nonlossy_clauses isn't NULL, *nonlossy_clauses receives a list of the
+ * nonlossy indexquals.
  */
 static IndexScan *
-create_indexscan_plan(Query *root,
+create_indexscan_plan(PlannerInfo *root,
                                          IndexPath *best_path,
                                          List *tlist,
-                                         List *scan_clauses)
+                                         List *scan_clauses,
+                                         List **nonlossy_clauses)
 {
-       List       *indxquals = best_path->indexquals;
+       List       *indexquals = best_path->indexquals;
        Index           baserelid = best_path->path.parent->relid;
+       Oid                     indexoid = best_path->indexinfo->indexoid;
        List       *qpqual;
-       Expr       *indxqual_or_expr = NULL;
-       List       *stripped_indxquals;
-       List       *fixed_indxquals;
-       List       *indxstrategy;
-       List       *indxsubtype;
-       List       *indxlossy;
-       FastList        indexids;
-       List       *i;
+       List       *stripped_indexquals;
+       List       *fixed_indexquals;
+       List       *nonlossy_indexquals;
+       List       *indexstrategy;
+       List       *indexsubtype;
+       ListCell   *l;
        IndexScan  *scan_plan;
 
        /* it should be a base rel... */
@@ -710,104 +734,183 @@ create_indexscan_plan(Query *root,
        Assert(best_path->path.parent->rtekind == RTE_RELATION);
 
        /*
-        * If this is a innerjoin scan, the indexclauses will contain join
+        * Build "stripped" indexquals structure (no RestrictInfos) to pass to
+        * executor as indexqualorig
+        */
+       stripped_indexquals = get_actual_clauses(indexquals);
+
+       /*
+        * The executor needs a copy with the indexkey on the left of each
+        * clause and with index attr numbers substituted for table ones. This
+        * pass also gets strategy info and looks for "lossy" operators.
+        */
+       fix_indexqual_references(indexquals, best_path,
+                                                        &fixed_indexquals,
+                                                        &nonlossy_indexquals,
+                                                        &indexstrategy,
+                                                        &indexsubtype);
+
+       /* pass back nonlossy quals if caller wants 'em */
+       if (nonlossy_clauses)
+               *nonlossy_clauses = nonlossy_indexquals;
+
+       /*
+        * If this is an innerjoin scan, the indexclauses will contain join
         * clauses that are not present in scan_clauses (since the passed-in
         * value is just the rel's baserestrictinfo list).  We must add these
-        * clauses to scan_clauses to ensure they get checked.  In most cases
+        * clauses to scan_clauses to ensure they get checked.  In most cases
         * we will remove the join clauses again below, but if a join clause
         * contains a special operator, we need to make sure it gets into the
         * scan_clauses.
+        *
+        * Note: pointer comparison should be enough to determine RestrictInfo
+        * matches.
         */
        if (best_path->isjoininner)
+               scan_clauses = list_union_ptr(scan_clauses, best_path->indexclauses);
+
+       /*
+        * The qpqual list must contain all restrictions not automatically
+        * handled by the index.  All the predicates in the indexquals will be
+        * checked (either by the index itself, or by nodeIndexscan.c), but if
+        * there are any "special" operators involved then they must be included
+        * in qpqual.  Also, any lossy index operators must be rechecked in
+        * the qpqual.  The upshot is that qpqual must contain scan_clauses
+        * minus whatever appears in nonlossy_indexquals.
+        *
+        * In normal cases simple pointer equality checks will be enough to
+        * spot duplicate RestrictInfos, so we try that first.  In some situations
+        * (particularly with OR'd index conditions) we may have scan_clauses
+        * that are not equal to, but are logically implied by, the index quals;
+        * so we also try a predicate_implied_by() check to see if we can discard
+        * quals that way.
+        *
+        * While at it, we strip off the RestrictInfos to produce a list of
+        * plain expressions.
+        */
+       qpqual = NIL;
+       foreach(l, scan_clauses)
        {
-               /*
-                * We don't currently support OR indexscans in joins, so we only
-                * need to worry about the plain AND case.  Also, pointer comparison
-                * should be enough to determine RestrictInfo matches.
-                */
-               Assert(length(best_path->indexclauses) == 1);
-               scan_clauses = set_ptrUnion(scan_clauses,
-                                                                       (List *) lfirst(best_path->indexclauses));
-       }
+               RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
 
-       /* Reduce RestrictInfo list to bare expressions */
-       scan_clauses = get_actual_clauses(scan_clauses);
+               Assert(IsA(rinfo, RestrictInfo));
+               if (list_member_ptr(nonlossy_indexquals, rinfo))
+                       continue;
+               if (predicate_implied_by(list_make1(rinfo->clause),
+                                                                nonlossy_indexquals))
+                       continue;
+               qpqual = lappend(qpqual, rinfo->clause);
+       }
 
        /* Sort clauses into best execution order */
-       scan_clauses = order_qual_clauses(root, scan_clauses);
+       qpqual = order_qual_clauses(root, qpqual);
 
-       /* Build list of index OIDs */
-       FastListInit(&indexids);
-       foreach(i, best_path->indexinfo)
-       {
-               IndexOptInfo *index = (IndexOptInfo *) lfirst(i);
+       /* Finally ready to build the plan node */
+       scan_plan = make_indexscan(tlist,
+                                                          qpqual,
+                                                          baserelid,
+                                                          indexoid,
+                                                          fixed_indexquals,
+                                                          stripped_indexquals,
+                                                          indexstrategy,
+                                                          indexsubtype,
+                                                          best_path->indexscandir);
 
-               FastAppendo(&indexids, index->indexoid);
-       }
+       copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
+       /* use the indexscan-specific rows estimate, not the parent rel's */
+       scan_plan->scan.plan.plan_rows = best_path->rows;
+
+       return scan_plan;
+}
+
+/*
+ * create_bitmap_scan_plan
+ *       Returns a bitmap scan plan for the base relation scanned by 'best_path'
+ *       with restriction clauses 'scan_clauses' and targetlist 'tlist'.
+ */
+static BitmapHeapScan *
+create_bitmap_scan_plan(PlannerInfo *root,
+                                               BitmapHeapPath *best_path,
+                                               List *tlist,
+                                               List *scan_clauses)
+{
+       Index           baserelid = best_path->path.parent->relid;
+       Plan       *bitmapqualplan;
+       List       *bitmapqualorig;
+       List       *indexquals;
+       List       *qpqual;
+       ListCell   *l;
+       BitmapHeapScan *scan_plan;
+
+       /* it should be a base rel... */
+       Assert(baserelid > 0);
+       Assert(best_path->path.parent->rtekind == RTE_RELATION);
+
+       /* Process the bitmapqual tree into a Plan tree and qual lists */
+       bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
+                                                                                  &bitmapqualorig, &indexquals);
+
+       /* Reduce RestrictInfo list to bare expressions */
+       scan_clauses = get_actual_clauses(scan_clauses);
 
        /*
-        * Build "stripped" indexquals structure (no RestrictInfos) to pass to
-        * executor as indxqualorig
+        * If this is a innerjoin scan, the indexclauses will contain join
+        * clauses that are not present in scan_clauses (since the passed-in
+        * value is just the rel's baserestrictinfo list).  We must add these
+        * clauses to scan_clauses to ensure they get checked.  In most cases
+        * we will remove the join clauses again below, but if a join clause
+        * contains a special operator, we need to make sure it gets into the
+        * scan_clauses.
         */
-       stripped_indxquals = NIL;
-       foreach(i, indxquals)
+       if (best_path->isjoininner)
        {
-               List   *andlist = (List *) lfirst(i);
-
-               stripped_indxquals = lappend(stripped_indxquals,
-                                                                        get_actual_clauses(andlist));
+               scan_clauses = list_union(scan_clauses, bitmapqualorig);
        }
 
        /*
         * The qpqual list must contain all restrictions not automatically
-        * handled by the index.  All the predicates in the indexquals will
-        * be checked (either by the index itself, or by nodeIndexscan.c), but
-        * if there are any "special" operators involved then they must be
-        * added to qpqual.  The upshot is that qpquals must contain scan_clauses
-        * minus whatever appears in indxquals.
+        * handled by the index.  All the predicates in the indexquals will be
+        * checked (either by the index itself, or by nodeBitmapHeapscan.c),
+        * but if there are any "special" or lossy operators involved then they
+        * must be added to qpqual.  The upshot is that qpquals must contain
+        * scan_clauses minus whatever appears in indexquals.
+        *
+        * In normal cases simple equal() checks will be enough to spot duplicate
+        * clauses, so we try that first.  In some situations (particularly with
+        * OR'd index conditions) we may have scan_clauses that are not equal to,
+        * but are logically implied by, the index quals; so we also try a
+        * predicate_implied_by() check to see if we can discard quals that way.
         */
-       if (length(indxquals) > 1)
-       {
-               /*
-                * Build an expression representation of the indexqual, expanding
-                * the implicit OR and AND semantics of the first- and
-                * second-level lists.  (The odds that this will exactly match any
-                * scan_clause are not great; perhaps we need more smarts here.)
-                */
-               indxqual_or_expr = make_expr_from_indexclauses(indxquals);
-               qpqual = set_difference(scan_clauses, makeList1(indxqual_or_expr));
-       }
-       else
+       qpqual = NIL;
+       foreach(l, scan_clauses)
        {
-               /*
-                * Here, we can simply treat the first sublist as an independent
-                * set of qual expressions, since there is no top-level OR
-                * behavior.
-                */
-               Assert(stripped_indxquals != NIL);
-               qpqual = set_difference(scan_clauses, lfirst(stripped_indxquals));
+               Node   *clause = (Node *) lfirst(l);
+
+               if (list_member(indexquals, clause))
+                       continue;
+               if (predicate_implied_by(list_make1(clause),
+                                                                indexquals))
+                       continue;
+               qpqual = lappend(qpqual, clause);
        }
 
+       /* Sort clauses into best execution order */
+       qpqual = order_qual_clauses(root, qpqual);
+
        /*
-        * The executor needs a copy with the indexkey on the left of each
-        * clause and with index attr numbers substituted for table ones. This
-        * pass also gets strategy info and looks for "lossy" operators.
+        * When dealing with special or lossy operators, we will at this point
+        * have duplicate clauses in qpqual and bitmapqualorig.  We may as well
+        * drop 'em from bitmapqualorig, since there's no point in making the
+        * tests twice.
         */
-       fix_indxqual_references(indxquals, best_path,
-                                                       &fixed_indxquals,
-                                                       &indxstrategy, &indxsubtype, &indxlossy);
+       bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
 
        /* Finally ready to build the plan node */
-       scan_plan = make_indexscan(tlist,
-                                                          qpqual,
-                                                          baserelid,
-                                                          FastListValue(&indexids),
-                                                          fixed_indxquals,
-                                                          stripped_indxquals,
-                                                          indxstrategy,
-                                                          indxsubtype,
-                                                          indxlossy,
-                                                          best_path->indexscandir);
+       scan_plan = make_bitmap_heapscan(tlist,
+                                                                        qpqual,
+                                                                        bitmapqualplan,
+                                                                        bitmapqualorig,
+                                                                        baserelid);
 
        copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
        /* use the indexscan-specific rows estimate, not the parent rel's */
@@ -816,13 +919,120 @@ create_indexscan_plan(Query *root,
        return scan_plan;
 }
 
+/*
+ * Given a bitmapqual tree, generate the Plan tree that implements it
+ *
+ * As byproducts, we also return in *qual and *indexqual the qual lists
+ * (in implicit-AND form, without RestrictInfos) describing the original index
+ * conditions and the generated indexqual conditions.  The latter is made to
+ * exclude lossy index operators.
+ */
+static Plan *
+create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
+                                         List **qual, List **indexqual)
+{
+       Plan       *plan;
+
+       if (IsA(bitmapqual, BitmapAndPath))
+       {
+               BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
+               List       *subplans = NIL;
+               List       *subquals = NIL;
+               List       *subindexquals = NIL;
+               ListCell   *l;
+
+               foreach(l, apath->bitmapquals)
+               {
+                       Plan   *subplan;
+                       List   *subqual;
+                       List   *subindexqual;
+
+                       subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
+                                                                                       &subqual, &subindexqual);
+                       subplans = lappend(subplans, subplan);
+                       subquals = list_concat(subquals, subqual);
+                       subindexquals = list_concat(subindexquals, subindexqual);
+               }
+               plan = (Plan *) make_bitmap_and(subplans);
+               plan->startup_cost = apath->path.startup_cost;
+               plan->total_cost = apath->path.total_cost;
+               plan->plan_rows =
+                       clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
+               plan->plan_width = 0;   /* meaningless */
+               *qual = subquals;
+               *indexqual = subindexquals;
+       }
+       else if (IsA(bitmapqual, BitmapOrPath))
+       {
+               BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
+               List       *subplans = NIL;
+               List       *subquals = NIL;
+               List       *subindexquals = NIL;
+               ListCell   *l;
+
+               foreach(l, opath->bitmapquals)
+               {
+                       Plan   *subplan;
+                       List   *subqual;
+                       List   *subindexqual;
+
+                       subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
+                                                                                       &subqual, &subindexqual);
+                       subplans = lappend(subplans, subplan);
+                       subquals = lappend(subquals,
+                                                          make_ands_explicit(subqual));
+                       subindexquals = lappend(subindexquals,
+                                                                       make_ands_explicit(subindexqual));
+               }
+               plan = (Plan *) make_bitmap_or(subplans);
+               plan->startup_cost = opath->path.startup_cost;
+               plan->total_cost = opath->path.total_cost;
+               plan->plan_rows =
+                       clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
+               plan->plan_width = 0;   /* meaningless */
+               *qual = list_make1(make_orclause(subquals));
+               *indexqual = list_make1(make_orclause(subindexquals));
+       }
+       else if (IsA(bitmapqual, IndexPath))
+       {
+               IndexPath *ipath = (IndexPath *) bitmapqual;
+               IndexScan *iscan;
+               List   *nonlossy_clauses;
+
+               /* Use the regular indexscan plan build machinery... */
+               iscan = create_indexscan_plan(root, ipath, NIL, NIL,
+                                                                         &nonlossy_clauses);
+               /* then convert to a bitmap indexscan */
+               plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
+                                                                                         iscan->indexid,
+                                                                                         iscan->indexqual,
+                                                                                         iscan->indexqualorig,
+                                                                                         iscan->indexstrategy,
+                                                                                         iscan->indexsubtype);
+               plan->startup_cost = 0.0;
+               plan->total_cost = ipath->indextotalcost;
+               plan->plan_rows =
+                       clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
+               plan->plan_width = 0;   /* meaningless */
+               *qual = get_actual_clauses(ipath->indexclauses);
+               *indexqual = get_actual_clauses(nonlossy_clauses);
+       }
+       else
+       {
+               elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
+               plan = NULL;                    /* keep compiler quiet */
+       }
+
+       return plan;
+}
+
 /*
  * create_tidscan_plan
  *      Returns a tidscan plan for the base relation scanned by 'best_path'
  *      with restriction clauses 'scan_clauses' and targetlist 'tlist'.
  */
 static TidScan *
-create_tidscan_plan(Query *root, TidPath *best_path,
+create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
                                        List *tlist, List *scan_clauses)
 {
        TidScan    *scan_plan;
@@ -854,7 +1064,7 @@ create_tidscan_plan(Query *root, TidPath *best_path,
  *      with restriction clauses 'scan_clauses' and targetlist 'tlist'.
  */
 static SubqueryScan *
-create_subqueryscan_plan(Query *root, Path *best_path,
+create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
                                                 List *tlist, List *scan_clauses)
 {
        SubqueryScan *scan_plan;
@@ -886,7 +1096,7 @@ create_subqueryscan_plan(Query *root, Path *best_path,
  *      with restriction clauses 'scan_clauses' and targetlist 'tlist'.
  */
 static FunctionScan *
-create_functionscan_plan(Query *root, Path *best_path,
+create_functionscan_plan(PlannerInfo *root, Path *best_path,
                                                 List *tlist, List *scan_clauses)
 {
        FunctionScan *scan_plan;
@@ -916,7 +1126,7 @@ create_functionscan_plan(Query *root, Path *best_path,
  *****************************************************************************/
 
 static NestLoop *
-create_nestloop_plan(Query *root,
+create_nestloop_plan(PlannerInfo *root,
                                         NestPath *best_path,
                                         Plan *outer_plan,
                                         Plan *inner_plan)
@@ -933,10 +1143,7 @@ create_nestloop_plan(Query *root,
                 * An index is being used to reduce the number of tuples scanned
                 * in the inner relation.  If there are join clauses being used
                 * with the index, we may remove those join clauses from the list
-                * of clauses that have to be checked as qpquals at the join node
-                * --- but only if there's just one indexscan in the inner path
-                * (otherwise, several different sets of clauses are being ORed
-                * together).
+                * of clauses that have to be checked as qpquals at the join node.
                 *
                 * We can also remove any join clauses that are redundant with those
                 * being used in the index scan; prior redundancy checks will not
@@ -947,16 +1154,34 @@ create_nestloop_plan(Query *root,
                 * not a special innerjoin path.
                 */
                IndexPath  *innerpath = (IndexPath *) best_path->innerjoinpath;
-               List       *indexclauses = innerpath->indexclauses;
 
-               if (innerpath->isjoininner &&
-                       length(indexclauses) == 1)              /* single indexscan? */
+               if (innerpath->isjoininner)
                {
                        joinrestrictclauses =
                                select_nonredundant_join_clauses(root,
                                                                                                 joinrestrictclauses,
-                                                                                                lfirst(indexclauses),
-                                                                                                best_path->jointype);
+                                                                                                innerpath->indexclauses,
+                                                                                                IS_OUTER_JOIN(best_path->jointype));
+               }
+       }
+       else if (IsA(best_path->innerjoinpath, BitmapHeapPath))
+       {
+               /*
+                * Same deal for bitmapped index scans.
+                */
+               BitmapHeapPath *innerpath = (BitmapHeapPath *) best_path->innerjoinpath;
+
+               if (innerpath->isjoininner)
+               {
+                       List       *bitmapclauses;
+
+                       bitmapclauses =
+                               make_restrictinfo_from_bitmapqual(innerpath->bitmapqual, true);
+                       joinrestrictclauses =
+                               select_nonredundant_join_clauses(root,
+                                                                                                joinrestrictclauses,
+                                                                                                bitmapclauses,
+                                                                                                IS_OUTER_JOIN(best_path->jointype));
                }
        }
 
@@ -990,7 +1215,7 @@ create_nestloop_plan(Query *root,
 }
 
 static MergeJoin *
-create_mergejoin_plan(Query *root,
+create_mergejoin_plan(PlannerInfo *root,
                                          MergePath *best_path,
                                          Plan *outer_plan,
                                          Plan *inner_plan)
@@ -1019,7 +1244,7 @@ create_mergejoin_plan(Query *root,
         * the list of quals that must be checked as qpquals.
         */
        mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
-       joinclauses = set_difference(joinclauses, mergeclauses);
+       joinclauses = list_difference(joinclauses, mergeclauses);
 
        /*
         * Rearrange mergeclauses, if needed, so that the outer variable is
@@ -1073,7 +1298,7 @@ create_mergejoin_plan(Query *root,
 }
 
 static HashJoin *
-create_hashjoin_plan(Query *root,
+create_hashjoin_plan(PlannerInfo *root,
                                         HashPath *best_path,
                                         Plan *outer_plan,
                                         Plan *inner_plan)
@@ -1103,7 +1328,7 @@ create_hashjoin_plan(Query *root,
         * the list of quals that must be checked as qpquals.
         */
        hashclauses = get_actual_clauses(best_path->path_hashclauses);
-       joinclauses = set_difference(joinclauses, hashclauses);
+       joinclauses = list_difference(joinclauses, hashclauses);
 
        /*
         * Rearrange hashclauses, if needed, so that the outer variable is
@@ -1145,102 +1370,56 @@ create_hashjoin_plan(Query *root,
  *****************************************************************************/
 
 /*
- * fix_indxqual_references
+ * fix_indexqual_references
  *       Adjust indexqual clauses to the form the executor's indexqual
  *       machinery needs, and check for recheckable (lossy) index conditions.
  *
- * We have four tasks here:
+ * We have five tasks here:
  *     * Remove RestrictInfo nodes from the input clauses.
  *     * Index keys must be represented by Var nodes with varattno set to the
  *       index's attribute number, not the attribute number in the original rel.
  *     * If the index key is on the right, commute the clause to put it on the
- *       left.  (Someday the executor might not need this, but for now it does.)
- *     * We must construct lists of operator strategy numbers, subtypes, and
- *       recheck (lossy-operator) flags for the top-level operators of each
- *       index clause.
- *
- * Both the input list and the "fixed" output list have the form of lists of
- * sublists of qual clauses --- the top-level list has one entry for each
- * indexscan to be performed.  The semantics are OR-of-ANDs.  Note however
- * that the input list contains RestrictInfos, while the output list doesn't.
+ *       left.
+ *     * We must construct lists of operator strategy numbers and subtypes
+ *       for the top-level operators of each index clause.
+ *     * We must detect any lossy index operators.  The API is that we return
+ *       a list of the input clauses whose operators are NOT lossy.
  *
- * fixed_indexquals receives a modified copy of the indexqual list --- the
+ * fixed_indexquals receives a modified copy of the indexquals list --- the
  * original is not changed.  Note also that the copy shares no substructure
  * with the original; this is needed in case there is a subplan in it (we need
  * two separate copies of the subplan tree, or things will go awry).
  *
- * indxstrategy receives a list of integer sublists of strategy numbers.
- * indxsubtype receives a list of OID sublists of strategy subtypes.
- * indxlossy receives a list of integer sublists of lossy-operator booleans.
+ * nonlossy_indexquals receives a list of the original input clauses (with
+ * RestrictInfos) that contain non-lossy operators.
+ *
+ * indexstrategy receives an integer list of strategy numbers.
+ * indexsubtype receives an OID list of strategy subtypes.
  */
 static void
-fix_indxqual_references(List *indexquals, IndexPath *index_path,
-                                               List **fixed_indexquals,
-                                               List **indxstrategy,
-                                               List **indxsubtype,
-                                               List **indxlossy)
+fix_indexqual_references(List *indexquals, IndexPath *index_path,
+                                                List **fixed_indexquals,
+                                                List **nonlossy_indexquals,
+                                                List **indexstrategy,
+                                                List **indexsubtype)
 {
-       Relids          baserelids = index_path->path.parent->relids;
-       int                     baserelid = index_path->path.parent->relid;
-       List       *ixinfo = index_path->indexinfo;
-       List       *i;
+       IndexOptInfo *index = index_path->indexinfo;
+       ListCell   *l;
 
        *fixed_indexquals = NIL;
-       *indxstrategy = NIL;
-       *indxsubtype = NIL;
-       *indxlossy = NIL;
-       foreach(i, indexquals)
-       {
-               List       *indexqual = lfirst(i);
-               IndexOptInfo *index = (IndexOptInfo *) lfirst(ixinfo);
-               List       *fixed_qual;
-               List       *strategy;
-               List       *subtype;
-               List       *lossy;
-
-               fix_indxqual_sublist(indexqual, baserelids, baserelid, index,
-                                                        &fixed_qual, &strategy, &subtype, &lossy);
-               *fixed_indexquals = lappend(*fixed_indexquals, fixed_qual);
-               *indxstrategy = lappend(*indxstrategy, strategy);
-               *indxsubtype = lappend(*indxsubtype, subtype);
-               *indxlossy = lappend(*indxlossy, lossy);
-
-               ixinfo = lnext(ixinfo);
-       }
-}
+       *nonlossy_indexquals = NIL;
+       *indexstrategy = NIL;
+       *indexsubtype = NIL;
 
-/*
- * Fix the sublist of indexquals to be used in a particular scan.
- *
- * For each qual clause, commute if needed to put the indexkey operand on the
- * left, and then fix its varattno.  (We do not need to change the other side
- * of the clause.)  Then determine the operator's strategy number and subtype
- * number, and check for lossy index behavior.
- *
- * Returns four lists:
- *             the list of fixed indexquals
- *             the integer list of strategy numbers
- *             the OID list of strategy subtypes
- *             the integer list of lossiness flags (1/0)
- */
-static void
-fix_indxqual_sublist(List *indexqual,
-                                        Relids baserelids, int baserelid,
-                                        IndexOptInfo *index,
-                                        List **fixed_quals,
-                                        List **strategy,
-                                        List **subtype,
-                                        List **lossy)
-{
-       List       *i;
-
-       *fixed_quals = NIL;
-       *strategy = NIL;
-       *subtype = NIL;
-       *lossy = NIL;
-       foreach(i, indexqual)
+       /*
+        * For each qual clause, commute if needed to put the indexkey operand on
+        * the left, and then fix its varattno.  (We do not need to change the
+        * other side of the clause.)  Then determine the operator's strategy
+        * number and subtype number, and check for lossy index behavior.
+        */
+       foreach(l, indexquals)
        {
-               RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
+               RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
                OpExpr     *clause;
                OpExpr     *newclause;
                Oid                     opclass;
@@ -1251,7 +1430,7 @@ fix_indxqual_sublist(List *indexqual,
                Assert(IsA(rinfo, RestrictInfo));
                clause = (OpExpr *) rinfo->clause;
                if (!IsA(clause, OpExpr) ||
-                       length(clause->args) != 2)
+                       list_length(clause->args) != 2)
                        elog(ERROR, "indexqual clause is not binary opclause");
 
                /*
@@ -1268,37 +1447,40 @@ fix_indxqual_sublist(List *indexqual,
                 * the clause.  The indexkey should be the side that refers to
                 * (only) the base relation.
                 */
-               if (!bms_equal(rinfo->left_relids, baserelids))
+               if (!bms_equal(rinfo->left_relids, index->rel->relids))
                        CommuteClause(newclause);
 
                /*
                 * Now, determine which index attribute this is, change the
                 * indexkey operand as needed, and get the index opclass.
                 */
-               lfirst(newclause->args) = fix_indxqual_operand(lfirst(newclause->args),
-                                                                                                          baserelid,
-                                                                                                          index,
-                                                                                                          &opclass);
+               linitial(newclause->args) =
+                       fix_indexqual_operand(linitial(newclause->args),
+                                                                 index,
+                                                                 &opclass);
 
-               *fixed_quals = lappend(*fixed_quals, newclause);
+               *fixed_indexquals = lappend(*fixed_indexquals, newclause);
 
                /*
-                * Look up the (possibly commuted) operator in the operator class to
-                * get its strategy numbers and the recheck indicator.  This also
-                * double-checks that we found an operator matching the index.
+                * Look up the (possibly commuted) operator in the operator class
+                * to get its strategy numbers and the recheck indicator.  This
+                * also double-checks that we found an operator matching the
+                * index.
                 */
                get_op_opclass_properties(newclause->opno, opclass,
                                                                  &stratno, &stratsubtype, &recheck);
 
-               *strategy = lappendi(*strategy, stratno);
-               *subtype = lappendo(*subtype, stratsubtype);
-               *lossy = lappendi(*lossy, (int) recheck);
+               *indexstrategy = lappend_int(*indexstrategy, stratno);
+               *indexsubtype = lappend_oid(*indexsubtype, stratsubtype);
+
+               /* If it's not lossy, add to nonlossy_indexquals */
+               if (!recheck)
+                       *nonlossy_indexquals = lappend(*nonlossy_indexquals, rinfo);
        }
 }
 
 static Node *
-fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
-                                        Oid *opclass)
+fix_indexqual_operand(Node *node, IndexOptInfo *index, Oid *opclass)
 {
        /*
         * We represent index keys by Var nodes having the varno of the base
@@ -1309,7 +1491,7 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
         */
        Var                *result;
        int                     pos;
-       List       *indexprs;
+       ListCell   *indexpr_item;
 
        /*
         * Remove any binary-compatible relabeling of the indexkey
@@ -1318,7 +1500,7 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
                node = (Node *) ((RelabelType *) node)->arg;
 
        if (IsA(node, Var) &&
-               ((Var *) node)->varno == baserelid)
+               ((Var *) node)->varno == index->rel->relid)
        {
                /* Try to match against simple index columns */
                int                     varatt = ((Var *) node)->varattno;
@@ -1340,29 +1522,29 @@ fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
        }
 
        /* Try to match against index expressions */
-       indexprs = index->indexprs;
+       indexpr_item = list_head(index->indexprs);
        for (pos = 0; pos < index->ncolumns; pos++)
        {
                if (index->indexkeys[pos] == 0)
                {
                        Node       *indexkey;
 
-                       if (indexprs == NIL)
+                       if (indexpr_item == NULL)
                                elog(ERROR, "too few entries in indexprs list");
-                       indexkey = (Node *) lfirst(indexprs);
+                       indexkey = (Node *) lfirst(indexpr_item);
                        if (indexkey && IsA(indexkey, RelabelType))
                                indexkey = (Node *) ((RelabelType *) indexkey)->arg;
                        if (equal(node, indexkey))
                        {
                                /* Found a match */
-                               result = makeVar(baserelid, pos + 1,
-                                                                exprType(lfirst(indexprs)), -1,
+                               result = makeVar(index->rel->relid, pos + 1,
+                                                                exprType(lfirst(indexpr_item)), -1,
                                                                 0);
                                /* return the correct opclass, too */
                                *opclass = index->classlist[pos];
                                return (Node *) result;
                        }
-                       indexprs = lnext(indexprs);
+                       indexpr_item = lnext(indexpr_item);
                }
        }
 
@@ -1383,11 +1565,11 @@ static List *
 get_switched_clauses(List *clauses, Relids outerrelids)
 {
        List       *t_list = NIL;
-       List       *i;
+       ListCell   *l;
 
-       foreach(i, clauses)
+       foreach(l, clauses)
        {
-               RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
+               RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
                OpExpr     *clause = (OpExpr *) restrictinfo->clause;
 
                Assert(is_opclause(clause));
@@ -1404,7 +1586,7 @@ get_switched_clauses(List *clauses, Relids outerrelids)
                        temp->opfuncid = InvalidOid;
                        temp->opresulttype = clause->opresulttype;
                        temp->opretset = clause->opretset;
-                       temp->args = listCopy(clause->args);
+                       temp->args = list_copy(clause->args);
                        /* Commute it --- note this modifies the temp node in-place. */
                        CommuteClause(temp);
                        t_list = lappend(t_list, temp);
@@ -1427,31 +1609,30 @@ get_switched_clauses(List *clauses, Relids outerrelids)
  * For now, we just move any quals that contain SubPlan references (but not
  * InitPlan references) to the end of the list.
  */
-static List *
-order_qual_clauses(Query *root, List *clauses)
+List *
+order_qual_clauses(PlannerInfo *root, List *clauses)
 {
-       FastList        nosubplans;
-       FastList        withsubplans;
-       List       *l;
+       List       *nosubplans;
+       List       *withsubplans;
+       ListCell   *l;
 
        /* No need to work hard if the query is subselect-free */
-       if (!root->hasSubLinks)
+       if (!root->parse->hasSubLinks)
                return clauses;
 
-       FastListInit(&nosubplans);
-       FastListInit(&withsubplans);
+       nosubplans = NIL;
+       withsubplans = NIL;
        foreach(l, clauses)
        {
-               Node       *clause = lfirst(l);
+               Node       *clause = (Node *) lfirst(l);
 
                if (contain_subplans(clause))
-                       FastAppend(&withsubplans, clause);
+                       withsubplans = lappend(withsubplans, clause);
                else
-                       FastAppend(&nosubplans, clause);
+                       nosubplans = lappend(nosubplans, clause);
        }
 
-       FastConcFast(&nosubplans, &withsubplans);
-       return FastListValue(&nosubplans);
+       return list_concat(nosubplans, withsubplans);
 }
 
 /*
@@ -1534,12 +1715,11 @@ static IndexScan *
 make_indexscan(List *qptlist,
                           List *qpqual,
                           Index scanrelid,
-                          List *indxid,
-                          List *indxqual,
-                          List *indxqualorig,
-                          List *indxstrategy,
-                          List *indxsubtype,
-                          List *indxlossy,
+                          Oid indexid,
+                          List *indexqual,
+                          List *indexqualorig,
+                          List *indexstrategy,
+                          List *indexsubtype,
                           ScanDirection indexscandir)
 {
        IndexScan  *node = makeNode(IndexScan);
@@ -1551,13 +1731,59 @@ make_indexscan(List *qptlist,
        plan->lefttree = NULL;
        plan->righttree = NULL;
        node->scan.scanrelid = scanrelid;
-       node->indxid = indxid;
-       node->indxqual = indxqual;
-       node->indxqualorig = indxqualorig;
-       node->indxstrategy = indxstrategy;
-       node->indxsubtype = indxsubtype;
-       node->indxlossy = indxlossy;
-       node->indxorderdir = indexscandir;
+       node->indexid = indexid;
+       node->indexqual = indexqual;
+       node->indexqualorig = indexqualorig;
+       node->indexstrategy = indexstrategy;
+       node->indexsubtype = indexsubtype;
+       node->indexorderdir = indexscandir;
+
+       return node;
+}
+
+static BitmapIndexScan *
+make_bitmap_indexscan(Index scanrelid,
+                                         Oid indexid,
+                                         List *indexqual,
+                                         List *indexqualorig,
+                                         List *indexstrategy,
+                                         List *indexsubtype)
+{
+       BitmapIndexScan *node = makeNode(BitmapIndexScan);
+       Plan       *plan = &node->scan.plan;
+
+       /* cost should be inserted by caller */
+       plan->targetlist = NIL;         /* not used */
+       plan->qual = NIL;                       /* not used */
+       plan->lefttree = NULL;
+       plan->righttree = NULL;
+       node->scan.scanrelid = scanrelid;
+       node->indexid = indexid;
+       node->indexqual = indexqual;
+       node->indexqualorig = indexqualorig;
+       node->indexstrategy = indexstrategy;
+       node->indexsubtype = indexsubtype;
+
+       return node;
+}
+
+static BitmapHeapScan *
+make_bitmap_heapscan(List *qptlist,
+                                        List *qpqual,
+                                        Plan *lefttree,
+                                        List *bitmapqualorig,
+                                        Index scanrelid)
+{
+       BitmapHeapScan *node = makeNode(BitmapHeapScan);
+       Plan       *plan = &node->scan.plan;
+
+       /* cost should be inserted by caller */
+       plan->targetlist = qptlist;
+       plan->qual = qpqual;
+       plan->lefttree = lefttree;
+       plan->righttree = NULL;
+       node->scan.scanrelid = scanrelid;
+       node->bitmapqualorig = bitmapqualorig;
 
        return node;
 }
@@ -1632,7 +1858,7 @@ make_append(List *appendplans, bool isTarget, List *tlist)
 {
        Append     *node = makeNode(Append);
        Plan       *plan = &node->plan;
-       List       *subnode;
+       ListCell   *subnode;
 
        /*
         * Compute cost as sum of subplan costs.  We charge nothing extra for
@@ -1647,7 +1873,7 @@ make_append(List *appendplans, bool isTarget, List *tlist)
        {
                Plan       *subplan = (Plan *) lfirst(subnode);
 
-               if (subnode == appendplans)             /* first node? */
+               if (subnode == list_head(appendplans))  /* first node? */
                        plan->startup_cost = subplan->startup_cost;
                plan->total_cost += subplan->total_cost;
                plan->plan_rows += subplan->plan_rows;
@@ -1665,6 +1891,38 @@ make_append(List *appendplans, bool isTarget, List *tlist)
        return node;
 }
 
+static BitmapAnd *
+make_bitmap_and(List *bitmapplans)
+{
+       BitmapAnd  *node = makeNode(BitmapAnd);
+       Plan       *plan = &node->plan;
+
+       /* cost should be inserted by caller */
+       plan->targetlist = NIL;
+       plan->qual = NIL;
+       plan->lefttree = NULL;
+       plan->righttree = NULL;
+       node->bitmapplans = bitmapplans;
+
+       return node;
+}
+
+static BitmapOr *
+make_bitmap_or(List *bitmapplans)
+{
+       BitmapOr   *node = makeNode(BitmapOr);
+       Plan       *plan = &node->plan;
+
+       /* cost should be inserted by caller */
+       plan->targetlist = NIL;
+       plan->qual = NIL;
+       plan->lefttree = NULL;
+       plan->righttree = NULL;
+       node->bitmapplans = bitmapplans;
+
+       return node;
+}
+
 static NestLoop *
 make_nestloop(List *tlist,
                          List *joinclauses,
@@ -1762,7 +2020,7 @@ make_mergejoin(List *tlist,
  * Caller must have built the sortColIdx and sortOperators arrays already.
  */
 static Sort *
-make_sort(Query *root, Plan *lefttree, int numCols,
+make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
                  AttrNumber *sortColIdx, Oid *sortOperators)
 {
        Sort       *node = makeNode(Sort);
@@ -1834,16 +2092,19 @@ add_sort_column(AttrNumber colIdx, Oid sortOp,
  * adding a Result node just to do the projection.
  */
 static Sort *
-make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
+make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys)
 {
        List       *tlist = lefttree->targetlist;
-       List       *i;
+       ListCell   *i;
        int                     numsortkeys;
        AttrNumber *sortColIdx;
        Oid                *sortOperators;
 
-       /* We will need at most length(pathkeys) sort columns; possibly less */
-       numsortkeys = length(pathkeys);
+       /*
+        * We will need at most list_length(pathkeys) sort columns; possibly
+        * less
+        */
+       numsortkeys = list_length(pathkeys);
        sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
        sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
 
@@ -1853,8 +2114,8 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
        {
                List       *keysublist = (List *) lfirst(i);
                PathKeyItem *pathkey = NULL;
-               Resdom     *resdom = NULL;
-               List       *j;
+               TargetEntry *tle = NULL;
+               ListCell   *j;
 
                /*
                 * We can sort by any one of the sort key items listed in this
@@ -1870,28 +2131,28 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
                 */
                foreach(j, keysublist)
                {
-                       pathkey = lfirst(j);
+                       pathkey = (PathKeyItem *) lfirst(j);
                        Assert(IsA(pathkey, PathKeyItem));
-                       resdom = tlist_member(pathkey->key, tlist);
-                       if (resdom)
+                       tle = tlist_member(pathkey->key, tlist);
+                       if (tle)
                                break;
                }
-               if (!resdom)
+               if (!tle)
                {
                        /* No matching Var; look for a computable expression */
                        foreach(j, keysublist)
                        {
-                               List   *exprvars;
-                               List   *k;
+                               List       *exprvars;
+                               ListCell   *k;
 
-                               pathkey = lfirst(j);
+                               pathkey = (PathKeyItem *) lfirst(j);
                                exprvars = pull_var_clause(pathkey->key, false);
                                foreach(k, exprvars)
                                {
                                        if (!tlist_member(lfirst(k), tlist))
                                                break;
                                }
-                               freeList(exprvars);
+                               list_free(exprvars);
                                if (!k)
                                        break;          /* found usable expression */
                        }
@@ -1910,14 +2171,11 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
                        /*
                         * Add resjunk entry to input's tlist
                         */
-                       resdom = makeResdom(length(tlist) + 1,
-                                                               exprType(pathkey->key),
-                                                               exprTypmod(pathkey->key),
-                                                               NULL,
-                                                               true);
-                       tlist = lappend(tlist,
-                                                       makeTargetEntry(resdom,
-                                                                                       (Expr *) pathkey->key));
+                       tle = makeTargetEntry((Expr *) pathkey->key,
+                                                                 list_length(tlist) + 1,
+                                                                 NULL,
+                                                                 true);
+                       tlist = lappend(tlist, tle);
                        lefttree->targetlist = tlist;           /* just in case NIL before */
                }
 
@@ -1927,7 +2185,7 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
                 * scenarios where multiple mergejoinable clauses mention the same
                 * var, for example.)  So enter it only once in the sort arrays.
                 */
-               numsortkeys = add_sort_column(resdom->resno, pathkey->sortop,
+               numsortkeys = add_sort_column(tle->resno, pathkey->sortop,
                                                                 numsortkeys, sortColIdx, sortOperators);
        }
 
@@ -1945,24 +2203,27 @@ make_sort_from_pathkeys(Query *root, Plan *lefttree, List *pathkeys)
  *       'lefttree' is the node which yields input tuples
  */
 Sort *
-make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree)
+make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
 {
        List       *sub_tlist = lefttree->targetlist;
-       List       *i;
+       ListCell   *l;
        int                     numsortkeys;
        AttrNumber *sortColIdx;
        Oid                *sortOperators;
 
-       /* We will need at most length(sortcls) sort columns; possibly less */
-       numsortkeys = length(sortcls);
+       /*
+        * We will need at most list_length(sortcls) sort columns; possibly
+        * less
+        */
+       numsortkeys = list_length(sortcls);
        sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
        sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
 
        numsortkeys = 0;
 
-       foreach(i, sortcls)
+       foreach(l, sortcls)
        {
-               SortClause *sortcl = (SortClause *) lfirst(i);
+               SortClause *sortcl = (SortClause *) lfirst(l);
                TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
 
                /*
@@ -1970,7 +2231,7 @@ make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree)
                 * parser should have removed 'em, but no point in sorting
                 * redundantly.
                 */
-               numsortkeys = add_sort_column(tle->resdom->resno, sortcl->sortop,
+               numsortkeys = add_sort_column(tle->resno, sortcl->sortop,
                                                                 numsortkeys, sortColIdx, sortOperators);
        }
 
@@ -1994,28 +2255,31 @@ make_sort_from_sortclauses(Query *root, List *sortcls, Plan *lefttree)
  * GroupClause entries.
  */
 Sort *
-make_sort_from_groupcols(Query *root,
+make_sort_from_groupcols(PlannerInfo *root,
                                                 List *groupcls,
                                                 AttrNumber *grpColIdx,
                                                 Plan *lefttree)
 {
        List       *sub_tlist = lefttree->targetlist;
        int                     grpno = 0;
-       List       *i;
+       ListCell   *l;
        int                     numsortkeys;
        AttrNumber *sortColIdx;
        Oid                *sortOperators;
 
-       /* We will need at most length(groupcls) sort columns; possibly less */
-       numsortkeys = length(groupcls);
+       /*
+        * We will need at most list_length(groupcls) sort columns; possibly
+        * less
+        */
+       numsortkeys = list_length(groupcls);
        sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
        sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
 
        numsortkeys = 0;
 
-       foreach(i, groupcls)
+       foreach(l, groupcls)
        {
-               GroupClause *grpcl = (GroupClause *) lfirst(i);
+               GroupClause *grpcl = (GroupClause *) lfirst(l);
                TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
 
                /*
@@ -2023,7 +2287,7 @@ make_sort_from_groupcols(Query *root,
                 * parser should have removed 'em, but no point in sorting
                 * redundantly.
                 */
-               numsortkeys = add_sort_column(tle->resdom->resno, grpcl->sortop,
+               numsortkeys = add_sort_column(tle->resno, grpcl->sortop,
                                                                 numsortkeys, sortColIdx, sortOperators);
                grpno++;
        }
@@ -2085,7 +2349,7 @@ materialize_finished_plan(Plan *subplan)
 }
 
 Agg *
-make_agg(Query *root, List *tlist, List *qual,
+make_agg(PlannerInfo *root, List *tlist, List *qual,
                 AggStrategy aggstrategy,
                 int numGroupCols, AttrNumber *grpColIdx,
                 long numGroups, int numAggs,
@@ -2150,8 +2414,9 @@ make_agg(Query *root, List *tlist, List *qual,
 }
 
 Group *
-make_group(Query *root,
+make_group(PlannerInfo *root,
                   List *tlist,
+                  List *qual,
                   int numGroupCols,
                   AttrNumber *grpColIdx,
                   double numGroups,
@@ -2178,7 +2443,8 @@ make_group(Query *root,
        plan->plan_rows = numGroups;
 
        /*
-        * We also need to account for the cost of evaluation of the tlist.
+        * We also need to account for the cost of evaluation of the qual (ie,
+        * the HAVING clause) and the tlist.
         *
         * XXX this double-counts the cost of evaluation of any expressions used
         * for grouping, since in reality those will have been evaluated at a
@@ -2188,12 +2454,19 @@ make_group(Query *root,
         * See notes in grouping_planner about why this routine and make_agg are
         * the only ones in this file that worry about tlist eval cost.
         */
+       if (qual)
+       {
+               cost_qual_eval(&qual_cost, qual);
+               plan->startup_cost += qual_cost.startup;
+               plan->total_cost += qual_cost.startup;
+               plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
+       }
        cost_qual_eval(&qual_cost, tlist);
        plan->startup_cost += qual_cost.startup;
        plan->total_cost += qual_cost.startup;
        plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
 
-       plan->qual = NIL;
+       plan->qual = qual;
        plan->targetlist = tlist;
        plan->lefttree = lefttree;
        plan->righttree = NULL;
@@ -2210,10 +2483,10 @@ make_unique(Plan *lefttree, List *distinctList)
 {
        Unique     *node = makeNode(Unique);
        Plan       *plan = &node->plan;
-       int                     numCols = length(distinctList);
+       int                     numCols = list_length(distinctList);
        int                     keyno = 0;
        AttrNumber *uniqColIdx;
-       List       *slitem;
+       ListCell   *slitem;
 
        copy_plan_costsize(plan, lefttree);
 
@@ -2247,7 +2520,7 @@ make_unique(Plan *lefttree, List *distinctList)
                SortClause *sortcl = (SortClause *) lfirst(slitem);
                TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
 
-               uniqColIdx[keyno++] = tle->resdom->resno;
+               uniqColIdx[keyno++] = tle->resno;
        }
 
        node->numCols = numCols;
@@ -2267,10 +2540,10 @@ make_setop(SetOpCmd cmd, Plan *lefttree,
 {
        SetOp      *node = makeNode(SetOp);
        Plan       *plan = &node->plan;
-       int                     numCols = length(distinctList);
+       int                     numCols = list_length(distinctList);
        int                     keyno = 0;
        AttrNumber *dupColIdx;
-       List       *slitem;
+       ListCell   *slitem;
 
        copy_plan_costsize(plan, lefttree);
 
@@ -2305,7 +2578,7 @@ make_setop(SetOpCmd cmd, Plan *lefttree,
                SortClause *sortcl = (SortClause *) lfirst(slitem);
                TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
 
-               dupColIdx[keyno++] = tle->resdom->resno;
+               dupColIdx[keyno++] = tle->resno;
        }
 
        node->cmd = cmd;