i965: Only consider fixed_hw_reg in equals() if file is HW_REG/IMM.
[mesa.git] / src / mesa / drivers / dri / i965 / brw_vec4.cpp
index 9102be268d98d4b4782e3aa571dc54363a39a408..b97b6c13a13d3646504a37cd0cd231ce63086964 100644 (file)
  */
 
 #include "brw_vec4.h"
+#include "brw_fs.h"
 #include "brw_cfg.h"
 #include "brw_vs.h"
+#include "brw_nir.h"
+#include "brw_vec4_live_variables.h"
 #include "brw_dead_control_flow.h"
 
 extern "C" {
@@ -32,6 +35,7 @@ extern "C" {
 #include "program/prog_print.h"
 #include "program/prog_parameter.h"
 }
+#include "main/context.h"
 
 #define MAX_INSTRUCTION (1 << 30)
 
@@ -39,26 +43,6 @@ using namespace brw;
 
 namespace brw {
 
-/**
- * Common helper for constructing swizzles.  When only a subset of
- * channels of a vec4 are used, we don't want to reference the other
- * channels, as that will tell optimization passes that those other
- * channels are used.
- */
-unsigned
-swizzle_for_size(int size)
-{
-   static const unsigned size_swizzles[4] = {
-      BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
-      BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
-      BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
-      BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
-   };
-
-   assert((size >= 1) && (size <= 4));
-   return size_swizzles[size - 1];
-}
-
 void
 src_reg::init()
 {
@@ -74,7 +58,7 @@ src_reg::src_reg(register_file file, int reg, const glsl_type *type)
    this->file = file;
    this->reg = reg;
    if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
-      this->swizzle = swizzle_for_size(type->vector_elements);
+      this->swizzle = brw_swizzle_for_size(type->vector_elements);
    else
       this->swizzle = BRW_SWIZZLE_XYZW;
 }
@@ -112,6 +96,27 @@ src_reg::src_reg(int32_t i)
    this->fixed_hw_reg.dw1.d = i;
 }
 
+src_reg::src_reg(uint8_t vf[4])
+{
+   init();
+
+   this->file = IMM;
+   this->type = BRW_REGISTER_TYPE_VF;
+   memcpy(&this->fixed_hw_reg.dw1.ud, vf, sizeof(unsigned));
+}
+
+src_reg::src_reg(uint8_t vf0, uint8_t vf1, uint8_t vf2, uint8_t vf3)
+{
+   init();
+
+   this->file = IMM;
+   this->type = BRW_REGISTER_TYPE_VF;
+   this->fixed_hw_reg.dw1.ud = (vf0 <<  0) |
+                               (vf1 <<  8) |
+                               (vf2 << 16) |
+                               (vf3 << 24);
+}
+
 src_reg::src_reg(struct brw_reg reg)
 {
    init();
@@ -121,7 +126,7 @@ src_reg::src_reg(struct brw_reg reg)
    this->type = reg.type;
 }
 
-src_reg::src_reg(dst_reg reg)
+src_reg::src_reg(const dst_reg &reg)
 {
    init();
 
@@ -131,24 +136,7 @@ src_reg::src_reg(dst_reg reg)
    this->type = reg.type;
    this->reladdr = reg.reladdr;
    this->fixed_hw_reg = reg.fixed_hw_reg;
-
-   int swizzles[4];
-   int next_chan = 0;
-   int last = 0;
-
-   for (int i = 0; i < 4; i++) {
-      if (!(reg.writemask & (1 << i)))
-         continue;
-
-      swizzles[next_chan++] = last = i;
-   }
-
-   for (; next_chan < 4; next_chan++) {
-      swizzles[next_chan] = last;
-   }
-
-   this->swizzle = BRW_SWIZZLE4(swizzles[0], swizzles[1],
-                                swizzles[2], swizzles[3]);
+   this->swizzle = brw_swizzle_for_mask(reg.writemask);
 }
 
 void
@@ -173,7 +161,7 @@ dst_reg::dst_reg(register_file file, int reg)
 }
 
 dst_reg::dst_reg(register_file file, int reg, const glsl_type *type,
-                 int writemask)
+                 unsigned writemask)
 {
    init();
 
@@ -183,6 +171,17 @@ dst_reg::dst_reg(register_file file, int reg, const glsl_type *type,
    this->writemask = writemask;
 }
 
+dst_reg::dst_reg(register_file file, int reg, brw_reg_type type,
+                 unsigned writemask)
+{
+   init();
+
+   this->file = file;
+   this->reg = reg;
+   this->type = type;
+   this->writemask = writemask;
+}
+
 dst_reg::dst_reg(struct brw_reg reg)
 {
    init();
@@ -192,7 +191,7 @@ dst_reg::dst_reg(struct brw_reg reg)
    this->type = reg.type;
 }
 
-dst_reg::dst_reg(src_reg reg)
+dst_reg::dst_reg(const src_reg &reg)
 {
    init();
 
@@ -200,34 +199,74 @@ dst_reg::dst_reg(src_reg reg)
    this->reg = reg.reg;
    this->reg_offset = reg.reg_offset;
    this->type = reg.type;
-   /* How should we do writemasking when converting from a src_reg?  It seems
-    * pretty obvious that for src.xxxx the caller wants to write to src.x, but
-    * what about for src.wx?  Just special-case src.xxxx for now.
-    */
-   if (reg.swizzle == BRW_SWIZZLE_XXXX)
-      this->writemask = WRITEMASK_X;
-   else
-      this->writemask = WRITEMASK_XYZW;
+   this->writemask = brw_mask_for_swizzle(reg.swizzle);
    this->reladdr = reg.reladdr;
    this->fixed_hw_reg = reg.fixed_hw_reg;
 }
 
+bool
+dst_reg::equals(const dst_reg &r) const
+{
+   return (file == r.file &&
+           reg == r.reg &&
+           reg_offset == r.reg_offset &&
+           type == r.type &&
+           negate == r.negate &&
+           abs == r.abs &&
+           writemask == r.writemask &&
+           (reladdr == r.reladdr ||
+            (reladdr && r.reladdr && reladdr->equals(*r.reladdr))) &&
+           ((file != HW_REG && file != IMM) ||
+            memcmp(&fixed_hw_reg, &r.fixed_hw_reg,
+                   sizeof(fixed_hw_reg)) == 0));
+}
+
 bool
 vec4_instruction::is_send_from_grf()
 {
    switch (opcode) {
    case SHADER_OPCODE_SHADER_TIME_ADD:
    case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
+   case SHADER_OPCODE_UNTYPED_ATOMIC:
+   case SHADER_OPCODE_UNTYPED_SURFACE_READ:
+   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
+   case SHADER_OPCODE_TYPED_ATOMIC:
+   case SHADER_OPCODE_TYPED_SURFACE_READ:
+   case SHADER_OPCODE_TYPED_SURFACE_WRITE:
       return true;
    default:
       return false;
    }
 }
 
+unsigned
+vec4_instruction::regs_read(unsigned arg) const
+{
+   if (src[arg].file == BAD_FILE)
+      return 0;
+
+   switch (opcode) {
+   case SHADER_OPCODE_SHADER_TIME_ADD:
+   case SHADER_OPCODE_UNTYPED_ATOMIC:
+   case SHADER_OPCODE_UNTYPED_SURFACE_READ:
+   case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
+   case SHADER_OPCODE_TYPED_ATOMIC:
+   case SHADER_OPCODE_TYPED_SURFACE_READ:
+   case SHADER_OPCODE_TYPED_SURFACE_WRITE:
+      return arg == 0 ? mlen : 1;
+
+   case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
+      return arg == 1 ? mlen : 1;
+
+   default:
+      return 1;
+   }
+}
+
 bool
-vec4_instruction::can_do_source_mods(struct brw_context *brw)
+vec4_instruction::can_do_source_mods(const struct brw_device_info *devinfo)
 {
-   if (brw->gen == 6 && is_math())
+   if (devinfo->gen == 6 && is_math())
       return false;
 
    if (is_send_from_grf())
@@ -249,7 +288,7 @@ vec4_instruction::can_do_source_mods(struct brw_context *brw)
 int
 vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
 {
-   if (inst->mlen == 0)
+   if (inst->mlen == 0 || inst->is_send_from_grf())
       return 0;
 
    switch (inst->opcode) {
@@ -274,8 +313,11 @@ vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
    case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
       return 3;
    case GS_OPCODE_URB_WRITE:
+   case GS_OPCODE_URB_WRITE_ALLOCATE:
    case GS_OPCODE_THREAD_END:
       return 0;
+   case GS_OPCODE_FF_SYNC:
+      return 1;
    case SHADER_OPCODE_SHADER_TIME_ADD:
       return 0;
    case SHADER_OPCODE_TEX:
@@ -287,10 +329,7 @@ vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
    case SHADER_OPCODE_TXS:
    case SHADER_OPCODE_TG4:
    case SHADER_OPCODE_TG4_OFFSET:
-      return inst->header_present ? 1 : 0;
-   case SHADER_OPCODE_UNTYPED_ATOMIC:
-   case SHADER_OPCODE_UNTYPED_SURFACE_READ:
-      return 0;
+      return inst->header_size;
    default:
       unreachable("not reached");
    }
@@ -311,6 +350,72 @@ src_reg::equals(const src_reg &r) const
                  sizeof(fixed_hw_reg)) == 0);
 }
 
+bool
+vec4_visitor::opt_vector_float()
+{
+   bool progress = false;
+
+   int last_reg = -1, last_reg_offset = -1;
+   enum register_file last_reg_file = BAD_FILE;
+
+   int remaining_channels = 0;
+   uint8_t imm[4];
+   int inst_count = 0;
+   vec4_instruction *imm_inst[4];
+
+   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
+      if (last_reg != inst->dst.reg ||
+          last_reg_offset != inst->dst.reg_offset ||
+          last_reg_file != inst->dst.file) {
+         last_reg = inst->dst.reg;
+         last_reg_offset = inst->dst.reg_offset;
+         last_reg_file = inst->dst.file;
+         remaining_channels = WRITEMASK_XYZW;
+
+         inst_count = 0;
+      }
+
+      if (inst->opcode != BRW_OPCODE_MOV ||
+          inst->dst.writemask == WRITEMASK_XYZW ||
+          inst->src[0].file != IMM)
+         continue;
+
+      int vf = brw_float_to_vf(inst->src[0].fixed_hw_reg.dw1.f);
+      if (vf == -1)
+         continue;
+
+      if ((inst->dst.writemask & WRITEMASK_X) != 0)
+         imm[0] = vf;
+      if ((inst->dst.writemask & WRITEMASK_Y) != 0)
+         imm[1] = vf;
+      if ((inst->dst.writemask & WRITEMASK_Z) != 0)
+         imm[2] = vf;
+      if ((inst->dst.writemask & WRITEMASK_W) != 0)
+         imm[3] = vf;
+
+      imm_inst[inst_count++] = inst;
+
+      remaining_channels &= ~inst->dst.writemask;
+      if (remaining_channels == 0) {
+         vec4_instruction *mov = MOV(inst->dst, imm);
+         mov->dst.type = BRW_REGISTER_TYPE_F;
+         mov->dst.writemask = WRITEMASK_XYZW;
+         inst->insert_after(block, mov);
+         last_reg = -1;
+
+         for (int i = 0; i < inst_count; i++) {
+            imm_inst[i]->remove(block);
+         }
+         progress = true;
+      }
+   }
+
+   if (progress)
+      invalidate_live_intervals();
+
+   return progress;
+}
+
 /* Replaces unused channels of a swizzle with channels that are used.
  *
  * For instance, this pass transforms
@@ -329,59 +434,33 @@ vec4_visitor::opt_reduce_swizzle()
 {
    bool progress = false;
 
-   foreach_in_list_safe(vec4_instruction, inst, &instructions) {
-      if (inst->dst.file == BAD_FILE || inst->dst.file == HW_REG)
+   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
+      if (inst->dst.file == BAD_FILE || inst->dst.file == HW_REG ||
+          inst->is_send_from_grf())
          continue;
 
-      int swizzle[4];
+      unsigned swizzle;
 
       /* Determine which channels of the sources are read. */
       switch (inst->opcode) {
+      case VEC4_OPCODE_PACK_BYTES:
       case BRW_OPCODE_DP4:
       case BRW_OPCODE_DPH: /* FINISHME: DPH reads only three channels of src0,
                             *           but all four of src1.
                             */
-         swizzle[0] = 0;
-         swizzle[1] = 1;
-         swizzle[2] = 2;
-         swizzle[3] = 3;
+         swizzle = brw_swizzle_for_size(4);
          break;
       case BRW_OPCODE_DP3:
-         swizzle[0] = 0;
-         swizzle[1] = 1;
-         swizzle[2] = 2;
-         swizzle[3] = -1;
+         swizzle = brw_swizzle_for_size(3);
          break;
       case BRW_OPCODE_DP2:
-         swizzle[0] = 0;
-         swizzle[1] = 1;
-         swizzle[2] = -1;
-         swizzle[3] = -1;
+         swizzle = brw_swizzle_for_size(2);
          break;
       default:
-         swizzle[0] = inst->dst.writemask & WRITEMASK_X ? 0 : -1;
-         swizzle[1] = inst->dst.writemask & WRITEMASK_Y ? 1 : -1;
-         swizzle[2] = inst->dst.writemask & WRITEMASK_Z ? 2 : -1;
-         swizzle[3] = inst->dst.writemask & WRITEMASK_W ? 3 : -1;
+         swizzle = brw_swizzle_for_mask(inst->dst.writemask);
          break;
       }
 
-      /* Resolve unread channels (-1) by assigning them the swizzle of the
-       * first channel that is used.
-       */
-      int first_used_channel = 0;
-      for (int i = 0; i < 4; i++) {
-         if (swizzle[i] != -1) {
-            first_used_channel = swizzle[i];
-            break;
-         }
-      }
-      for (int i = 0; i < 4; i++) {
-         if (swizzle[i] == -1) {
-            swizzle[i] = first_used_channel;
-         }
-      }
-
       /* Update sources' swizzles. */
       for (int i = 0; i < 3; i++) {
          if (inst->src[i].file != GRF &&
@@ -389,12 +468,8 @@ vec4_visitor::opt_reduce_swizzle()
              inst->src[i].file != UNIFORM)
             continue;
 
-         int swiz[4];
-         for (int j = 0; j < 4; j++) {
-            swiz[j] = BRW_GET_SWZ(inst->src[i].swizzle, swizzle[j]);
-         }
-
-         unsigned new_swizzle = BRW_SWIZZLE4(swiz[0], swiz[1], swiz[2], swiz[3]);
+         const unsigned new_swizzle =
+            brw_compose_swizzle(swizzle, inst->src[i].swizzle);
          if (inst->src[i].swizzle != new_swizzle) {
             inst->src[i].swizzle = new_swizzle;
             progress = true;
@@ -402,157 +477,6 @@ vec4_visitor::opt_reduce_swizzle()
       }
    }
 
-   if (progress)
-      invalidate_live_intervals(false);
-
-   return progress;
-}
-
-static bool
-try_eliminate_instruction(vec4_instruction *inst, int new_writemask,
-                          const struct brw_context *brw)
-{
-   if (inst->has_side_effects())
-      return false;
-
-   if (new_writemask == 0) {
-      /* Don't dead code eliminate instructions that write to the
-       * accumulator as a side-effect. Instead just set the destination
-       * to the null register to free it.
-       */
-      if (inst->writes_accumulator || inst->writes_flag()) {
-         inst->dst = dst_reg(retype(brw_null_reg(), inst->dst.type));
-      } else {
-         inst->remove();
-      }
-
-      return true;
-   } else if (inst->dst.writemask != new_writemask) {
-      switch (inst->opcode) {
-      case SHADER_OPCODE_TXF_CMS:
-      case SHADER_OPCODE_GEN4_SCRATCH_READ:
-      case VS_OPCODE_PULL_CONSTANT_LOAD:
-      case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
-         break;
-      default:
-         /* Do not set a writemask on Gen6 for math instructions, those are
-          * executed using align1 mode that does not support a destination mask.
-          */
-         if (!(brw->gen == 6 && inst->is_math()) && !inst->is_tex()) {
-            inst->dst.writemask = new_writemask;
-            return true;
-         }
-      }
-   }
-
-   return false;
-}
-
-/**
- * Must be called after calculate_live_intervals() to remove unused
- * writes to registers -- register allocation will fail otherwise
- * because something deffed but not used won't be considered to
- * interfere with other regs.
- */
-bool
-vec4_visitor::dead_code_eliminate()
-{
-   bool progress = false;
-   int pc = -1;
-
-   calculate_live_intervals();
-
-   foreach_in_list_safe(vec4_instruction, inst, &instructions) {
-      pc++;
-
-      bool inst_writes_flag = false;
-      if (inst->dst.file != GRF) {
-         if (inst->dst.is_null() && inst->writes_flag()) {
-            inst_writes_flag = true;
-         } else {
-            continue;
-         }
-      }
-
-      if (inst->dst.file == GRF) {
-         int write_mask = inst->dst.writemask;
-
-         for (int c = 0; c < 4; c++) {
-            if (write_mask & (1 << c)) {
-               assert(this->virtual_grf_end[inst->dst.reg * 4 + c] >= pc);
-               if (this->virtual_grf_end[inst->dst.reg * 4 + c] == pc) {
-                  write_mask &= ~(1 << c);
-               }
-            }
-         }
-
-         progress = try_eliminate_instruction(inst, write_mask, brw) ||
-                    progress;
-      }
-
-      if (inst->predicate || inst->prev == NULL)
-         continue;
-
-      int dead_channels;
-      if (inst_writes_flag) {
-/* Arbitrarily chosen, other than not being an xyzw writemask. */
-#define FLAG_WRITEMASK (1 << 5)
-         dead_channels = inst->reads_flag() ? 0 : FLAG_WRITEMASK;
-      } else {
-         dead_channels = inst->dst.writemask;
-
-         for (int i = 0; i < 3; i++) {
-            if (inst->src[i].file != GRF ||
-                inst->src[i].reg != inst->dst.reg)
-                  continue;
-
-            for (int j = 0; j < 4; j++) {
-               int swiz = BRW_GET_SWZ(inst->src[i].swizzle, j);
-               dead_channels &= ~(1 << swiz);
-            }
-         }
-      }
-
-      for (exec_node *node = inst->prev, *prev = node->prev;
-           prev != NULL && dead_channels != 0;
-           node = prev, prev = prev->prev) {
-         vec4_instruction *scan_inst = (vec4_instruction  *)node;
-
-         if (scan_inst->is_control_flow())
-            break;
-
-         if (inst_writes_flag) {
-            if (scan_inst->dst.is_null() && scan_inst->writes_flag()) {
-               scan_inst->remove();
-               progress = true;
-               continue;
-            } else if (scan_inst->reads_flag()) {
-               break;
-            }
-         }
-
-         if (inst->dst.file == scan_inst->dst.file &&
-             inst->dst.reg == scan_inst->dst.reg &&
-             inst->dst.reg_offset == scan_inst->dst.reg_offset) {
-            int new_writemask = scan_inst->dst.writemask & ~dead_channels;
-
-            progress = try_eliminate_instruction(scan_inst, new_writemask, brw) ||
-                       progress;
-         }
-
-         for (int i = 0; i < 3; i++) {
-            if (scan_inst->src[i].file != inst->dst.file ||
-                scan_inst->src[i].reg != inst->dst.reg)
-               continue;
-
-            for (int j = 0; j < 4; j++) {
-               int swiz = BRW_GET_SWZ(scan_inst->src[i].swizzle, j);
-               dead_channels &= ~(1 << swiz);
-            }
-         }
-      }
-   }
-
    if (progress)
       invalidate_live_intervals();
 
@@ -569,7 +493,7 @@ vec4_visitor::split_uniform_registers()
     * vector.  The goal is to make elimination of unused uniform
     * components easier later.
     */
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       for (int i = 0 ; i < 3; i++) {
         if (inst->src[i].file != UNIFORM)
            continue;
@@ -602,7 +526,7 @@ vec4_visitor::pack_uniform_registers()
     * expect unused vector elements when we've moved array access out
     * to pull constants, and from some GLSL code generators like wine.
     */
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       for (int i = 0 ; i < 3; i++) {
         if (inst->src[i].file != UNIFORM)
            continue;
@@ -655,7 +579,7 @@ vec4_visitor::pack_uniform_registers()
    this->uniforms = new_uniform_count;
 
    /* Now, update the instructions for our repacked uniforms. */
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       for (int i = 0 ; i < 3; i++) {
         int src = inst->src[i].reg;
 
@@ -663,12 +587,8 @@ vec4_visitor::pack_uniform_registers()
            continue;
 
         inst->src[i].reg = new_loc[src];
-
-        int sx = BRW_GET_SWZ(inst->src[i].swizzle, 0) + new_chan[src];
-        int sy = BRW_GET_SWZ(inst->src[i].swizzle, 1) + new_chan[src];
-        int sz = BRW_GET_SWZ(inst->src[i].swizzle, 2) + new_chan[src];
-        int sw = BRW_GET_SWZ(inst->src[i].swizzle, 3) + new_chan[src];
-        inst->src[i].swizzle = BRW_SWIZZLE4(sx, sy, sz, sw);
+         inst->src[i].swizzle += BRW_SWIZZLE4(new_chan[src], new_chan[src],
+                                              new_chan[src], new_chan[src]);
       }
    }
 }
@@ -690,8 +610,31 @@ vec4_visitor::opt_algebraic()
 {
    bool progress = false;
 
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       switch (inst->opcode) {
+      case BRW_OPCODE_MOV:
+         if (inst->src[0].file != IMM)
+            break;
+
+         if (inst->saturate) {
+            if (inst->dst.type != inst->src[0].type)
+               assert(!"unimplemented: saturate mixed types");
+
+            if (brw_saturate_immediate(inst->dst.type,
+                                       &inst->src[0].fixed_hw_reg)) {
+               inst->saturate = false;
+               progress = true;
+            }
+         }
+         break;
+
+      case VEC4_OPCODE_UNPACK_UNIFORM:
+         if (inst->src[0].file != UNIFORM) {
+            inst->opcode = BRW_OPCODE_MOV;
+            progress = true;
+         }
+         break;
+
       case BRW_OPCODE_ADD:
         if (inst->src[1].is_zero()) {
            inst->opcode = BRW_OPCODE_MOV;
@@ -722,8 +665,46 @@ vec4_visitor::opt_algebraic()
            inst->opcode = BRW_OPCODE_MOV;
            inst->src[1] = src_reg();
            progress = true;
+         } else if (inst->src[1].is_negative_one()) {
+            inst->opcode = BRW_OPCODE_MOV;
+            inst->src[0].negate = !inst->src[0].negate;
+            inst->src[1] = src_reg();
+            progress = true;
         }
         break;
+      case BRW_OPCODE_CMP:
+         if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
+             inst->src[0].abs &&
+             inst->src[0].negate &&
+             inst->src[1].is_zero()) {
+            inst->src[0].abs = false;
+            inst->src[0].negate = false;
+            inst->conditional_mod = BRW_CONDITIONAL_Z;
+            progress = true;
+            break;
+         }
+         break;
+      case SHADER_OPCODE_RCP: {
+         vec4_instruction *prev = (vec4_instruction *)inst->prev;
+         if (prev->opcode == SHADER_OPCODE_SQRT) {
+            if (inst->src[0].equals(src_reg(prev->dst))) {
+               inst->opcode = SHADER_OPCODE_RSQ;
+               inst->src[0] = prev->src[0];
+               progress = true;
+            }
+         }
+         break;
+      }
+      case SHADER_OPCODE_BROADCAST:
+         if (is_uniform(inst->src[0]) ||
+             inst->src[1].is_zero()) {
+            inst->opcode = BRW_OPCODE_MOV;
+            inst->src[1] = src_reg();
+            inst->force_writemask_all = true;
+            progress = true;
+         }
+         break;
+
       default:
         break;
       }
@@ -798,7 +779,7 @@ vec4_visitor::move_push_constants_to_pull_constants()
    /* Now actually rewrite usage of the things we've moved to pull
     * constants.
     */
-   foreach_in_list_safe(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
       for (int i = 0 ; i < 3; i++) {
         if (inst->src[i].file != UNIFORM ||
             pull_constant_loc[inst->src[i].reg] == -1)
@@ -808,7 +789,7 @@ vec4_visitor::move_push_constants_to_pull_constants()
 
         dst_reg temp = dst_reg(this, glsl_type::vec4_type);
 
-        emit_pull_constant_load(inst, temp, inst->src[i],
+        emit_pull_constant_load(block, inst, temp, inst->src[i],
                                 pull_constant_loc[uniform]);
 
         inst->src[i].file = temp.file;
@@ -822,6 +803,53 @@ vec4_visitor::move_push_constants_to_pull_constants()
    pack_uniform_registers();
 }
 
+/* Conditions for which we want to avoid setting the dependency control bits */
+bool
+vec4_visitor::is_dep_ctrl_unsafe(const vec4_instruction *inst)
+{
+#define IS_DWORD(reg) \
+   (reg.type == BRW_REGISTER_TYPE_UD || \
+    reg.type == BRW_REGISTER_TYPE_D)
+
+   /* "When source or destination datatype is 64b or operation is integer DWord
+    * multiply, DepCtrl must not be used."
+    * May apply to future SoCs as well.
+    */
+   if (devinfo->is_cherryview) {
+      if (inst->opcode == BRW_OPCODE_MUL &&
+         IS_DWORD(inst->src[0]) &&
+         IS_DWORD(inst->src[1]))
+         return true;
+   }
+#undef IS_DWORD
+
+   if (devinfo->gen >= 8) {
+      if (inst->opcode == BRW_OPCODE_F32TO16)
+         return true;
+   }
+
+   /*
+    * mlen:
+    * In the presence of send messages, totally interrupt dependency
+    * control. They're long enough that the chance of dependency
+    * control around them just doesn't matter.
+    *
+    * predicate:
+    * From the Ivy Bridge PRM, volume 4 part 3.7, page 80:
+    * When a sequence of NoDDChk and NoDDClr are used, the last instruction that
+    * completes the scoreboard clear must have a non-zero execution mask. This
+    * means, if any kind of predication can change the execution mask or channel
+    * enable of the last instruction, the optimization must be avoided. This is
+    * to avoid instructions being shot down the pipeline when no writes are
+    * required.
+    *
+    * math:
+    * Dependency control does not work well over math instructions.
+    * NB: Discovered empirically
+    */
+   return (inst->mlen || inst->predicate || inst->is_math());
+}
+
 /**
  * Sets the dependency control fields on instructions after register
  * allocation and before the generator is run.
@@ -845,8 +873,6 @@ vec4_visitor::opt_set_dependency_control()
    vec4_instruction *last_mrf_write[BRW_MAX_GRF];
    uint8_t mrf_channels_written[BRW_MAX_GRF];
 
-   calculate_cfg();
-
    assert(prog_data->total_grf ||
           !"Must be called after register allocation");
 
@@ -869,28 +895,7 @@ vec4_visitor::opt_set_dependency_control()
             assert(inst->src[i].file != MRF);
          }
 
-         /* In the presence of send messages, totally interrupt dependency
-          * control.  They're long enough that the chance of dependency
-          * control around them just doesn't matter.
-          */
-         if (inst->mlen) {
-            memset(last_grf_write, 0, sizeof(last_grf_write));
-            memset(last_mrf_write, 0, sizeof(last_mrf_write));
-            continue;
-         }
-
-         /* It looks like setting dependency control on a predicated
-          * instruction hangs the GPU.
-          */
-         if (inst->predicate) {
-            memset(last_grf_write, 0, sizeof(last_grf_write));
-            memset(last_mrf_write, 0, sizeof(last_mrf_write));
-            continue;
-         }
-
-         /* Dependency control does not work well over math instructions.
-          */
-         if (inst->is_math()) {
+         if (is_dep_ctrl_unsafe(inst)) {
             memset(last_grf_write, 0, sizeof(last_grf_write));
             memset(last_mrf_write, 0, sizeof(last_mrf_write));
             continue;
@@ -959,37 +964,25 @@ vec4_instruction::can_reswizzle(int dst_writemask,
 void
 vec4_instruction::reswizzle(int dst_writemask, int swizzle)
 {
-   int new_writemask = 0;
-   int new_swizzle[4] = { 0 };
-
-   /* Dot product instructions write a single result into all channels. */
+   /* Destination write mask doesn't correspond to source swizzle for the dot
+    * product and pack_bytes instructions.
+    */
    if (opcode != BRW_OPCODE_DP4 && opcode != BRW_OPCODE_DPH &&
-       opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2) {
+       opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2 &&
+       opcode != VEC4_OPCODE_PACK_BYTES) {
       for (int i = 0; i < 3; i++) {
          if (src[i].file == BAD_FILE || src[i].file == IMM)
             continue;
 
-         for (int c = 0; c < 4; c++) {
-            new_swizzle[c] = BRW_GET_SWZ(src[i].swizzle, BRW_GET_SWZ(swizzle, c));
-         }
-
-         src[i].swizzle = BRW_SWIZZLE4(new_swizzle[0], new_swizzle[1],
-                                       new_swizzle[2], new_swizzle[3]);
+         src[i].swizzle = brw_compose_swizzle(swizzle, src[i].swizzle);
       }
    }
 
-   for (int c = 0; c < 4; c++) {
-      int bit = 1 << BRW_GET_SWZ(swizzle, c);
-      /* Skip components of the swizzle not used by the dst. */
-      if (!(dst_writemask & (1 << c)))
-         continue;
-      /* If we were populating this component, then populate the
-       * corresponding channel of the new dst.
-       */
-      if (dst.writemask & bit)
-         new_writemask |= (1 << c);
-   }
-   dst.writemask = new_writemask;
+   /* Apply the specified swizzle and writemask to the original mask of
+    * written components.
+    */
+   dst.writemask = dst_writemask &
+                   brw_apply_swizzle_to_mask(swizzle, dst.writemask);
 }
 
 /*
@@ -1022,10 +1015,7 @@ vec4_visitor::opt_register_coalesce()
       /* Can't coalesce this GRF if someone else was going to
        * read it later.
        */
-      if (this->virtual_grf_end[inst->src[0].reg * 4 + 0] > ip ||
-          this->virtual_grf_end[inst->src[0].reg * 4 + 1] > ip ||
-          this->virtual_grf_end[inst->src[0].reg * 4 + 2] > ip ||
-          this->virtual_grf_end[inst->src[0].reg * 4 + 3] > ip)
+      if (var_range_end(var_from_reg(alloc, inst->src[0]), 4) > ip)
         continue;
 
       /* We need to check interference with the final destination between this
@@ -1033,41 +1023,28 @@ vec4_visitor::opt_register_coalesce()
        * we're eliminating.  To do that, keep track of which of our source
        * channels we've seen initialized.
        */
-      bool chans_needed[4] = {false, false, false, false};
-      int chans_remaining = 0;
-      int swizzle_mask = 0;
-      for (int i = 0; i < 4; i++) {
-        int chan = BRW_GET_SWZ(inst->src[0].swizzle, i);
-
-        if (!(inst->dst.writemask & (1 << i)))
-           continue;
-
-         swizzle_mask |= (1 << chan);
-
-        if (!chans_needed[chan]) {
-           chans_needed[chan] = true;
-           chans_remaining++;
-        }
-      }
+      const unsigned chans_needed =
+         brw_apply_inv_swizzle_to_mask(inst->src[0].swizzle,
+                                       inst->dst.writemask);
+      unsigned chans_remaining = chans_needed;
 
       /* Now walk up the instruction stream trying to see if we can rewrite
        * everything writing to the temporary to write into the destination
        * instead.
        */
-      vec4_instruction *scan_inst;
-      for (scan_inst = (vec4_instruction *)inst->prev;
-          scan_inst->prev != NULL;
-          scan_inst = (vec4_instruction *)scan_inst->prev) {
-        if (scan_inst->dst.file == GRF &&
-            scan_inst->dst.reg == inst->src[0].reg &&
-            scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
+      vec4_instruction *_scan_inst = (vec4_instruction *)inst->prev;
+      foreach_inst_in_block_reverse_starting_from(vec4_instruction, scan_inst,
+                                                  inst, block) {
+         _scan_inst = scan_inst;
+
+         if (inst->src[0].in_range(scan_inst->dst, scan_inst->regs_written)) {
             /* Found something writing to the reg we want to coalesce away. */
             if (to_mrf) {
                /* SEND instructions can't have MRF as a destination. */
                if (scan_inst->mlen)
                   break;
 
-               if (brw->gen == 6) {
+               if (devinfo->gen == 6) {
                   /* gen6 math instructions must have the destination be
                    * GRF, so no compute-to-MRF for them.
                    */
@@ -1080,35 +1057,22 @@ vec4_visitor::opt_register_coalesce()
             /* If we can't handle the swizzle, bail. */
             if (!scan_inst->can_reswizzle(inst->dst.writemask,
                                           inst->src[0].swizzle,
-                                          swizzle_mask)) {
+                                          chans_needed)) {
                break;
             }
 
+            /* This doesn't handle coalescing of multiple registers. */
+            if (scan_inst->regs_written > 1)
+               break;
+
            /* Mark which channels we found unconditional writes for. */
-           if (!scan_inst->predicate) {
-              for (int i = 0; i < 4; i++) {
-                 if (scan_inst->dst.writemask & (1 << i) &&
-                     chans_needed[i]) {
-                    chans_needed[i] = false;
-                    chans_remaining--;
-                 }
-              }
-           }
+           if (!scan_inst->predicate)
+               chans_remaining &= ~scan_inst->dst.writemask;
 
            if (chans_remaining == 0)
               break;
         }
 
-        /* We don't handle flow control here.  Most computation of values
-         * that could be coalesced happens just before their use.
-         */
-        if (scan_inst->opcode == BRW_OPCODE_DO ||
-            scan_inst->opcode == BRW_OPCODE_WHILE ||
-            scan_inst->opcode == BRW_OPCODE_ELSE ||
-            scan_inst->opcode == BRW_OPCODE_ENDIF) {
-           break;
-        }
-
          /* You can't read from an MRF, so if someone else reads our MRF's
           * source GRF that we wanted to rewrite, that stops us.  If it's a
           * GRF we're trying to coalesce to, we don't actually handle
@@ -1116,11 +1080,9 @@ vec4_visitor::opt_register_coalesce()
           */
         bool interfered = false;
         for (int i = 0; i < 3; i++) {
-           if (scan_inst->src[i].file == GRF &&
-               scan_inst->src[i].reg == inst->src[0].reg &&
-               scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
+            if (inst->src[0].in_range(scan_inst->src[i],
+                                      scan_inst->regs_read(i)))
               interfered = true;
-           }
         }
         if (interfered)
            break;
@@ -1128,10 +1090,8 @@ vec4_visitor::opt_register_coalesce()
          /* If somebody else writes our destination here, we can't coalesce
           * before that.
           */
-         if (scan_inst->dst.file == inst->dst.file &&
-             scan_inst->dst.reg == inst->dst.reg) {
+         if (inst->dst.in_range(scan_inst->dst, scan_inst->regs_written))
            break;
-         }
 
          /* Check for reads of the register we're trying to coalesce into.  We
           * can't go rewriting instructions above that to put some other value
@@ -1144,11 +1104,9 @@ vec4_visitor::opt_register_coalesce()
             }
          } else {
             for (int i = 0; i < 3; i++) {
-               if (scan_inst->src[i].file == inst->dst.file &&
-                   scan_inst->src[i].reg == inst->dst.reg &&
-                   scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
+               if (inst->dst.in_range(scan_inst->src[i],
+                                      scan_inst->regs_read(i)))
                   interfered = true;
-               }
             }
             if (interfered)
                break;
@@ -1161,7 +1119,7 @@ vec4_visitor::opt_register_coalesce()
          * computing the value.  Now go rewrite the instruction stream
          * between the two.
          */
-
+         vec4_instruction *scan_inst = _scan_inst;
         while (scan_inst != inst) {
            if (scan_inst->dst.file == GRF &&
                scan_inst->dst.reg == inst->src[0].reg &&
@@ -1181,7 +1139,47 @@ vec4_visitor::opt_register_coalesce()
    }
 
    if (progress)
-      invalidate_live_intervals(false);
+      invalidate_live_intervals();
+
+   return progress;
+}
+
+/**
+ * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
+ * flow.  We could probably do better here with some form of divergence
+ * analysis.
+ */
+bool
+vec4_visitor::eliminate_find_live_channel()
+{
+   bool progress = false;
+   unsigned depth = 0;
+
+   foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
+      switch (inst->opcode) {
+      case BRW_OPCODE_IF:
+      case BRW_OPCODE_DO:
+         depth++;
+         break;
+
+      case BRW_OPCODE_ENDIF:
+      case BRW_OPCODE_WHILE:
+         depth--;
+         break;
+
+      case SHADER_OPCODE_FIND_LIVE_CHANNEL:
+         if (depth == 0) {
+            inst->opcode = BRW_OPCODE_MOV;
+            inst->src[0] = src_reg(0);
+            inst->force_writemask_all = true;
+            progress = true;
+         }
+         break;
+
+      default:
+         break;
+      }
+   }
 
    return progress;
 }
@@ -1201,7 +1199,7 @@ vec4_visitor::opt_register_coalesce()
 void
 vec4_visitor::split_virtual_grfs()
 {
-   int num_vars = this->virtual_grf_count;
+   int num_vars = this->alloc.count;
    int new_virtual_grf[num_vars];
    bool split_grf[num_vars];
 
@@ -1209,22 +1207,19 @@ vec4_visitor::split_virtual_grfs()
 
    /* Try to split anything > 0 sized. */
    for (int i = 0; i < num_vars; i++) {
-      split_grf[i] = this->virtual_grf_sizes[i] != 1;
+      split_grf[i] = this->alloc.sizes[i] != 1;
    }
 
    /* Check that the instructions are compatible with the registers we're trying
     * to split.
     */
-   foreach_in_list(vec4_instruction, inst, &instructions) {
-      /* If there's a SEND message loading from a GRF on gen7+, it needs to be
-       * contiguous.
-       */
-      if (inst->is_send_from_grf()) {
-         for (int i = 0; i < 3; i++) {
-            if (inst->src[i].file == GRF) {
-               split_grf[inst->src[i].reg] = false;
-            }
-         }
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
+      if (inst->dst.file == GRF && inst->regs_written > 1)
+         split_grf[inst->dst.reg] = false;
+
+      for (int i = 0; i < 3; i++) {
+         if (inst->src[i].file == GRF && inst->regs_read(i) > 1)
+            split_grf[inst->src[i].reg] = false;
       }
    }
 
@@ -1235,16 +1230,16 @@ vec4_visitor::split_virtual_grfs()
       if (!split_grf[i])
          continue;
 
-      new_virtual_grf[i] = virtual_grf_alloc(1);
-      for (int j = 2; j < this->virtual_grf_sizes[i]; j++) {
-         int reg = virtual_grf_alloc(1);
+      new_virtual_grf[i] = alloc.allocate(1);
+      for (unsigned j = 2; j < this->alloc.sizes[i]; j++) {
+         unsigned reg = alloc.allocate(1);
          assert(reg == new_virtual_grf[i] + j - 1);
          (void) reg;
       }
-      this->virtual_grf_sizes[i] = 1;
+      this->alloc.sizes[i] = 1;
    }
 
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       if (inst->dst.file == GRF && split_grf[inst->dst.reg] &&
           inst->dst.reg_offset != 0) {
          inst->dst.reg = (new_virtual_grf[inst->dst.reg] +
@@ -1260,7 +1255,7 @@ vec4_visitor::split_virtual_grfs()
          }
       }
    }
-   invalidate_live_intervals(false);
+   invalidate_live_intervals();
 }
 
 void
@@ -1275,13 +1270,22 @@ vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
    vec4_instruction *inst = (vec4_instruction *)be_inst;
 
    if (inst->predicate) {
-      fprintf(file, "(%cf0) ",
-             inst->predicate_inverse ? '-' : '+');
+      fprintf(file, "(%cf0.%d) ",
+              inst->predicate_inverse ? '-' : '+',
+              inst->flag_subreg);
    }
 
    fprintf(file, "%s", brw_instruction_name(inst->opcode));
+   if (inst->saturate)
+      fprintf(file, ".sat");
    if (inst->conditional_mod) {
       fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
+      if (!inst->predicate &&
+          (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
+                                inst->opcode != BRW_OPCODE_IF &&
+                                inst->opcode != BRW_OPCODE_WHILE))) {
+         fprintf(file, ".f0.%d", inst->flag_subreg);
+      }
    }
    fprintf(file, " ");
 
@@ -1368,6 +1372,13 @@ vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
          case BRW_REGISTER_TYPE_UD:
             fprintf(file, "%uU", inst->src[i].fixed_hw_reg.dw1.ud);
             break;
+         case BRW_REGISTER_TYPE_VF:
+            fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
+                    brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >>  0) & 0xff),
+                    brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >>  8) & 0xff),
+                    brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 16) & 0xff),
+                    brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 24) & 0xff));
+            break;
          default:
             fprintf(file, "???");
             break;
@@ -1417,7 +1428,7 @@ vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
       /* Don't print .0; and only VGRFs have reg_offsets and sizes */
       if (inst->src[i].reg_offset != 0 &&
           inst->src[i].file == GRF &&
-          virtual_grf_sizes[inst->src[i].reg] != 1)
+          alloc.sizes[inst->src[i].reg] != 1)
          fprintf(file, ".%d", inst->src[i].reg_offset);
 
       if (inst->src[i].file != IMM) {
@@ -1469,7 +1480,7 @@ void
 vec4_visitor::lower_attributes_to_hw_regs(const int *attribute_map,
                                           bool interleaved)
 {
-   foreach_in_list(vec4_instruction, inst, &instructions) {
+   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
       /* We have to support ATTR as a destination for GL_FIXED fixup. */
       if (inst->dst.file == ATTR) {
         int grf = attribute_map[inst->dst.reg + inst->dst.reg_offset];
@@ -1549,7 +1560,7 @@ vec4_vs_visitor::setup_attributes(int payload_reg)
    unsigned vue_entries =
       MAX2(nr_attributes, prog_data->vue_map.num_slots);
 
-   if (brw->gen == 6)
+   if (devinfo->gen == 6)
       prog_data->urb_entry_size = ALIGN(vue_entries, 8) / 8;
    else
       prog_data->urb_entry_size = ALIGN(vue_entries, 4) / 4;
@@ -1565,7 +1576,7 @@ vec4_visitor::setup_uniforms(int reg)
    /* The pre-gen6 VS requires that some push constants get loaded no
     * matter what, or the GPU would hang.
     */
-   if (brw->gen < 6 && this->uniforms == 0) {
+   if (devinfo->gen < 6 && this->uniforms == 0) {
       assert(this->uniforms < this->uniform_array_size);
       this->uniform_vector_size[this->uniforms] = 1;
 
@@ -1609,14 +1620,22 @@ vec4_vs_visitor::setup_payload(void)
    this->first_non_payload_grf = reg;
 }
 
+void
+vec4_visitor::assign_binding_table_offsets()
+{
+   assign_common_binding_table_offsets(0);
+}
+
 src_reg
 vec4_visitor::get_timestamp()
 {
-   assert(brw->gen >= 7);
+   assert(devinfo->gen >= 7);
 
    src_reg ts = src_reg(brw_reg(BRW_ARCHITECTURE_REGISTER_FILE,
                                 BRW_ARF_TIMESTAMP,
                                 0,
+                                0,
+                                0,
                                 BRW_REGISTER_TYPE_UD,
                                 BRW_VERTICAL_STRIDE_0,
                                 BRW_WIDTH_4,
@@ -1670,20 +1689,16 @@ vec4_visitor::emit_shader_time_end()
     */
    emit(ADD(diff, src_reg(diff), src_reg(-2u)));
 
-   emit_shader_time_write(st_base, src_reg(diff));
-   emit_shader_time_write(st_written, src_reg(1u));
+   emit_shader_time_write(0, src_reg(diff));
+   emit_shader_time_write(1, src_reg(1u));
    emit(BRW_OPCODE_ELSE);
-   emit_shader_time_write(st_reset, src_reg(1u));
+   emit_shader_time_write(2, src_reg(1u));
    emit(BRW_OPCODE_ENDIF);
 }
 
 void
-vec4_visitor::emit_shader_time_write(enum shader_time_shader_type type,
-                                     src_reg value)
+vec4_visitor::emit_shader_time_write(int shader_time_subindex, src_reg value)
 {
-   int shader_time_index =
-      brw_get_shader_time_index(brw, shader_prog, prog, type);
-
    dst_reg dst =
       dst_reg(this, glsl_type::get_array_instance(glsl_type::vec4_type, 2));
 
@@ -1692,30 +1707,41 @@ vec4_visitor::emit_shader_time_write(enum shader_time_shader_type type,
    time.reg_offset++;
 
    offset.type = BRW_REGISTER_TYPE_UD;
-   emit(MOV(offset, src_reg(shader_time_index * SHADER_TIME_STRIDE)));
+   int index = shader_time_index * 3 + shader_time_subindex;
+   emit(MOV(offset, src_reg(index * SHADER_TIME_STRIDE)));
 
    time.type = BRW_REGISTER_TYPE_UD;
    emit(MOV(time, src_reg(value)));
 
-   emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
+   vec4_instruction *inst =
+      emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
+   inst->mlen = 2;
 }
 
 bool
-vec4_visitor::run()
+vec4_visitor::run(gl_clip_plane *clip_planes)
 {
+   bool use_vec4_nir =
+      compiler->glsl_compiler_options[stage].NirOptions != NULL;
+
    sanity_param_count = prog->Parameters->NumParameters;
 
-   if (INTEL_DEBUG & DEBUG_SHADER_TIME)
+   if (shader_time_index >= 0)
       emit_shader_time_begin();
 
-   assign_common_binding_table_offsets(0);
+   assign_binding_table_offsets();
 
    emit_prolog();
 
-   /* Generate VS IR for main().  (the visitor only descends into
-    * functions called "main").
-    */
-   if (shader) {
+   if (use_vec4_nir) {
+      assert(prog->nir != NULL);
+      emit_nir_code();
+      if (failed)
+         return false;
+   } else if (shader) {
+      /* Generate VS IR for main().  (the visitor only descends into
+       * functions called "main").
+       */
       visit_instructions(shader->base.ir);
    } else {
       emit_program_code();
@@ -1723,17 +1749,19 @@ vec4_visitor::run()
    base_ir = NULL;
 
    if (key->userclip_active && !prog->UsesClipDistanceOut)
-      setup_uniform_clipplane_values();
+      setup_uniform_clipplane_values(clip_planes);
 
    emit_thread_end();
 
+   calculate_cfg();
+
    /* Before any optimization, push array accesses out to scratch
     * space where we need them to be.  This pass may allocate new
     * virtual GRFs, so we want to do it early.  It also makes sure
     * that we have reladdr computations available for CSE, since we'll
     * often do repeated subexpressions for those.
     */
-   if (shader) {
+   if (shader || use_vec4_nir) {
       move_grf_array_access_to_scratch();
       move_uniform_array_access_to_pull_constants();
    } else {
@@ -1749,48 +1777,57 @@ vec4_visitor::run()
    move_push_constants_to_pull_constants();
    split_virtual_grfs();
 
-   const char *stage_name = stage == MESA_SHADER_GEOMETRY ? "gs" : "vs";
-
-#define OPT(pass, args...) do {                                        \
+#define OPT(pass, args...) ({                                          \
       pass_num++;                                                      \
       bool this_progress = pass(args);                                 \
                                                                        \
       if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) {  \
          char filename[64];                                            \
          snprintf(filename, 64, "%s-%04d-%02d-%02d-" #pass,            \
-                  stage_name, shader_prog ? shader_prog->Name : 0, iteration, pass_num); \
+                  stage_abbrev, shader_prog ? shader_prog->Name : 0, iteration, pass_num); \
                                                                        \
-         backend_visitor::dump_instructions(filename);                 \
+         backend_shader::dump_instructions(filename);                  \
       }                                                                \
                                                                        \
       progress = progress || this_progress;                            \
-   } while (false)
+      this_progress;                                                   \
+   })
 
 
    if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
       char filename[64];
       snprintf(filename, 64, "%s-%04d-00-start",
-               stage_name, shader_prog ? shader_prog->Name : 0);
+               stage_abbrev, shader_prog ? shader_prog->Name : 0);
 
-      backend_visitor::dump_instructions(filename);
+      backend_shader::dump_instructions(filename);
    }
 
    bool progress;
    int iteration = 0;
+   int pass_num = 0;
    do {
       progress = false;
+      pass_num = 0;
       iteration++;
-      int pass_num = 0;
 
       OPT(opt_reduce_swizzle);
       OPT(dead_code_eliminate);
       OPT(dead_control_flow_eliminate, this);
       OPT(opt_copy_propagation);
-      OPT(opt_algebraic);
       OPT(opt_cse);
+      OPT(opt_algebraic);
       OPT(opt_register_coalesce);
+      OPT(eliminate_find_live_channel);
    } while (progress);
 
+   pass_num = 0;
+
+   if (OPT(opt_vector_float)) {
+      OPT(opt_cse);
+      OPT(opt_copy_propagation, false);
+      OPT(opt_copy_propagation, true);
+      OPT(dead_code_eliminate);
+   }
 
    if (failed)
       return false;
@@ -1799,9 +1836,9 @@ vec4_visitor::run()
 
    if (false) {
       /* Debug of register spilling: Go spill everything. */
-      const int grf_count = virtual_grf_count;
-      float spill_costs[virtual_grf_count];
-      bool no_spill[virtual_grf_count];
+      const int grf_count = alloc.count;
+      float spill_costs[alloc.count];
+      bool no_spill[alloc.count];
       evaluate_spill_costs(spill_costs, no_spill);
       for (int i = 0; i < grf_count; i++) {
          if (no_spill[i])
@@ -1810,15 +1847,30 @@ vec4_visitor::run()
       }
    }
 
-   while (!reg_allocate()) {
-      if (failed)
-         return false;
+   bool allocated_without_spills = reg_allocate();
+
+   if (!allocated_without_spills) {
+      compiler->shader_perf_log(log_data,
+                                "%s shader triggered register spilling.  "
+                                "Try reducing the number of live vec4 values "
+                                "to improve performance.\n",
+                                stage_name);
+
+      while (!reg_allocate()) {
+         if (failed)
+            return false;
+      }
    }
 
    opt_schedule_instructions();
 
    opt_set_dependency_control();
 
+   if (last_scratch > 0) {
+      prog_data->base.total_scratch =
+         brw_get_scratch_size(last_scratch * REG_SIZE);
+   }
+
    /* If any state parameters were appended, then ParameterValues could have
     * been realloced, in which case the driver uniform storage set up by
     * _mesa_associate_uniform_storage() would point to freed memory.  Make
@@ -1826,8 +1878,6 @@ vec4_visitor::run()
     */
    assert(sanity_param_count == prog->Parameters->NumParameters);
 
-   calculate_cfg();
-
    return !failed;
 }
 
@@ -1842,14 +1892,16 @@ extern "C" {
  */
 const unsigned *
 brw_vs_emit(struct brw_context *brw,
-            struct gl_shader_program *prog,
-            struct brw_vs_compile *c,
-            struct brw_vs_prog_data *prog_data,
             void *mem_ctx,
+            const struct brw_vs_prog_key *key,
+            struct brw_vs_prog_data *prog_data,
+            struct gl_vertex_program *vp,
+            struct gl_shader_program *prog,
             unsigned *final_assembly_size)
 {
    bool start_busy = false;
    double start_time = 0;
+   const unsigned *assembly = NULL;
 
    if (unlikely(brw->perf_debug)) {
       start_busy = (brw->batch.last_bo &&
@@ -1861,30 +1913,93 @@ brw_vs_emit(struct brw_context *brw,
    if (prog)
       shader = (brw_shader *) prog->_LinkedShaders[MESA_SHADER_VERTEX];
 
+   int st_index = -1;
+   if (INTEL_DEBUG & DEBUG_SHADER_TIME)
+      st_index = brw_get_shader_time_index(brw, prog, &vp->Base, ST_VS);
+
    if (unlikely(INTEL_DEBUG & DEBUG_VS))
-      brw_dump_ir(brw, "vertex", prog, &shader->base, &c->vp->program.Base);
+      brw_dump_ir("vertex", prog, &shader->base, &vp->Base);
+
+   if (!vp->Base.nir &&
+       (brw->intelScreen->compiler->scalar_vs ||
+        brw->intelScreen->compiler->glsl_compiler_options[MESA_SHADER_VERTEX].NirOptions != NULL)) {
+      /* Normally we generate NIR in LinkShader() or
+       * ProgramStringNotify(), but Mesa's fixed-function vertex program
+       * handling doesn't notify the driver at all.  Just do it here, at
+       * the last minute, even though it's lame.
+       */
+      assert(vp->Base.Id == 0 && prog == NULL);
+      vp->Base.nir =
+         brw_create_nir(brw, NULL, &vp->Base, MESA_SHADER_VERTEX,
+                        brw->intelScreen->compiler->scalar_vs);
+   }
 
-   vec4_vs_visitor v(brw, c, prog_data, prog, mem_ctx);
-   if (!v.run()) {
-      if (prog) {
-         prog->LinkStatus = false;
-         ralloc_strcat(&prog->InfoLog, v.fail_msg);
-      }
+   if (brw->intelScreen->compiler->scalar_vs) {
+      prog_data->base.dispatch_mode = DISPATCH_MODE_SIMD8;
+
+      fs_visitor v(brw->intelScreen->compiler, brw,
+                   mem_ctx, MESA_SHADER_VERTEX, key,
+                   &prog_data->base.base, prog, &vp->Base,
+                   8, st_index);
+      if (!v.run_vs(brw_select_clip_planes(&brw->ctx))) {
+         if (prog) {
+            prog->LinkStatus = false;
+            ralloc_strcat(&prog->InfoLog, v.fail_msg);
+         }
+
+         _mesa_problem(NULL, "Failed to compile vertex shader: %s\n",
+                       v.fail_msg);
 
-      _mesa_problem(NULL, "Failed to compile vertex shader: %s\n",
-                    v.fail_msg);
+         return NULL;
+      }
 
-      return NULL;
+      fs_generator g(brw->intelScreen->compiler, brw,
+                     mem_ctx, (void *) key, &prog_data->base.base,
+                     &vp->Base, v.promoted_constants,
+                     v.runtime_check_aads_emit, "VS");
+      if (INTEL_DEBUG & DEBUG_VS) {
+         char *name;
+         if (prog) {
+            name = ralloc_asprintf(mem_ctx, "%s vertex shader %d",
+                                   prog->Label ? prog->Label : "unnamed",
+                                   prog->Name);
+         } else {
+            name = ralloc_asprintf(mem_ctx, "vertex program %d",
+                                   vp->Base.Id);
+         }
+         g.enable_debug(name);
+      }
+      g.generate_code(v.cfg, 8);
+      assembly = g.get_assembly(final_assembly_size);
    }
 
-   const unsigned *assembly = NULL;
-   vec4_generator g(brw, prog, &c->vp->program.Base, &prog_data->base,
-                    mem_ctx, INTEL_DEBUG & DEBUG_VS);
-   assembly = g.generate_assembly(v.cfg, final_assembly_size);
+   if (!assembly) {
+      prog_data->base.dispatch_mode = DISPATCH_MODE_4X2_DUAL_OBJECT;
+
+      vec4_vs_visitor v(brw->intelScreen->compiler, brw, key, prog_data,
+                        vp, prog, mem_ctx, st_index,
+                        !_mesa_is_gles3(&brw->ctx));
+      if (!v.run(brw_select_clip_planes(&brw->ctx))) {
+         if (prog) {
+            prog->LinkStatus = false;
+            ralloc_strcat(&prog->InfoLog, v.fail_msg);
+         }
+
+         _mesa_problem(NULL, "Failed to compile vertex shader: %s\n",
+                       v.fail_msg);
+
+         return NULL;
+      }
+
+      vec4_generator g(brw->intelScreen->compiler, brw,
+                       prog, &vp->Base, &prog_data->base,
+                       mem_ctx, INTEL_DEBUG & DEBUG_VS, "vertex", "VS");
+      assembly = g.generate_assembly(v.cfg, final_assembly_size);
+   }
 
    if (unlikely(brw->perf_debug) && shader) {
       if (shader->compiled_once) {
-         brw_vs_debug_recompile(brw, prog, &c->key);
+         brw_vs_debug_recompile(brw, prog, key);
       }
       if (start_busy && !drm_intel_bo_busy(brw->batch.last_bo)) {
          perf_debug("VS compile took %.03f ms and stalled the GPU\n",
@@ -1898,24 +2013,14 @@ brw_vs_emit(struct brw_context *brw,
 
 
 void
-brw_vec4_setup_prog_key_for_precompile(struct gl_context *ctx,
-                                       struct brw_vec4_prog_key *key,
-                                       GLuint id, struct gl_program *prog)
+brw_vue_setup_prog_key_for_precompile(struct gl_context *ctx,
+                                      struct brw_vue_prog_key *key,
+                                      GLuint id, struct gl_program *prog)
 {
+   struct brw_context *brw = brw_context(ctx);
    key->program_string_id = id;
-   key->clamp_vertex_color = ctx->API == API_OPENGL_COMPAT;
-
-   unsigned sampler_count = _mesa_fls(prog->SamplersUsed);
-   for (unsigned i = 0; i < sampler_count; i++) {
-      if (prog->ShadowSamplers & (1 << i)) {
-         /* Assume DEPTH_TEXTURE_MODE is the default: X, X, X, 1 */
-         key->tex.swizzles[i] =
-            MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_ONE);
-      } else {
-         /* Color sampler: assume no swizzling. */
-         key->tex.swizzles[i] = SWIZZLE_XYZW;
-      }
-   }
+
+   brw_setup_tex_for_precompile(brw, &key->tex, prog);
 }
 
 } /* extern "C" */