gallivm: use texture target from shader instead of static state for size query
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_sample_soa.c
index e685f4b73f0ce7775ea42233ed2a2d4cce717990..e403ac83c6a5c0cd186832f477da1a53a11c9cb6 100644 (file)
 
 #include "pipe/p_defines.h"
 #include "pipe/p_state.h"
+#include "pipe/p_shader_tokens.h"
 #include "util/u_debug.h"
 #include "util/u_dump.h"
 #include "util/u_memory.h"
 #include "util/u_math.h"
 #include "util/u_format.h"
+#include "util/u_cpu_detect.h"
 #include "lp_bld_debug.h"
 #include "lp_bld_type.h"
 #include "lp_bld_const.h"
@@ -56,6 +58,7 @@
 #include "lp_bld_sample_aos.h"
 #include "lp_bld_struct.h"
 #include "lp_bld_quad.h"
+#include "lp_bld_pack.h"
 
 
 /**
@@ -69,7 +72,7 @@
  */
 static void
 lp_build_sample_texel_soa(struct lp_build_sample_context *bld,
-                          unsigned unit,
+                          unsigned sampler_unit,
                           LLVMValueRef width,
                           LLVMValueRef height,
                           LLVMValueRef depth,
@@ -79,9 +82,10 @@ lp_build_sample_texel_soa(struct lp_build_sample_context *bld,
                           LLVMValueRef y_stride,
                           LLVMValueRef z_stride,
                           LLVMValueRef data_ptr,
+                          LLVMValueRef mipoffsets,
                           LLVMValueRef texel_out[4])
 {
-   const struct lp_sampler_static_state *static_state = bld->static_state;
+   const struct lp_static_sampler_state *static_state = bld->static_sampler_state;
    const unsigned dims = bld->dims;
    struct lp_build_context *int_coord_bld = &bld->int_coord_bld;
    LLVMBuilderRef builder = bld->gallivm->builder;
@@ -136,6 +140,9 @@ lp_build_sample_texel_soa(struct lp_build_sample_context *bld,
                           bld->format_desc,
                           x, y, z, y_stride, z_stride,
                           &offset, &i, &j);
+   if (mipoffsets) {
+      offset = lp_build_add(&bld->int_coord_bld, offset, mipoffsets);
+   }
 
    if (use_border) {
       /* If we can sample the border color, it means that texcoords may
@@ -175,7 +182,7 @@ lp_build_sample_texel_soa(struct lp_build_sample_context *bld,
       /* select texel color or border color depending on use_border */
       LLVMValueRef border_color_ptr = 
          bld->dynamic_state->border_color(bld->dynamic_state,
-                                          bld->gallivm, unit);
+                                          bld->gallivm, sampler_unit);
       int chan;
       for (chan = 0; chan < 4; chan++) {
          LLVMValueRef border_chan =
@@ -183,6 +190,11 @@ lp_build_sample_texel_soa(struct lp_build_sample_context *bld,
                                lp_build_const_int32(bld->gallivm, chan));
          LLVMValueRef border_chan_vec =
             lp_build_broadcast_scalar(&bld->float_vec_bld, border_chan);
+
+         if (!bld->texel_type.floating) {
+            border_chan_vec = LLVMBuildBitCast(builder, border_chan_vec,
+                                               bld->texel_bld.vec_type, "");
+         }
          texel_out[chan] = lp_build_select(&bld->texel_bld, use_border,
                                            border_chan_vec, texel_out[chan]);
       }
@@ -219,6 +231,41 @@ lp_build_coord_mirror(struct lp_build_sample_context *bld,
 }
 
 
+/**
+ * Helper to compute the first coord and the weight for
+ * linear wrap repeat npot textures
+ */
+void
+lp_build_coord_repeat_npot_linear(struct lp_build_sample_context *bld,
+                                  LLVMValueRef coord_f,
+                                  LLVMValueRef length_i,
+                                  LLVMValueRef length_f,
+                                  LLVMValueRef *coord0_i,
+                                  LLVMValueRef *weight_f)
+{
+   struct lp_build_context *coord_bld = &bld->coord_bld;
+   struct lp_build_context *int_coord_bld = &bld->int_coord_bld;
+   LLVMValueRef half = lp_build_const_vec(bld->gallivm, coord_bld->type, 0.5);
+   LLVMValueRef length_minus_one = lp_build_sub(int_coord_bld, length_i,
+                                                int_coord_bld->one);
+   LLVMValueRef mask;
+   /* wrap with normalized floats is just fract */
+   coord_f = lp_build_fract(coord_bld, coord_f);
+   /* mul by size and subtract 0.5 */
+   coord_f = lp_build_mul(coord_bld, coord_f, length_f);
+   coord_f = lp_build_sub(coord_bld, coord_f, half);
+   /*
+    * we avoided the 0.5/length division before the repeat wrap,
+    * now need to fix up edge cases with selects
+    */
+   /* convert to int, compute lerp weight */
+   lp_build_ifloor_fract(coord_bld, coord_f, coord0_i, weight_f);
+   mask = lp_build_compare(int_coord_bld->gallivm, int_coord_bld->type,
+                           PIPE_FUNC_LESS, *coord0_i, int_coord_bld->zero);
+   *coord0_i = lp_build_select(int_coord_bld, mask, length_minus_one, *coord0_i);
+}
+
+
 /**
  * Build LLVM code for texture wrap mode for linear filtering.
  * \param x0_out  returns first integer texcoord
@@ -230,6 +277,7 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
                             LLVMValueRef coord,
                             LLVMValueRef length,
                             LLVMValueRef length_f,
+                            LLVMValueRef offset,
                             boolean is_pot,
                             unsigned wrap_mode,
                             LLVMValueRef *x0_out,
@@ -245,36 +293,48 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
 
    switch(wrap_mode) {
    case PIPE_TEX_WRAP_REPEAT:
-      /* mul by size and subtract 0.5 */
-      coord = lp_build_mul(coord_bld, coord, length_f);
-      coord = lp_build_sub(coord_bld, coord, half);
-      /* convert to int, compute lerp weight */
-      lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
-      /* repeat wrap */
       if (is_pot) {
+         /* mul by size and subtract 0.5 */
+         coord = lp_build_mul(coord_bld, coord, length_f);
+         coord = lp_build_sub(coord_bld, coord, half);
+         if (offset) {
+            offset = lp_build_int_to_float(coord_bld, offset);
+            coord = lp_build_add(coord_bld, coord, offset);
+         }
+         /* convert to int, compute lerp weight */
+         lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
          coord1 = lp_build_add(int_coord_bld, coord0, int_coord_bld->one);
+         /* repeat wrap */
          coord0 = LLVMBuildAnd(builder, coord0, length_minus_one, "");
          coord1 = LLVMBuildAnd(builder, coord1, length_minus_one, "");
       }
       else {
-         /* Add a bias to the texcoord to handle negative coords */
-         LLVMValueRef bias = lp_build_mul_imm(int_coord_bld, length, 1024);
          LLVMValueRef mask;
-         coord0 = LLVMBuildAdd(builder, coord0, bias, "");
-         coord0 = LLVMBuildURem(builder, coord0, length, "");
-         mask = lp_build_compare(bld->gallivm, int_coord_bld->type,
+         if (offset) {
+            offset = lp_build_int_to_float(coord_bld, offset);
+            offset = lp_build_div(coord_bld, offset, length_f);
+            coord = lp_build_add(coord_bld, coord, offset);
+         }
+         lp_build_coord_repeat_npot_linear(bld, coord,
+                                           length, length_f,
+                                           &coord0, &weight);
+         mask = lp_build_compare(int_coord_bld->gallivm, int_coord_bld->type,
                                  PIPE_FUNC_NOTEQUAL, coord0, length_minus_one);
          coord1 = LLVMBuildAnd(builder,
-                              lp_build_add(int_coord_bld, coord0, int_coord_bld->one),
-                              mask, "");
+                               lp_build_add(int_coord_bld, coord0, int_coord_bld->one),
+                               mask, "");
       }
       break;
 
    case PIPE_TEX_WRAP_CLAMP:
-      if (bld->static_state->normalized_coords) {
+      if (bld->static_sampler_state->normalized_coords) {
          /* scale coord to length */
          coord = lp_build_mul(coord_bld, coord, length_f);
       }
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
 
       /* clamp to [0, length] */
       coord = lp_build_clamp(coord_bld, coord, coord_bld->zero, length_f);
@@ -291,10 +351,15 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
          struct lp_build_context abs_coord_bld = bld->coord_bld;
          abs_coord_bld.type.sign = FALSE;
 
-         if (bld->static_state->normalized_coords) {
+         if (bld->static_sampler_state->normalized_coords) {
             /* mul by tex size */
             coord = lp_build_mul(coord_bld, coord, length_f);
          }
+         if (offset) {
+            offset = lp_build_int_to_float(coord_bld, offset);
+            coord = lp_build_add(coord_bld, coord, offset);
+         }
+
          /* clamp to length max */
          coord = lp_build_min(coord_bld, coord, length_f);
          /* subtract 0.5 */
@@ -310,20 +375,20 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
       }
 
    case PIPE_TEX_WRAP_CLAMP_TO_BORDER:
-      {
-         LLVMValueRef min;
-         if (bld->static_state->normalized_coords) {
-            /* scale coord to length */
-            coord = lp_build_mul(coord_bld, coord, length_f);
-         }
-         /* was: clamp to [-0.5, length + 0.5], then sub 0.5 */
-         coord = lp_build_sub(coord_bld, coord, half);
-         min = lp_build_const_vec(bld->gallivm, coord_bld->type, -1.0F);
-         coord = lp_build_clamp(coord_bld, coord, min, length_f);
-         /* convert to int, compute lerp weight */
-         lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
-         coord1 = lp_build_add(int_coord_bld, coord0, int_coord_bld->one);
+      if (bld->static_sampler_state->normalized_coords) {
+         /* scale coord to length */
+         coord = lp_build_mul(coord_bld, coord, length_f);
+      }
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
       }
+      /* was: clamp to [-0.5, length + 0.5], then sub 0.5 */
+      /* can skip clamp (though might not work for very large coord values */
+      coord = lp_build_sub(coord_bld, coord, half);
+      /* convert to int, compute lerp weight */
+      lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
+      coord1 = lp_build_add(int_coord_bld, coord0, int_coord_bld->one);
       break;
 
    case PIPE_TEX_WRAP_MIRROR_REPEAT:
@@ -333,6 +398,10 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
       /* scale coord to length */
       coord = lp_build_mul(coord_bld, coord, length_f);
       coord = lp_build_sub(coord_bld, coord, half);
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
 
       /* convert to int, compute lerp weight */
       lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
@@ -345,12 +414,15 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
       break;
 
    case PIPE_TEX_WRAP_MIRROR_CLAMP:
-      coord = lp_build_abs(coord_bld, coord);
-
-      if (bld->static_state->normalized_coords) {
+      if (bld->static_sampler_state->normalized_coords) {
          /* scale coord to length */
          coord = lp_build_mul(coord_bld, coord, length_f);
       }
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
+      coord = lp_build_abs(coord_bld, coord);
 
       /* clamp to [0, length] */
       coord = lp_build_min(coord_bld, coord, length_f);
@@ -364,42 +436,50 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
 
    case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE:
       {
-         LLVMValueRef min, max;
          struct lp_build_context abs_coord_bld = bld->coord_bld;
          abs_coord_bld.type.sign = FALSE;
-         coord = lp_build_abs(coord_bld, coord);
 
-         if (bld->static_state->normalized_coords) {
+         if (bld->static_sampler_state->normalized_coords) {
             /* scale coord to length */
             coord = lp_build_mul(coord_bld, coord, length_f);
          }
+         if (offset) {
+            offset = lp_build_int_to_float(coord_bld, offset);
+            coord = lp_build_add(coord_bld, coord, offset);
+         }
+         coord = lp_build_abs(coord_bld, coord);
 
-         /* clamp to [0.5, length - 0.5] */
-         min = half;
-         max = lp_build_sub(coord_bld, length_f, min);
-         coord = lp_build_clamp(coord_bld, coord, min, max);
-
+         /* clamp to length max */
+         coord = lp_build_min(coord_bld, coord, length_f);
+         /* subtract 0.5 */
          coord = lp_build_sub(coord_bld, coord, half);
+         /* clamp to [0, length - 0.5] */
+         coord = lp_build_max(coord_bld, coord, coord_bld->zero);
 
          /* convert to int, compute lerp weight */
          lp_build_ifloor_fract(&abs_coord_bld, coord, &coord0, &weight);
          coord1 = lp_build_add(int_coord_bld, coord0, int_coord_bld->one);
+         /* coord1 = min(coord1, length-1) */
+         coord1 = lp_build_min(int_coord_bld, coord1, length_minus_one);
       }
       break;
 
    case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER:
       {
-         coord = lp_build_abs(coord_bld, coord);
-
-         if (bld->static_state->normalized_coords) {
+         if (bld->static_sampler_state->normalized_coords) {
             /* scale coord to length */
             coord = lp_build_mul(coord_bld, coord, length_f);
          }
+         if (offset) {
+            offset = lp_build_int_to_float(coord_bld, offset);
+            coord = lp_build_add(coord_bld, coord, offset);
+         }
+         coord = lp_build_abs(coord_bld, coord);
 
          /* was: clamp to [-0.5, length + 0.5] then sub 0.5 */
-         /* skip -0.5 clamp (always positive), do sub first */
+         /* skip clamp - always positive, and other side
+            only potentially matters for very large coords */
          coord = lp_build_sub(coord_bld, coord, half);
-         coord = lp_build_min(coord_bld, coord, length_f);
 
          /* convert to int, compute lerp weight */
          lp_build_ifloor_fract(coord_bld, coord, &coord0, &weight);
@@ -424,6 +504,8 @@ lp_build_sample_wrap_linear(struct lp_build_sample_context *bld,
  * Build LLVM code for texture wrap mode for nearest filtering.
  * \param coord  the incoming texcoord (nominally in [0,1])
  * \param length  the texture size along one dimension, as int vector
+ * \param length_f  the texture size along one dimension, as float vector
+ * \param offset  texel offset along one dimension (as int vector)
  * \param is_pot  if TRUE, length is a power of two
  * \param wrap_mode  one of PIPE_TEX_WRAP_x
  */
@@ -432,6 +514,7 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
                              LLVMValueRef coord,
                              LLVMValueRef length,
                              LLVMValueRef length_f,
+                             LLVMValueRef offset,
                              boolean is_pot,
                              unsigned wrap_mode)
 {
@@ -443,21 +526,30 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
    
    switch(wrap_mode) {
    case PIPE_TEX_WRAP_REPEAT:
-      coord = lp_build_mul(coord_bld, coord, length_f);
-      icoord = lp_build_ifloor(coord_bld, coord);
-      if (is_pot)
+      if (is_pot) {
+         coord = lp_build_mul(coord_bld, coord, length_f);
+         icoord = lp_build_ifloor(coord_bld, coord);
+         if (offset) {
+            icoord = lp_build_add(int_coord_bld, icoord, offset);
+         }
          icoord = LLVMBuildAnd(builder, icoord, length_minus_one, "");
+      }
       else {
-         /* Add a bias to the texcoord to handle negative coords */
-         LLVMValueRef bias = lp_build_mul_imm(int_coord_bld, length, 1024);
-         icoord = LLVMBuildAdd(builder, icoord, bias, "");
-         icoord = LLVMBuildURem(builder, icoord, length, "");
+          if (offset) {
+             offset = lp_build_int_to_float(coord_bld, offset);
+             offset = lp_build_div(coord_bld, offset, length_f);
+             coord = lp_build_add(coord_bld, coord, offset);
+          }
+          /* take fraction, unnormalize */
+          coord = lp_build_fract_safe(coord_bld, coord);
+          coord = lp_build_mul(coord_bld, coord, length_f);
+          icoord = lp_build_itrunc(coord_bld, coord);
       }
       break;
 
    case PIPE_TEX_WRAP_CLAMP:
    case PIPE_TEX_WRAP_CLAMP_TO_EDGE:
-      if (bld->static_state->normalized_coords) {
+      if (bld->static_sampler_state->normalized_coords) {
          /* scale coord to length */
          coord = lp_build_mul(coord_bld, coord, length_f);
       }
@@ -465,6 +557,9 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
       /* floor */
       /* use itrunc instead since we clamp to 0 anyway */
       icoord = lp_build_itrunc(coord_bld, coord);
+      if (offset) {
+         icoord = lp_build_add(int_coord_bld, icoord, offset);
+      }
 
       /* clamp to [0, length - 1]. */
       icoord = lp_build_clamp(int_coord_bld, icoord, int_coord_bld->zero,
@@ -472,30 +567,28 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
       break;
 
    case PIPE_TEX_WRAP_CLAMP_TO_BORDER:
-      /* Note: this is the same as CLAMP_TO_EDGE, except min = -min */
-      {
-         LLVMValueRef min, max;
-
-         if (bld->static_state->normalized_coords) {
-            /* scale coord to length */
-            coord = lp_build_mul(coord_bld, coord, length_f);
-         }
-
-         icoord = lp_build_ifloor(coord_bld, coord);
-
-         /* clamp to [-1, length] */
-         min = lp_build_negate(int_coord_bld, int_coord_bld->one);
-         max = length;
-         icoord = lp_build_clamp(int_coord_bld, icoord, min, max);
+      if (bld->static_sampler_state->normalized_coords) {
+         /* scale coord to length */
+         coord = lp_build_mul(coord_bld, coord, length_f);
+      }
+      /* no clamp necessary, border masking will handle this */
+      icoord = lp_build_ifloor(coord_bld, coord);
+      if (offset) {
+         icoord = lp_build_add(int_coord_bld, icoord, offset);
       }
       break;
 
    case PIPE_TEX_WRAP_MIRROR_REPEAT:
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         offset = lp_build_div(coord_bld, offset, length_f);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
       /* compute mirror function */
       coord = lp_build_coord_mirror(bld, coord);
 
       /* scale coord to length */
-      assert(bld->static_state->normalized_coords);
+      assert(bld->static_sampler_state->normalized_coords);
       coord = lp_build_mul(coord_bld, coord, length_f);
 
       /* itrunc == ifloor here */
@@ -507,12 +600,15 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
 
    case PIPE_TEX_WRAP_MIRROR_CLAMP:
    case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE:
-      coord = lp_build_abs(coord_bld, coord);
-
-      if (bld->static_state->normalized_coords) {
+      if (bld->static_sampler_state->normalized_coords) {
          /* scale coord to length */
          coord = lp_build_mul(coord_bld, coord, length_f);
       }
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
+      coord = lp_build_abs(coord_bld, coord);
 
       /* itrunc == ifloor here */
       icoord = lp_build_itrunc(coord_bld, coord);
@@ -522,18 +618,18 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
       break;
 
    case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER:
-      coord = lp_build_abs(coord_bld, coord);
-
-      if (bld->static_state->normalized_coords) {
+      if (bld->static_sampler_state->normalized_coords) {
          /* scale coord to length */
          coord = lp_build_mul(coord_bld, coord, length_f);
       }
+      if (offset) {
+         offset = lp_build_int_to_float(coord_bld, offset);
+         coord = lp_build_add(coord_bld, coord, offset);
+      }
+      coord = lp_build_abs(coord_bld, coord);
 
       /* itrunc == ifloor here */
       icoord = lp_build_itrunc(coord_bld, coord);
-
-      /* clamp to [0, length] */
-      icoord = lp_build_min(int_coord_bld, icoord, length);
       break;
 
    default:
@@ -551,14 +647,16 @@ lp_build_sample_wrap_nearest(struct lp_build_sample_context *bld,
  */
 static void
 lp_build_sample_image_nearest(struct lp_build_sample_context *bld,
-                              unsigned unit,
+                              unsigned sampler_unit,
                               LLVMValueRef size,
                               LLVMValueRef row_stride_vec,
                               LLVMValueRef img_stride_vec,
                               LLVMValueRef data_ptr,
+                              LLVMValueRef mipoffsets,
                               LLVMValueRef s,
                               LLVMValueRef t,
                               LLVMValueRef r,
+                              const LLVMValueRef *offsets,
                               LLVMValueRef colors_out[4])
 {
    const unsigned dims = bld->dims;
@@ -569,10 +667,10 @@ lp_build_sample_image_nearest(struct lp_build_sample_context *bld,
    LLVMValueRef flt_width_vec;
    LLVMValueRef flt_height_vec;
    LLVMValueRef flt_depth_vec;
-   LLVMValueRef x, y, z;
+   LLVMValueRef x, y = NULL, z = NULL;
 
    lp_build_extract_image_sizes(bld,
-                                bld->int_size_type,
+                                &bld->int_size_bld,
                                 bld->int_coord_type,
                                 size,
                                 &width_vec, &height_vec, &depth_vec);
@@ -580,7 +678,7 @@ lp_build_sample_image_nearest(struct lp_build_sample_context *bld,
    flt_size = lp_build_int_to_float(&bld->float_size_bld, size);
 
    lp_build_extract_image_sizes(bld,
-                                bld->float_size_type,
+                                &bld->float_size_bld,
                                 bld->coord_type,
                                 flt_size,
                                 &flt_width_vec, &flt_height_vec, &flt_depth_vec);
@@ -588,42 +686,39 @@ lp_build_sample_image_nearest(struct lp_build_sample_context *bld,
    /*
     * Compute integer texcoords.
     */
-   x = lp_build_sample_wrap_nearest(bld, s, width_vec, flt_width_vec,
-                                    bld->static_state->pot_width,
-                                    bld->static_state->wrap_s);
+   x = lp_build_sample_wrap_nearest(bld, s, width_vec, flt_width_vec, offsets[0],
+                                    bld->static_texture_state->pot_width,
+                                    bld->static_sampler_state->wrap_s);
    lp_build_name(x, "tex.x.wrapped");
 
    if (dims >= 2) {
-      y = lp_build_sample_wrap_nearest(bld, t, height_vec, flt_height_vec,
-                                       bld->static_state->pot_height,
-                                       bld->static_state->wrap_t);
+      y = lp_build_sample_wrap_nearest(bld, t, height_vec, flt_height_vec, offsets[1],
+                                       bld->static_texture_state->pot_height,
+                                       bld->static_sampler_state->wrap_t);
       lp_build_name(y, "tex.y.wrapped");
 
       if (dims == 3) {
-         z = lp_build_sample_wrap_nearest(bld, r, depth_vec, flt_depth_vec,
-                                          bld->static_state->pot_depth,
-                                          bld->static_state->wrap_r);
+         z = lp_build_sample_wrap_nearest(bld, r, depth_vec, flt_depth_vec, offsets[2],
+                                          bld->static_texture_state->pot_depth,
+                                          bld->static_sampler_state->wrap_r);
          lp_build_name(z, "tex.z.wrapped");
       }
-      else if (bld->static_state->target == PIPE_TEXTURE_CUBE) {
-         z = r;
-      }
-      else {
-         z = NULL;
-      }
    }
-   else {
-      y = z = NULL;
+   if (bld->static_texture_state->target == PIPE_TEXTURE_CUBE ||
+       bld->static_texture_state->target == PIPE_TEXTURE_1D_ARRAY ||
+       bld->static_texture_state->target == PIPE_TEXTURE_2D_ARRAY) {
+      z = r;
+      lp_build_name(z, "tex.z.layer");
    }
 
    /*
     * Get texture colors.
     */
-   lp_build_sample_texel_soa(bld, unit,
+   lp_build_sample_texel_soa(bld, sampler_unit,
                              width_vec, height_vec, depth_vec,
                              x, y, z,
                              row_stride_vec, img_stride_vec,
-                             data_ptr, colors_out);
+                             data_ptr, mipoffsets, colors_out);
 }
 
 
@@ -633,14 +728,16 @@ lp_build_sample_image_nearest(struct lp_build_sample_context *bld,
  */
 static void
 lp_build_sample_image_linear(struct lp_build_sample_context *bld,
-                             unsigned unit,
+                             unsigned sampler_unit,
                              LLVMValueRef size,
                              LLVMValueRef row_stride_vec,
                              LLVMValueRef img_stride_vec,
                              LLVMValueRef data_ptr,
+                             LLVMValueRef mipoffsets,
                              LLVMValueRef s,
                              LLVMValueRef t,
                              LLVMValueRef r,
+                             const LLVMValueRef *offsets,
                              LLVMValueRef colors_out[4])
 {
    const unsigned dims = bld->dims;
@@ -651,13 +748,13 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
    LLVMValueRef flt_width_vec;
    LLVMValueRef flt_height_vec;
    LLVMValueRef flt_depth_vec;
-   LLVMValueRef x0, y0, z0, x1, y1, z1;
-   LLVMValueRef s_fpart, t_fpart, r_fpart;
+   LLVMValueRef x0, y0 = NULL, z0 = NULL, x1, y1 = NULL, z1 = NULL;
+   LLVMValueRef s_fpart, t_fpart = NULL, r_fpart = NULL;
    LLVMValueRef neighbors[2][2][4];
    int chan;
 
    lp_build_extract_image_sizes(bld,
-                                bld->int_size_type,
+                                &bld->int_size_bld,
                                 bld->int_coord_type,
                                 size,
                                 &width_vec, &height_vec, &depth_vec);
@@ -665,7 +762,7 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
    flt_size = lp_build_int_to_float(&bld->float_size_bld, size);
 
    lp_build_extract_image_sizes(bld,
-                                bld->float_size_type,
+                                &bld->float_size_bld,
                                 bld->coord_type,
                                 flt_size,
                                 &flt_width_vec, &flt_height_vec, &flt_depth_vec);
@@ -673,64 +770,61 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
    /*
     * Compute integer texcoords.
     */
-   lp_build_sample_wrap_linear(bld, s, width_vec, flt_width_vec,
-                               bld->static_state->pot_width,
-                               bld->static_state->wrap_s,
+   lp_build_sample_wrap_linear(bld, s, width_vec, flt_width_vec, offsets[0],
+                               bld->static_texture_state->pot_width,
+                               bld->static_sampler_state->wrap_s,
                                &x0, &x1, &s_fpart);
    lp_build_name(x0, "tex.x0.wrapped");
    lp_build_name(x1, "tex.x1.wrapped");
 
    if (dims >= 2) {
-      lp_build_sample_wrap_linear(bld, t, height_vec, flt_height_vec,
-                                  bld->static_state->pot_height,
-                                  bld->static_state->wrap_t,
+      lp_build_sample_wrap_linear(bld, t, height_vec, flt_height_vec, offsets[1],
+                                  bld->static_texture_state->pot_height,
+                                  bld->static_sampler_state->wrap_t,
                                   &y0, &y1, &t_fpart);
       lp_build_name(y0, "tex.y0.wrapped");
       lp_build_name(y1, "tex.y1.wrapped");
 
       if (dims == 3) {
-         lp_build_sample_wrap_linear(bld, r, depth_vec, flt_depth_vec,
-                                     bld->static_state->pot_depth,
-                                     bld->static_state->wrap_r,
+         lp_build_sample_wrap_linear(bld, r, depth_vec, flt_depth_vec, offsets[2],
+                                     bld->static_texture_state->pot_depth,
+                                     bld->static_sampler_state->wrap_r,
                                      &z0, &z1, &r_fpart);
          lp_build_name(z0, "tex.z0.wrapped");
          lp_build_name(z1, "tex.z1.wrapped");
       }
-      else if (bld->static_state->target == PIPE_TEXTURE_CUBE) {
-         z0 = z1 = r;  /* cube face */
-         r_fpart = NULL;
-      }
-      else {
-         z0 = z1 = NULL;
-         r_fpart = NULL;
-      }
    }
-   else {
-      y0 = y1 = t_fpart = NULL;
-      z0 = z1 = r_fpart = NULL;
+   if (bld->static_texture_state->target == PIPE_TEXTURE_CUBE ||
+       bld->static_texture_state->target == PIPE_TEXTURE_1D_ARRAY ||
+       bld->static_texture_state->target == PIPE_TEXTURE_2D_ARRAY) {
+      z0 = z1 = r;  /* cube face or array layer */
+      lp_build_name(z0, "tex.z0.layer");
+      lp_build_name(z1, "tex.z1.layer");
    }
 
+
    /*
     * Get texture colors.
     */
    /* get x0/x1 texels */
-   lp_build_sample_texel_soa(bld, unit,
+   lp_build_sample_texel_soa(bld, sampler_unit,
                              width_vec, height_vec, depth_vec,
                              x0, y0, z0,
                              row_stride_vec, img_stride_vec,
-                             data_ptr, neighbors[0][0]);
-   lp_build_sample_texel_soa(bld, unit,
+                             data_ptr, mipoffsets, neighbors[0][0]);
+   lp_build_sample_texel_soa(bld, sampler_unit,
                              width_vec, height_vec, depth_vec,
                              x1, y0, z0,
                              row_stride_vec, img_stride_vec,
-                             data_ptr, neighbors[0][1]);
+                             data_ptr, mipoffsets, neighbors[0][1]);
 
    if (dims == 1) {
       /* Interpolate two samples from 1D image to produce one color */
       for (chan = 0; chan < 4; chan++) {
          colors_out[chan] = lp_build_lerp(&bld->texel_bld, s_fpart,
                                           neighbors[0][0][chan],
-                                          neighbors[0][1][chan]);
+                                          neighbors[0][1][chan],
+                                          0);
       }
    }
    else {
@@ -738,16 +832,16 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
       LLVMValueRef colors0[4];
 
       /* get x0/x1 texels at y1 */
-      lp_build_sample_texel_soa(bld, unit,
+      lp_build_sample_texel_soa(bld, sampler_unit,
                                 width_vec, height_vec, depth_vec,
                                 x0, y1, z0,
                                 row_stride_vec, img_stride_vec,
-                                data_ptr, neighbors[1][0]);
-      lp_build_sample_texel_soa(bld, unit,
+                                data_ptr, mipoffsets, neighbors[1][0]);
+      lp_build_sample_texel_soa(bld, sampler_unit,
                                 width_vec, height_vec, depth_vec,
                                 x1, y1, z0,
                                 row_stride_vec, img_stride_vec,
-                                data_ptr, neighbors[1][1]);
+                                data_ptr, mipoffsets, neighbors[1][1]);
 
       /* Bilinear interpolate the four samples from the 2D image / 3D slice */
       for (chan = 0; chan < 4; chan++) {
@@ -756,7 +850,8 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
                                           neighbors[0][0][chan],
                                           neighbors[0][1][chan],
                                           neighbors[1][0][chan],
-                                          neighbors[1][1][chan]);
+                                          neighbors[1][1][chan],
+                                          0);
       }
 
       if (dims == 3) {
@@ -764,26 +859,26 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
          LLVMValueRef colors1[4];
 
          /* get x0/x1/y0/y1 texels at z1 */
-         lp_build_sample_texel_soa(bld, unit,
+         lp_build_sample_texel_soa(bld, sampler_unit,
                                    width_vec, height_vec, depth_vec,
                                    x0, y0, z1,
                                    row_stride_vec, img_stride_vec,
-                                   data_ptr, neighbors1[0][0]);
-         lp_build_sample_texel_soa(bld, unit,
+                                   data_ptr, mipoffsets, neighbors1[0][0]);
+         lp_build_sample_texel_soa(bld, sampler_unit,
                                    width_vec, height_vec, depth_vec,
                                    x1, y0, z1,
                                    row_stride_vec, img_stride_vec,
-                                   data_ptr, neighbors1[0][1]);
-         lp_build_sample_texel_soa(bld, unit,
+                                   data_ptr, mipoffsets, neighbors1[0][1]);
+         lp_build_sample_texel_soa(bld, sampler_unit,
                                    width_vec, height_vec, depth_vec,
                                    x0, y1, z1,
                                    row_stride_vec, img_stride_vec,
-                                   data_ptr, neighbors1[1][0]);
-         lp_build_sample_texel_soa(bld, unit,
+                                   data_ptr, mipoffsets, neighbors1[1][0]);
+         lp_build_sample_texel_soa(bld, sampler_unit,
                                    width_vec, height_vec, depth_vec,
                                    x1, y1, z1,
                                    row_stride_vec, img_stride_vec,
-                                   data_ptr, neighbors1[1][1]);
+                                   data_ptr, mipoffsets, neighbors1[1][1]);
 
          /* Bilinear interpolate the four samples from the second Z slice */
          for (chan = 0; chan < 4; chan++) {
@@ -792,14 +887,16 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
                                              neighbors1[0][0][chan],
                                              neighbors1[0][1][chan],
                                              neighbors1[1][0][chan],
-                                             neighbors1[1][1][chan]);
+                                             neighbors1[1][1][chan],
+                                             0);
          }
 
          /* Linearly interpolate the two samples from the two 3D slices */
          for (chan = 0; chan < 4; chan++) {
             colors_out[chan] = lp_build_lerp(&bld->texel_bld,
                                              r_fpart,
-                                             colors0[chan], colors1[chan]);
+                                             colors0[chan], colors1[chan],
+                                             0);
          }
       }
       else {
@@ -820,26 +917,29 @@ lp_build_sample_image_linear(struct lp_build_sample_context *bld,
  */
 static void
 lp_build_sample_mipmap(struct lp_build_sample_context *bld,
-                       unsigned unit,
+                       unsigned sampler_unit,
                        unsigned img_filter,
                        unsigned mip_filter,
                        LLVMValueRef s,
                        LLVMValueRef t,
                        LLVMValueRef r,
+                       const LLVMValueRef *offsets,
                        LLVMValueRef ilevel0,
                        LLVMValueRef ilevel1,
                        LLVMValueRef lod_fpart,
                        LLVMValueRef *colors_out)
 {
    LLVMBuilderRef builder = bld->gallivm->builder;
-   LLVMValueRef size0;
-   LLVMValueRef size1;
-   LLVMValueRef row_stride0_vec;
-   LLVMValueRef row_stride1_vec;
-   LLVMValueRef img_stride0_vec;
-   LLVMValueRef img_stride1_vec;
-   LLVMValueRef data_ptr0;
-   LLVMValueRef data_ptr1;
+   LLVMValueRef size0 = NULL;
+   LLVMValueRef size1 = NULL;
+   LLVMValueRef row_stride0_vec = NULL;
+   LLVMValueRef row_stride1_vec = NULL;
+   LLVMValueRef img_stride0_vec = NULL;
+   LLVMValueRef img_stride1_vec = NULL;
+   LLVMValueRef data_ptr0 = NULL;
+   LLVMValueRef data_ptr1 = NULL;
+   LLVMValueRef mipoff0 = NULL;
+   LLVMValueRef mipoff1 = NULL;
    LLVMValueRef colors0[4], colors1[4];
    unsigned chan;
 
@@ -847,20 +947,27 @@ lp_build_sample_mipmap(struct lp_build_sample_context *bld,
    lp_build_mipmap_level_sizes(bld, ilevel0,
                                &size0,
                                &row_stride0_vec, &img_stride0_vec);
-   data_ptr0 = lp_build_get_mipmap_level(bld, ilevel0);
+   if (bld->num_lods == 1) {
+      data_ptr0 = lp_build_get_mipmap_level(bld, ilevel0);
+   }
+   else {
+      /* This path should work for num_lods 1 too but slightly less efficient */
+      data_ptr0 = bld->base_ptr;
+      mipoff0 = lp_build_get_mip_offsets(bld, ilevel0);
+   }
    if (img_filter == PIPE_TEX_FILTER_NEAREST) {
-      lp_build_sample_image_nearest(bld, unit,
+      lp_build_sample_image_nearest(bld, sampler_unit,
                                     size0,
                                     row_stride0_vec, img_stride0_vec,
-                                    data_ptr0, s, t, r,
+                                    data_ptr0, mipoff0, s, t, r, offsets,
                                     colors0);
    }
    else {
       assert(img_filter == PIPE_TEX_FILTER_LINEAR);
-      lp_build_sample_image_linear(bld, unit,
+      lp_build_sample_image_linear(bld, sampler_unit,
                                    size0,
                                    row_stride0_vec, img_stride0_vec,
-                                   data_ptr0, s, t, r,
+                                   data_ptr0, mipoff0, s, t, r, offsets,
                                    colors0);
    }
 
@@ -874,10 +981,30 @@ lp_build_sample_mipmap(struct lp_build_sample_context *bld,
       LLVMValueRef need_lerp;
 
       /* need_lerp = lod_fpart > 0 */
-      need_lerp = LLVMBuildFCmp(builder, LLVMRealUGT,
-                                lod_fpart,
-                                bld->float_bld.zero,
-                                "need_lerp");
+      if (bld->num_lods == 1) {
+         need_lerp = LLVMBuildFCmp(builder, LLVMRealUGT,
+                                   lod_fpart, bld->levelf_bld.zero,
+                                   "need_lerp");
+      }
+      else {
+         /*
+          * We'll do mip filtering if any of the quads (or individual
+          * pixel in case of per-pixel lod) need it.
+          * It might be better to split the vectors here and only fetch/filter
+          * quads which need it.
+          */
+         /*
+          * We unfortunately need to clamp lod_fpart here since we can get
+          * negative values which would screw up filtering if not all
+          * lod_fpart values have same sign.
+          */
+         lod_fpart = lp_build_max(&bld->levelf_bld, lod_fpart,
+                                  bld->levelf_bld.zero);
+         need_lerp = lp_build_compare(bld->gallivm, bld->levelf_bld.type,
+                                      PIPE_FUNC_GREATER,
+                                      lod_fpart, bld->levelf_bld.zero);
+         need_lerp = lp_build_any_true_range(&bld->leveli_bld, bld->num_lods, need_lerp);
+      }
 
       lp_build_if(&if_ctx, bld->gallivm, need_lerp);
       {
@@ -885,29 +1012,40 @@ lp_build_sample_mipmap(struct lp_build_sample_context *bld,
          lp_build_mipmap_level_sizes(bld, ilevel1,
                                      &size1,
                                      &row_stride1_vec, &img_stride1_vec);
-         data_ptr1 = lp_build_get_mipmap_level(bld, ilevel1);
+         if (bld->num_lods == 1) {
+            data_ptr1 = lp_build_get_mipmap_level(bld, ilevel1);
+         }
+         else {
+            data_ptr1 = bld->base_ptr;
+            mipoff1 = lp_build_get_mip_offsets(bld, ilevel1);
+         }
          if (img_filter == PIPE_TEX_FILTER_NEAREST) {
-            lp_build_sample_image_nearest(bld, unit,
+            lp_build_sample_image_nearest(bld, sampler_unit,
                                           size1,
                                           row_stride1_vec, img_stride1_vec,
-                                          data_ptr1, s, t, r,
+                                          data_ptr1, mipoff1, s, t, r, offsets,
                                           colors1);
          }
          else {
-            lp_build_sample_image_linear(bld, unit,
+            lp_build_sample_image_linear(bld, sampler_unit,
                                          size1,
                                          row_stride1_vec, img_stride1_vec,
-                                         data_ptr1, s, t, r,
+                                         data_ptr1, mipoff1, s, t, r, offsets,
                                          colors1);
          }
 
          /* interpolate samples from the two mipmap levels */
 
-         lod_fpart = lp_build_broadcast_scalar(&bld->texel_bld, lod_fpart);
+         if (bld->num_lods != bld->coord_type.length)
+            lod_fpart = lp_build_unpack_broadcast_aos_scalars(bld->gallivm,
+                                                              bld->levelf_bld.type,
+                                                              bld->texel_bld.type,
+                                                              lod_fpart);
 
          for (chan = 0; chan < 4; chan++) {
             colors0[chan] = lp_build_lerp(&bld->texel_bld, lod_fpart,
-                                          colors0[chan], colors1[chan]);
+                                          colors0[chan], colors1[chan],
+                                          0);
             LLVMBuildStore(builder, colors0[chan], colors_out[chan]);
          }
       }
@@ -916,35 +1054,63 @@ lp_build_sample_mipmap(struct lp_build_sample_context *bld,
 }
 
 
+/**
+ * Build (per-coord) layer value.
+ * Either clamp layer to valid values or fill in optional out_of_bounds
+ * value and just return value unclamped.
+ */
+static LLVMValueRef
+lp_build_layer_coord(struct lp_build_sample_context *bld,
+                     unsigned texture_unit,
+                     LLVMValueRef layer,
+                     LLVMValueRef *out_of_bounds)
+{
+   LLVMValueRef num_layers;
+   struct lp_build_context *int_coord_bld = &bld->int_coord_bld;
+
+   num_layers = bld->dynamic_state->depth(bld->dynamic_state,
+                                          bld->gallivm, texture_unit);
+
+   if (out_of_bounds) {
+      LLVMValueRef out1, out;
+      num_layers = lp_build_broadcast_scalar(int_coord_bld, num_layers);
+      out = lp_build_cmp(int_coord_bld, PIPE_FUNC_LESS, layer, int_coord_bld->zero);
+      out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_GEQUAL, layer, num_layers);
+      *out_of_bounds = lp_build_or(int_coord_bld, out, out1);
+      return layer;
+   }
+   else {
+      LLVMValueRef maxlayer;
+      maxlayer = lp_build_sub(&bld->int_bld, num_layers, bld->int_bld.one);
+      maxlayer = lp_build_broadcast_scalar(int_coord_bld, maxlayer);
+      return lp_build_clamp(int_coord_bld, layer, int_coord_bld->zero, maxlayer);
+   }
+}
+
 
 /**
- * General texture sampling codegen.
- * This function handles texture sampling for all texture targets (1D,
- * 2D, 3D, cube) and all filtering modes.
+ * Calculate cube face, lod, mip levels.
  */
 static void
-lp_build_sample_general(struct lp_build_sample_context *bld,
-                        unsigned unit,
-                        LLVMValueRef s,
-                        LLVMValueRef t,
-                        LLVMValueRef r,
-                        const LLVMValueRef *ddx,
-                        const LLVMValueRef *ddy,
-                        LLVMValueRef lod_bias, /* optional */
-                        LLVMValueRef explicit_lod, /* optional */
-                        LLVMValueRef *colors_out)
+lp_build_sample_common(struct lp_build_sample_context *bld,
+                       unsigned texture_index,
+                       unsigned sampler_index,
+                       LLVMValueRef *s,
+                       LLVMValueRef *t,
+                       LLVMValueRef *r,
+                       const struct lp_derivatives *derivs, /* optional */
+                       LLVMValueRef lod_bias, /* optional */
+                       LLVMValueRef explicit_lod, /* optional */
+                       LLVMValueRef *lod_ipart,
+                       LLVMValueRef *lod_fpart,
+                       LLVMValueRef *ilevel0,
+                       LLVMValueRef *ilevel1)
 {
-   struct lp_build_context *int_bld = &bld->int_bld;
-   LLVMBuilderRef builder = bld->gallivm->builder;
-   const unsigned mip_filter = bld->static_state->min_mip_filter;
-   const unsigned min_filter = bld->static_state->min_img_filter;
-   const unsigned mag_filter = bld->static_state->mag_img_filter;
-   LLVMValueRef lod_ipart = NULL, lod_fpart = NULL;
-   LLVMValueRef ilevel0, ilevel1 = NULL;
-   LLVMValueRef face_ddx[4], face_ddy[4];
-   LLVMValueRef texels[4];
-   LLVMValueRef i32t_zero = lp_build_const_int32(bld->gallivm, 0);
-   unsigned chan;
+   const unsigned mip_filter = bld->static_sampler_state->min_mip_filter;
+   const unsigned min_filter = bld->static_sampler_state->min_img_filter;
+   const unsigned mag_filter = bld->static_sampler_state->mag_img_filter;
+   const unsigned target = bld->static_texture_state->target;
+   LLVMValueRef first_level, cube_rho = NULL;
 
    /*
    printf("%s mip %d  min %d  mag %d\n", __FUNCTION__,
@@ -952,27 +1118,30 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
    */
 
    /*
-    * Choose cube face, recompute texcoords and derivatives for the chosen face.
+    * Choose cube face, recompute texcoords for the chosen face and
+    * compute rho here too (as it requires transform of derivatives).
     */
-   if (bld->static_state->target == PIPE_TEXTURE_CUBE) {
+   if (target == PIPE_TEXTURE_CUBE) {
       LLVMValueRef face, face_s, face_t;
-      lp_build_cube_lookup(bld, s, t, r, &face, &face_s, &face_t);
-      s = face_s; /* vec */
-      t = face_t; /* vec */
+      boolean need_derivs;
+      need_derivs = ((min_filter != mag_filter ||
+                      mip_filter != PIPE_TEX_MIPFILTER_NONE) &&
+                      !bld->static_sampler_state->min_max_lod_equal &&
+                      !explicit_lod);
+      lp_build_cube_lookup(bld, *s, *t, *r, derivs, &face, &face_s, &face_t,
+                           &cube_rho, need_derivs);
+      *s = face_s; /* vec */
+      *t = face_t; /* vec */
       /* use 'r' to indicate cube face */
-      r = lp_build_broadcast_scalar(&bld->int_coord_bld, face); /* vec */
-
-      /* recompute ddx, ddy using the new (s,t) face texcoords */
-      face_ddx[0] = lp_build_scalar_ddx(&bld->coord_bld, s);
-      face_ddx[1] = lp_build_scalar_ddx(&bld->coord_bld, t);
-      face_ddx[2] = NULL;
-      face_ddx[3] = NULL;
-      face_ddy[0] = lp_build_scalar_ddy(&bld->coord_bld, s);
-      face_ddy[1] = lp_build_scalar_ddy(&bld->coord_bld, t);
-      face_ddy[2] = NULL;
-      face_ddy[3] = NULL;
-      ddx = face_ddx;
-      ddy = face_ddy;
+      *r = face; /* vec */
+   }
+   else if (target == PIPE_TEXTURE_1D_ARRAY) {
+      *r = lp_build_iround(&bld->coord_bld, *t);
+      *r = lp_build_layer_coord(bld, texture_index, *r, NULL);
+   }
+   else if (target == PIPE_TEXTURE_2D_ARRAY) {
+      *r = lp_build_iround(&bld->coord_bld, *r);
+      *r = lp_build_layer_coord(bld, texture_index, *r, NULL);
    }
 
    /*
@@ -983,12 +1152,13 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
       /* Need to compute lod either to choose mipmap levels or to
        * distinguish between minification/magnification with one mipmap level.
        */
-      lp_build_lod_selector(bld, unit, ddx, ddy,
-                            lod_bias, explicit_lod,
+      lp_build_lod_selector(bld, texture_index, sampler_index,
+                            *s, *t, *r, cube_rho,
+                            derivs, lod_bias, explicit_lod,
                             mip_filter,
-                            &lod_ipart, &lod_fpart);
+                            lod_ipart, lod_fpart);
    } else {
-      lod_ipart = i32t_zero;
+      *lod_ipart = bld->leveli_bld.zero;
    }
 
    /*
@@ -1000,30 +1170,60 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
       /* fall-through */
    case PIPE_TEX_MIPFILTER_NONE:
       /* always use mip level 0 */
-      if (bld->static_state->target == PIPE_TEXTURE_CUBE) {
+      if (HAVE_LLVM == 0x0207 && target == PIPE_TEXTURE_CUBE) {
          /* XXX this is a work-around for an apparent bug in LLVM 2.7.
           * We should be able to set ilevel0 = const(0) but that causes
           * bad x86 code to be emitted.
           */
-         assert(lod_ipart);
-         lp_build_nearest_mip_level(bld, unit, lod_ipart, &ilevel0);
+         assert(*lod_ipart);
+         lp_build_nearest_mip_level(bld, texture_index, *lod_ipart, ilevel0, NULL);
       }
       else {
-         ilevel0 = i32t_zero;
+         first_level = bld->dynamic_state->first_level(bld->dynamic_state,
+                                                       bld->gallivm, texture_index);
+         first_level = lp_build_broadcast_scalar(&bld->leveli_bld, first_level);
+         *ilevel0 = first_level;
       }
       break;
    case PIPE_TEX_MIPFILTER_NEAREST:
-      assert(lod_ipart);
-      lp_build_nearest_mip_level(bld, unit, lod_ipart, &ilevel0);
+      assert(*lod_ipart);
+      lp_build_nearest_mip_level(bld, texture_index, *lod_ipart, ilevel0, NULL);
       break;
    case PIPE_TEX_MIPFILTER_LINEAR:
-      assert(lod_ipart);
-      assert(lod_fpart);
-      lp_build_linear_mip_levels(bld, unit,
-                                 lod_ipart, &lod_fpart,
-                                 &ilevel0, &ilevel1);
+      assert(*lod_ipart);
+      assert(*lod_fpart);
+      lp_build_linear_mip_levels(bld, texture_index,
+                                 *lod_ipart, lod_fpart,
+                                 ilevel0, ilevel1);
       break;
    }
+}
+
+/**
+ * General texture sampling codegen.
+ * This function handles texture sampling for all texture targets (1D,
+ * 2D, 3D, cube) and all filtering modes.
+ */
+static void
+lp_build_sample_general(struct lp_build_sample_context *bld,
+                        unsigned sampler_unit,
+                        LLVMValueRef s,
+                        LLVMValueRef t,
+                        LLVMValueRef r,
+                        const LLVMValueRef *offsets,
+                        LLVMValueRef lod_ipart,
+                        LLVMValueRef lod_fpart,
+                        LLVMValueRef ilevel0,
+                        LLVMValueRef ilevel1,
+                        LLVMValueRef *colors_out)
+{
+   struct lp_build_context *int_bld = &bld->int_bld;
+   LLVMBuilderRef builder = bld->gallivm->builder;
+   const unsigned mip_filter = bld->static_sampler_state->min_mip_filter;
+   const unsigned min_filter = bld->static_sampler_state->min_img_filter;
+   const unsigned mag_filter = bld->static_sampler_state->mag_img_filter;
+   LLVMValueRef texels[4];
+   unsigned chan;
 
    /*
     * Get/interpolate texture colors.
@@ -1031,14 +1231,14 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
 
    for (chan = 0; chan < 4; ++chan) {
      texels[chan] = lp_build_alloca(bld->gallivm, bld->texel_bld.vec_type, "");
-     lp_build_name(texels[chan], "sampler%u_texel_%c_var", unit, "xyzw"[chan]);
+     lp_build_name(texels[chan], "sampler%u_texel_%c_var", sampler_unit, "xyzw"[chan]);
    }
 
    if (min_filter == mag_filter) {
-      /* no need to distinquish between minification and magnification */
-      lp_build_sample_mipmap(bld, unit,
+      /* no need to distinguish between minification and magnification */
+      lp_build_sample_mipmap(bld, sampler_unit,
                              min_filter, mip_filter,
-                             s, t, r,
+                             s, t, r, offsets,
                              ilevel0, ilevel1, lod_fpart,
                              texels);
    }
@@ -1049,6 +1249,19 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
       struct lp_build_if_state if_ctx;
       LLVMValueRef minify;
 
+      /*
+       * XXX this should to all lods into account, if some are min
+       * some max probably could hack up the coords/weights in the linear
+       * path with selects to work for nearest.
+       * If that's just two quads sitting next to each other it seems
+       * quite ok to do the same filtering method on both though, at
+       * least unless we have explicit lod (and who uses different
+       * min/mag filter with that?)
+       */
+      if (bld->num_lods > 1)
+         lod_ipart = LLVMBuildExtractElement(builder, lod_ipart,
+                                             lp_build_const_int32(bld->gallivm, 0), "");
+
       /* minify = lod >= 0.0 */
       minify = LLVMBuildICmp(builder, LLVMIntSGE,
                              lod_ipart, int_bld->zero, "");
@@ -1056,19 +1269,19 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
       lp_build_if(&if_ctx, bld->gallivm, minify);
       {
          /* Use the minification filter */
-         lp_build_sample_mipmap(bld, unit,
+         lp_build_sample_mipmap(bld, sampler_unit,
                                 min_filter, mip_filter,
-                                s, t, r,
+                                s, t, r, offsets,
                                 ilevel0, ilevel1, lod_fpart,
                                 texels);
       }
       lp_build_else(&if_ctx);
       {
          /* Use the magnification filter */
-         lp_build_sample_mipmap(bld, unit,
+         lp_build_sample_mipmap(bld, sampler_unit,
                                 mag_filter, PIPE_TEX_MIPFILTER_NONE,
-                                s, t, r,
-                                i32t_zero, NULL, NULL,
+                                s, t, r, offsets,
+                                ilevel0, NULL, NULL,
                                 texels);
       }
       lp_build_endif(&if_ctx);
@@ -1076,29 +1289,176 @@ lp_build_sample_general(struct lp_build_sample_context *bld,
 
    for (chan = 0; chan < 4; ++chan) {
      colors_out[chan] = LLVMBuildLoad(builder, texels[chan], "");
-     lp_build_name(colors_out[chan], "sampler%u_texel_%c", unit, "xyzw"[chan]);
+     lp_build_name(colors_out[chan], "sampler%u_texel_%c", sampler_unit, "xyzw"[chan]);
+   }
+}
+
+
+/**
+ * Texel fetch function.
+ * In contrast to general sampling there is no filtering, no coord minification,
+ * lod (if any) is always explicit uint, coords are uints (in terms of texel units)
+ * directly to be applied to the selected mip level (after adding texel offsets).
+ * This function handles texel fetch for all targets where texel fetch is supported
+ * (no cube maps, but 1d, 2d, 3d are supported, arrays and buffers should be too).
+ */
+static void
+lp_build_fetch_texel(struct lp_build_sample_context *bld,
+                     unsigned texture_unit,
+                     const LLVMValueRef *coords,
+                     LLVMValueRef explicit_lod,
+                     const LLVMValueRef *offsets,
+                     LLVMValueRef *colors_out)
+{
+   struct lp_build_context *perquadi_bld = &bld->leveli_bld;
+   struct lp_build_context *int_coord_bld = &bld->int_coord_bld;
+   unsigned dims = bld->dims, chan;
+   unsigned target = bld->static_texture_state->target;
+   boolean out_of_bound_ret_zero = TRUE;
+   LLVMValueRef size, ilevel;
+   LLVMValueRef row_stride_vec = NULL, img_stride_vec = NULL;
+   LLVMValueRef x = coords[0], y = coords[1], z = coords[2];
+   LLVMValueRef width, height, depth, i, j;
+   LLVMValueRef offset, out_of_bounds, out1;
+
+   out_of_bounds = int_coord_bld->zero;
+
+   if (explicit_lod && bld->static_texture_state->target != PIPE_BUFFER) {
+      if (bld->num_lods != int_coord_bld->type.length) {
+         ilevel = lp_build_pack_aos_scalars(bld->gallivm, int_coord_bld->type,
+                                            perquadi_bld->type, explicit_lod, 0);
+      }
+      else {
+         ilevel = explicit_lod;
+      }
+      lp_build_nearest_mip_level(bld, texture_unit, ilevel, &ilevel,
+                                 out_of_bound_ret_zero ? &out_of_bounds : NULL);
+   }
+   else {
+      assert(bld->num_lods == 1);
+      if (bld->static_texture_state->target != PIPE_BUFFER) {
+         ilevel = bld->dynamic_state->first_level(bld->dynamic_state,
+                                                  bld->gallivm, texture_unit);
+      }
+      else {
+         ilevel = lp_build_const_int32(bld->gallivm, 0);
+      }
+   }
+   lp_build_mipmap_level_sizes(bld, ilevel,
+                               &size,
+                               &row_stride_vec, &img_stride_vec);
+   lp_build_extract_image_sizes(bld, &bld->int_size_bld, int_coord_bld->type,
+                                size, &width, &height, &depth);
+
+   if (target == PIPE_TEXTURE_1D_ARRAY ||
+       target == PIPE_TEXTURE_2D_ARRAY) {
+      if (target == PIPE_TEXTURE_1D_ARRAY) {
+         z = y;
+      }
+      if (out_of_bound_ret_zero) {
+         z = lp_build_layer_coord(bld, texture_unit, z, &out1);
+         out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+      }
+      else {
+         z = lp_build_layer_coord(bld, texture_unit, z, NULL);
+      }
+   }
+
+   /* This is a lot like border sampling */
+   if (offsets[0]) {
+      /*
+       * coords are really unsigned, offsets are signed, but I don't think
+       * exceeding 31 bits is possible
+       */
+      x = lp_build_add(int_coord_bld, x, offsets[0]);
+   }
+   out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_LESS, x, int_coord_bld->zero);
+   out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+   out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_GEQUAL, x, width);
+   out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+
+   if (dims >= 2) {
+      if (offsets[1]) {
+         y = lp_build_add(int_coord_bld, y, offsets[1]);
+      }
+      out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_LESS, y, int_coord_bld->zero);
+      out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+      out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_GEQUAL, y, height);
+      out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+
+      if (dims >= 3) {
+         if (offsets[2]) {
+            z = lp_build_add(int_coord_bld, z, offsets[2]);
+         }
+         out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_LESS, z, int_coord_bld->zero);
+         out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+         out1 = lp_build_cmp(int_coord_bld, PIPE_FUNC_GEQUAL, z, depth);
+         out_of_bounds = lp_build_or(int_coord_bld, out_of_bounds, out1);
+      }
+   }
+
+   lp_build_sample_offset(int_coord_bld,
+                          bld->format_desc,
+                          x, y, z, row_stride_vec, img_stride_vec,
+                          &offset, &i, &j);
+
+   if (bld->static_texture_state->target != PIPE_BUFFER) {
+      offset = lp_build_add(int_coord_bld, offset,
+                            lp_build_get_mip_offsets(bld, ilevel));
+   }
+
+   offset = lp_build_andnot(int_coord_bld, offset, out_of_bounds);
+
+   lp_build_fetch_rgba_soa(bld->gallivm,
+                           bld->format_desc,
+                           bld->texel_type,
+                           bld->base_ptr, offset,
+                           i, j,
+                           colors_out);
+
+   if (out_of_bound_ret_zero) {
+      /*
+       * Only needed for ARB_robust_buffer_access_behavior and d3d10.
+       * Could use min/max above instead of out-of-bounds comparisons
+       * if we don't care about the result returned for out-of-bounds.
+       */
+      for (chan = 0; chan < 4; chan++) {
+         colors_out[chan] = lp_build_select(&bld->texel_bld, out_of_bounds,
+                                            bld->texel_bld.zero, colors_out[chan]);
+      }
    }
 }
 
 
 /**
  * Do shadow test/comparison.
- * \param p  the texcoord Z (aka R, aka P) component
+ * \param coords  incoming texcoords
  * \param texel  the texel to compare against (use the X channel)
+ * Ideally this should really be done per-sample.
  */
 static void
 lp_build_sample_compare(struct lp_build_sample_context *bld,
-                        LLVMValueRef p,
+                        const LLVMValueRef *coords,
                         LLVMValueRef texel[4])
 {
    struct lp_build_context *texel_bld = &bld->texel_bld;
    LLVMBuilderRef builder = bld->gallivm->builder;
-   LLVMValueRef res;
+   LLVMValueRef res, p;
    const unsigned chan = 0;
+   unsigned chan_type;
+   const struct util_format_description *format_desc;
 
-   if (bld->static_state->compare_mode == PIPE_TEX_COMPARE_NONE)
+   if (bld->static_sampler_state->compare_mode == PIPE_TEX_COMPARE_NONE)
       return;
 
+   if (bld->static_texture_state->target == PIPE_TEXTURE_2D_ARRAY ||
+       bld->static_texture_state->target == PIPE_TEXTURE_CUBE) {
+      p = coords[3];
+   }
+   else {
+      p = coords[2];
+   }
+
    /* debug code */
    if (0) {
       LLVMValueRef indx = lp_build_const_int32(bld->gallivm, 0);
@@ -1108,12 +1468,42 @@ lp_build_sample_compare(struct lp_build_sample_context *bld,
                       coord, tex);
    }
 
+   /* Clamp p coords to [0,1] for fixed function depth texture format */
+   format_desc = util_format_description(bld->static_texture_state->format);
+   /* not entirely sure we couldn't end up with non-valid swizzle here */
+   chan_type = format_desc->swizzle[0] <= UTIL_FORMAT_SWIZZLE_W ?
+                  format_desc->channel[format_desc->swizzle[0]].type :
+                  UTIL_FORMAT_TYPE_FLOAT;
+   if (chan_type != UTIL_FORMAT_TYPE_FLOAT) {
+      p = lp_build_clamp(&bld->coord_bld, p,
+                         bld->coord_bld.zero, bld->coord_bld.one);
+   }
+
+   /*
+    * technically this is not entirely correct for unorm depth as the ref value
+    * should be converted to the depth format (quantization!) and comparison
+    * then done in texture format.
+    */
+
    /* result = (p FUNC texel) ? 1 : 0 */
-   res = lp_build_cmp(texel_bld, bld->static_state->compare_func,
-                      p, texel[chan]);
+   /*
+    * honor d3d10 floating point rules here, which state that comparisons
+    * are ordered except NOT_EQUAL which is unordered.
+    */
+   if (bld->static_sampler_state->compare_func != PIPE_FUNC_NOTEQUAL) {
+      res = lp_build_cmp_ordered(texel_bld, bld->static_sampler_state->compare_func,
+                                 p, texel[chan]);
+   }
+   else {
+      res = lp_build_cmp(texel_bld, bld->static_sampler_state->compare_func,
+                         p, texel[chan]);
+   }
    res = lp_build_select(texel_bld, res, texel_bld->one, texel_bld->zero);
 
-   /* XXX returning result for default GL_DEPTH_TEXTURE_MODE = GL_LUMINANCE */
+   /*
+    * returning result for default GL_DEPTH_TEXTURE_MODE = GL_LUMINANCE.
+    * This should be ok because sampler swizzle is applied on top of it.
+    */
    texel[0] =
    texel[1] =
    texel[2] = res;
@@ -1126,7 +1516,9 @@ lp_build_sample_compare(struct lp_build_sample_context *bld,
  * For debugging.
  */
 void
-lp_build_sample_nop(struct gallivm_state *gallivm, struct lp_type type,
+lp_build_sample_nop(struct gallivm_state *gallivm,
+                    struct lp_type type,
+                    const LLVMValueRef *coords,
                     LLVMValueRef texel_out[4])
 {
    LLVMValueRef one = lp_build_one(gallivm, type);
@@ -1143,34 +1535,40 @@ lp_build_sample_nop(struct gallivm_state *gallivm, struct lp_type type,
  * 'texel' will return a vector of four LLVMValueRefs corresponding to
  * R, G, B, A.
  * \param type  vector float type to use for coords, etc.
- * \param ddx  partial derivatives of (s,t,r,q) with respect to x
- * \param ddy  partial derivatives of (s,t,r,q) with respect to y
+ * \param is_fetch  if this is a texel fetch instruction.
+ * \param derivs  partial derivatives of (s,t,r,q) with respect to x and y
  */
 void
 lp_build_sample_soa(struct gallivm_state *gallivm,
-                    const struct lp_sampler_static_state *static_state,
+                    const struct lp_static_texture_state *static_texture_state,
+                    const struct lp_static_sampler_state *static_sampler_state,
                     struct lp_sampler_dynamic_state *dynamic_state,
                     struct lp_type type,
-                    unsigned unit,
-                    unsigned num_coords,
+                    boolean is_fetch,
+                    unsigned texture_index,
+                    unsigned sampler_index,
                     const LLVMValueRef *coords,
-                    const LLVMValueRef ddx[4],
-                    const LLVMValueRef ddy[4],
+                    const LLVMValueRef *offsets,
+                    const struct lp_derivatives *derivs, /* optional */
                     LLVMValueRef lod_bias, /* optional */
                     LLVMValueRef explicit_lod, /* optional */
+                    boolean scalar_lod,
                     LLVMValueRef texel_out[4])
 {
-   unsigned dims = texture_dims(static_state->target);
+   unsigned dims = texture_dims(static_texture_state->target);
+   unsigned num_quads = type.length / 4;
+   unsigned mip_filter;
    struct lp_build_sample_context bld;
+   struct lp_static_sampler_state derived_sampler_state = *static_sampler_state;
    LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context);
    LLVMBuilderRef builder = gallivm->builder;
+   LLVMValueRef tex_width;
    LLVMValueRef s;
    LLVMValueRef t;
    LLVMValueRef r;
-   struct lp_type float_vec_type;
 
    if (0) {
-      enum pipe_format fmt = static_state->format;
+      enum pipe_format fmt = static_texture_state->format;
       debug_printf("Sample from %s\n", util_format_name(fmt));
    }
 
@@ -1179,39 +1577,119 @@ lp_build_sample_soa(struct gallivm_state *gallivm,
    /* Setup our build context */
    memset(&bld, 0, sizeof bld);
    bld.gallivm = gallivm;
-   bld.static_state = static_state;
+   bld.static_sampler_state = &derived_sampler_state;
+   bld.static_texture_state = static_texture_state;
    bld.dynamic_state = dynamic_state;
-   bld.format_desc = util_format_description(static_state->format);
+   bld.format_desc = util_format_description(static_texture_state->format);
    bld.dims = dims;
 
+   bld.vector_width = lp_type_width(type);
+
    bld.float_type = lp_type_float(32);
    bld.int_type = lp_type_int(32);
    bld.coord_type = type;
    bld.int_coord_type = lp_int_type(type);
-   bld.float_size_type = lp_type_float(32);
-   bld.float_size_type.length = dims > 1 ? 4 : 1;
-   bld.int_size_type = lp_int_type(bld.float_size_type);
+   bld.float_size_in_type = lp_type_float(32);
+   bld.float_size_in_type.length = dims > 1 ? 4 : 1;
+   bld.int_size_in_type = lp_int_type(bld.float_size_in_type);
    bld.texel_type = type;
 
-   float_vec_type = lp_type_float_vec(32);
+   /* always using the first channel hopefully should be safe,
+    * if not things WILL break in other places anyway.
+    */
+   if (bld.format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB &&
+       bld.format_desc->channel[0].pure_integer) {
+      if (bld.format_desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED) {
+         bld.texel_type = lp_type_int_vec(type.width, type.width * type.length);
+      }
+      else if (bld.format_desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED) {
+         bld.texel_type = lp_type_uint_vec(type.width, type.width * type.length);
+      }
+   }
+   else if (util_format_has_stencil(bld.format_desc) &&
+       !util_format_has_depth(bld.format_desc)) {
+      /* for stencil only formats, sample stencil (uint) */
+      bld.texel_type = lp_type_int_vec(type.width, type.width * type.length);
+   }
+
+   if (!static_texture_state->level_zero_only) {
+      derived_sampler_state.min_mip_filter = static_sampler_state->min_mip_filter;
+   } else {
+      derived_sampler_state.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
+   }
+   mip_filter = derived_sampler_state.min_mip_filter;
+
+   if (0) {
+      debug_printf("  .min_mip_filter = %u\n", derived_sampler_state.min_mip_filter);
+   }
+
+   /*
+    * This is all a bit complicated different paths are chosen for performance
+    * reasons.
+    * Essentially, there can be 1 lod per element, 1 lod per quad or 1 lod for
+    * everything (the last two options are equivalent for 4-wide case).
+    * If there's per-quad lod but we split to 4-wide so we can use AoS, per-quad
+    * lod is calculated then the lod value extracted afterwards so making this
+    * case basically the same as far as lod handling is concerned for the
+    * further sample/filter code as the 1 lod for everything case.
+    * Different lod handling mostly shows up when building mipmap sizes
+    * (lp_build_mipmap_level_sizes() and friends) and also in filtering
+    * (getting the fractional part of the lod to the right texels).
+    */
+
+   /*
+    * There are other situations where at least the multiple int lods could be
+    * avoided like min and max lod being equal.
+    */
+   if (explicit_lod && !scalar_lod &&
+       ((is_fetch && bld.static_texture_state->target != PIPE_BUFFER) ||
+        (!is_fetch && mip_filter != PIPE_TEX_MIPFILTER_NONE)))
+      bld.num_lods = type.length;
+   /* TODO: for true scalar_lod should only use 1 lod value */
+   else if ((is_fetch && explicit_lod && bld.static_texture_state->target != PIPE_BUFFER ) ||
+            (!is_fetch && mip_filter != PIPE_TEX_MIPFILTER_NONE)) {
+      bld.num_lods = num_quads;
+   }
+   else {
+      bld.num_lods = 1;
+   }
+
+   bld.levelf_type = type;
+   /* we want native vector size to be able to use our intrinsics */
+   if (bld.num_lods != type.length) {
+      bld.levelf_type.length = type.length > 4 ? ((type.length + 15) / 16) * 4 : 1;
+   }
+   bld.leveli_type = lp_int_type(bld.levelf_type);
+   bld.float_size_type = bld.float_size_in_type;
+   /* Note: size vectors may not be native. They contain minified w/h/d/_ values,
+    * with per-element lod that is w0/h0/d0/_/w1/h1/d1_/... so up to 8x4f32 */
+   if (bld.num_lods > 1) {
+      bld.float_size_type.length = bld.num_lods == type.length ?
+                                      bld.num_lods * bld.float_size_in_type.length :
+                                      type.length;
+   }
+   bld.int_size_type = lp_int_type(bld.float_size_type);
 
    lp_build_context_init(&bld.float_bld, gallivm, bld.float_type);
-   lp_build_context_init(&bld.float_vec_bld, gallivm, float_vec_type);
+   lp_build_context_init(&bld.float_vec_bld, gallivm, type);
    lp_build_context_init(&bld.int_bld, gallivm, bld.int_type);
    lp_build_context_init(&bld.coord_bld, gallivm, bld.coord_type);
    lp_build_context_init(&bld.int_coord_bld, gallivm, bld.int_coord_type);
+   lp_build_context_init(&bld.int_size_in_bld, gallivm, bld.int_size_in_type);
+   lp_build_context_init(&bld.float_size_in_bld, gallivm, bld.float_size_in_type);
    lp_build_context_init(&bld.int_size_bld, gallivm, bld.int_size_type);
    lp_build_context_init(&bld.float_size_bld, gallivm, bld.float_size_type);
    lp_build_context_init(&bld.texel_bld, gallivm, bld.texel_type);
+   lp_build_context_init(&bld.levelf_bld, gallivm, bld.levelf_type);
+   lp_build_context_init(&bld.leveli_bld, gallivm, bld.leveli_type);
 
    /* Get the dynamic state */
-   bld.width = dynamic_state->width(dynamic_state, gallivm, unit);
-   bld.height = dynamic_state->height(dynamic_state, gallivm, unit);
-   bld.depth = dynamic_state->depth(dynamic_state, gallivm, unit);
-   bld.row_stride_array = dynamic_state->row_stride(dynamic_state, gallivm, unit);
-   bld.img_stride_array = dynamic_state->img_stride(dynamic_state, gallivm, unit);
-   bld.data_array = dynamic_state->data_ptr(dynamic_state, gallivm, unit);
-   /* Note that data_array is an array[level] of pointers to texture images */
+   tex_width = dynamic_state->width(dynamic_state, gallivm, texture_index);
+   bld.row_stride_array = dynamic_state->row_stride(dynamic_state, gallivm, texture_index);
+   bld.img_stride_array = dynamic_state->img_stride(dynamic_state, gallivm, texture_index);
+   bld.base_ptr = dynamic_state->base_ptr(dynamic_state, gallivm, texture_index);
+   bld.mip_offsets = dynamic_state->mip_offsets(dynamic_state, gallivm, texture_index);
+   /* Note that mip_offsets is an array[level] of offsets to texture images */
 
    s = coords[0];
    t = coords[1];
@@ -1219,53 +1697,399 @@ lp_build_sample_soa(struct gallivm_state *gallivm,
 
    /* width, height, depth as single int vector */
    if (dims <= 1) {
-      bld.int_size = bld.width;
+      bld.int_size = tex_width;
    }
    else {
-      bld.int_size = LLVMBuildInsertElement(builder, bld.int_size_bld.undef,
-                                            bld.width, LLVMConstInt(i32t, 0, 0), "");
+      bld.int_size = LLVMBuildInsertElement(builder, bld.int_size_in_bld.undef,
+                                            tex_width, LLVMConstInt(i32t, 0, 0), "");
       if (dims >= 2) {
+         LLVMValueRef tex_height =
+            dynamic_state->height(dynamic_state, gallivm, texture_index);
          bld.int_size = LLVMBuildInsertElement(builder, bld.int_size,
-                                               bld.height, LLVMConstInt(i32t, 1, 0), "");
+                                               tex_height, LLVMConstInt(i32t, 1, 0), "");
          if (dims >= 3) {
+            LLVMValueRef tex_depth =
+               dynamic_state->depth(dynamic_state, gallivm, texture_index);
             bld.int_size = LLVMBuildInsertElement(builder, bld.int_size,
-                                                  bld.depth, LLVMConstInt(i32t, 2, 0), "");
+                                                  tex_depth, LLVMConstInt(i32t, 2, 0), "");
          }
       }
    }
 
    if (0) {
       /* For debug: no-op texture sampling */
-      lp_build_sample_nop(gallivm, bld.texel_type, texel_out);
-   }
-   else if (util_format_fits_8unorm(bld.format_desc) &&
-            lp_is_simple_wrap_mode(static_state->wrap_s) &&
-            lp_is_simple_wrap_mode(static_state->wrap_t)) {
-      /* do sampling/filtering with fixed pt arithmetic */
-      lp_build_sample_aos(&bld, unit, s, t, r, ddx, ddy,
-                          lod_bias, explicit_lod,
+      lp_build_sample_nop(gallivm,
+                          bld.texel_type,
+                          coords,
                           texel_out);
    }
 
+   else if (is_fetch) {
+      lp_build_fetch_texel(&bld, texture_index, coords,
+                           explicit_lod, offsets,
+                           texel_out);
+   }
+
    else {
+      LLVMValueRef lod_ipart = NULL, lod_fpart = NULL;
+      LLVMValueRef ilevel0 = NULL, ilevel1 = NULL;
+      boolean use_aos = util_format_fits_8unorm(bld.format_desc) &&
+                        lp_is_simple_wrap_mode(static_sampler_state->wrap_s) &&
+                        lp_is_simple_wrap_mode(static_sampler_state->wrap_t);
+
       if ((gallivm_debug & GALLIVM_DEBUG_PERF) &&
-          util_format_fits_8unorm(bld.format_desc)) {
+          !use_aos && util_format_fits_8unorm(bld.format_desc)) {
          debug_printf("%s: using floating point linear filtering for %s\n",
                       __FUNCTION__, bld.format_desc->short_name);
          debug_printf("  min_img %d  mag_img %d  mip %d  wraps %d  wrapt %d\n",
-                      static_state->min_img_filter,
-                      static_state->mag_img_filter,
-                      static_state->min_mip_filter,
-                      static_state->wrap_s,
-                      static_state->wrap_t);
+                      static_sampler_state->min_img_filter,
+                      static_sampler_state->mag_img_filter,
+                      static_sampler_state->min_mip_filter,
+                      static_sampler_state->wrap_s,
+                      static_sampler_state->wrap_t);
+      }
+
+      lp_build_sample_common(&bld, texture_index, sampler_index,
+                             &s, &t, &r,
+                             derivs, lod_bias, explicit_lod,
+                             &lod_ipart, &lod_fpart,
+                             &ilevel0, &ilevel1);
+
+      /*
+       * we only try 8-wide sampling with soa as it appears to
+       * be a loss with aos with AVX (but it should work).
+       * (It should be faster if we'd support avx2)
+       */
+      if (num_quads == 1 || !use_aos) {
+
+         if (num_quads > 1) {
+            if (mip_filter == PIPE_TEX_MIPFILTER_NONE) {
+               LLVMValueRef index0 = lp_build_const_int32(gallivm, 0);
+               /*
+                * These parameters are the same for all quads,
+                * could probably simplify.
+                */
+               lod_ipart = LLVMBuildExtractElement(builder, lod_ipart, index0, "");
+               ilevel0 = LLVMBuildExtractElement(builder, ilevel0, index0, "");
+            }
+         }
+         if (use_aos) {
+            /* do sampling/filtering with fixed pt arithmetic */
+            lp_build_sample_aos(&bld, sampler_index,
+                                s, t, r, offsets,
+                                lod_ipart, lod_fpart,
+                                ilevel0, ilevel1,
+                                texel_out);
+         }
+
+         else {
+            lp_build_sample_general(&bld, sampler_index,
+                                    s, t, r, offsets,
+                                    lod_ipart, lod_fpart,
+                                    ilevel0, ilevel1,
+                                    texel_out);
+         }
       }
+      else {
+         unsigned j;
+         struct lp_build_sample_context bld4;
+         struct lp_type type4 = type;
+         unsigned i;
+         LLVMValueRef texelout4[4];
+         LLVMValueRef texelouttmp[4][LP_MAX_VECTOR_LENGTH/16];
+
+         type4.length = 4;
+
+         /* Setup our build context */
+         memset(&bld4, 0, sizeof bld4);
+         bld4.gallivm = bld.gallivm;
+         bld4.static_texture_state = bld.static_texture_state;
+         bld4.static_sampler_state = bld.static_sampler_state;
+         bld4.dynamic_state = bld.dynamic_state;
+         bld4.format_desc = bld.format_desc;
+         bld4.dims = bld.dims;
+         bld4.row_stride_array = bld.row_stride_array;
+         bld4.img_stride_array = bld.img_stride_array;
+         bld4.base_ptr = bld.base_ptr;
+         bld4.mip_offsets = bld.mip_offsets;
+         bld4.int_size = bld.int_size;
+
+         bld4.vector_width = lp_type_width(type4);
+
+         bld4.float_type = lp_type_float(32);
+         bld4.int_type = lp_type_int(32);
+         bld4.coord_type = type4;
+         bld4.int_coord_type = lp_int_type(type4);
+         bld4.float_size_in_type = lp_type_float(32);
+         bld4.float_size_in_type.length = dims > 1 ? 4 : 1;
+         bld4.int_size_in_type = lp_int_type(bld4.float_size_in_type);
+         bld4.texel_type = bld.texel_type;
+         bld4.texel_type.length = 4;
+         bld4.levelf_type = type4;
+         /* we want native vector size to be able to use our intrinsics */
+         bld4.levelf_type.length = 1;
+         bld4.leveli_type = lp_int_type(bld4.levelf_type);
+
+         if (explicit_lod && !scalar_lod &&
+             ((is_fetch && bld.static_texture_state->target != PIPE_BUFFER) ||
+              (!is_fetch && mip_filter != PIPE_TEX_MIPFILTER_NONE)))
+            bld4.num_lods = type4.length;
+         else
+            bld4.num_lods = 1;
+
+         bld4.levelf_type = type4;
+         /* we want native vector size to be able to use our intrinsics */
+         if (bld4.num_lods != type4.length) {
+            bld4.levelf_type.length = 1;
+         }
+         bld4.leveli_type = lp_int_type(bld4.levelf_type);
+         bld4.float_size_type = bld4.float_size_in_type;
+         if (bld4.num_lods > 1) {
+            bld4.float_size_type.length = bld4.num_lods == type4.length ?
+                                            bld4.num_lods * bld4.float_size_in_type.length :
+                                            type4.length;
+         }
+         bld4.int_size_type = lp_int_type(bld4.float_size_type);
+
+         lp_build_context_init(&bld4.float_bld, gallivm, bld4.float_type);
+         lp_build_context_init(&bld4.float_vec_bld, gallivm, type4);
+         lp_build_context_init(&bld4.int_bld, gallivm, bld4.int_type);
+         lp_build_context_init(&bld4.coord_bld, gallivm, bld4.coord_type);
+         lp_build_context_init(&bld4.int_coord_bld, gallivm, bld4.int_coord_type);
+         lp_build_context_init(&bld4.int_size_in_bld, gallivm, bld4.int_size_in_type);
+         lp_build_context_init(&bld4.float_size_in_bld, gallivm, bld4.float_size_in_type);
+         lp_build_context_init(&bld4.int_size_bld, gallivm, bld4.int_size_type);
+         lp_build_context_init(&bld4.float_size_bld, gallivm, bld4.float_size_type);
+         lp_build_context_init(&bld4.texel_bld, gallivm, bld4.texel_type);
+         lp_build_context_init(&bld4.levelf_bld, gallivm, bld4.levelf_type);
+         lp_build_context_init(&bld4.leveli_bld, gallivm, bld4.leveli_type);
+
+         for (i = 0; i < num_quads; i++) {
+            LLVMValueRef s4, t4, r4;
+            LLVMValueRef lod_ipart4, lod_fpart4 = NULL;
+            LLVMValueRef ilevel04, ilevel14 = NULL;
+            LLVMValueRef offsets4[4] = { NULL };
+            unsigned num_lods = bld4.num_lods;
+
+            s4 = lp_build_extract_range(gallivm, s, 4*i, 4);
+            t4 = lp_build_extract_range(gallivm, t, 4*i, 4);
+            r4 = lp_build_extract_range(gallivm, r, 4*i, 4);
+
+            if (offsets[0]) {
+               offsets4[0] = lp_build_extract_range(gallivm, offsets[0], 4*i, 4);
+               if (dims > 1) {
+                  offsets4[1] = lp_build_extract_range(gallivm, offsets[1], 4*i, 4);
+                  if (dims > 2) {
+                     offsets4[2] = lp_build_extract_range(gallivm, offsets[2], 4*i, 4);
+                  }
+               }
+            }
+            lod_ipart4 = lp_build_extract_range(gallivm, lod_ipart, num_lods * i, num_lods);
+            ilevel04 = lp_build_extract_range(gallivm, ilevel0, num_lods * i, num_lods);
+            if (mip_filter == PIPE_TEX_MIPFILTER_LINEAR) {
+               ilevel14 = lp_build_extract_range(gallivm, ilevel1, num_lods * i, num_lods);
+               lod_fpart4 = lp_build_extract_range(gallivm, lod_fpart, num_lods * i, num_lods);
+            }
+
+            if (use_aos) {
+               /* do sampling/filtering with fixed pt arithmetic */
+               lp_build_sample_aos(&bld4, sampler_index,
+                                   s4, t4, r4, offsets4,
+                                   lod_ipart4, lod_fpart4,
+                                   ilevel04, ilevel14,
+                                   texelout4);
+            }
+
+            else {
+               lp_build_sample_general(&bld4, sampler_index,
+                                       s4, t4, r4, offsets4,
+                                       lod_ipart4, lod_fpart4,
+                                       ilevel04, ilevel14,
+                                       texelout4);
+            }
+            for (j = 0; j < 4; j++) {
+               texelouttmp[j][i] = texelout4[j];
+            }
+         }
+
+         for (j = 0; j < 4; j++) {
+            texel_out[j] = lp_build_concat(gallivm, texelouttmp[j], type4, num_quads);
+         }
+      }
+
+      lp_build_sample_compare(&bld, coords, texel_out);
+   }
+
+   if (static_texture_state->target != PIPE_BUFFER) {
+      apply_sampler_swizzle(&bld, texel_out);
+   }
+
+   /*
+    * texel type can be a (32bit) int/uint (for pure int formats only),
+    * however we are expected to always return floats (storage is untyped).
+    */
+   if (!bld.texel_type.floating) {
+      unsigned chan;
+      for (chan = 0; chan < 4; chan++) {
+         texel_out[chan] = LLVMBuildBitCast(builder, texel_out[chan],
+                                            lp_build_vec_type(gallivm, type), "");
+      }
+   }
+}
+
+void
+lp_build_size_query_soa(struct gallivm_state *gallivm,
+                        const struct lp_static_texture_state *static_state,
+                        struct lp_sampler_dynamic_state *dynamic_state,
+                        struct lp_type int_type,
+                        unsigned texture_unit,
+                        unsigned target,
+                        boolean need_nr_mips,
+                        boolean scalar_lod,
+                        LLVMValueRef explicit_lod,
+                        LLVMValueRef *sizes_out)
+{
+   LLVMValueRef lod, level, size;
+   LLVMValueRef first_level = NULL;
+   int dims, i;
+   boolean has_array;
+   unsigned num_lods = 1;
+   struct lp_build_context bld_int_vec;
 
-      lp_build_sample_general(&bld, unit, s, t, r, ddx, ddy,
-                              lod_bias, explicit_lod,
-                              texel_out);
+   /*
+    * Do some sanity verification about bound texture and shader dcl target.
+    * Not entirely sure what's possible but assume array/non-array
+    * always compatible (probably not ok for OpenGL but d3d10 has no
+    * distinction of arrays at the resource level).
+    * Everything else looks bogus (though not entirely sure about rect/2d).
+    * Currently disabled because it causes assertion failures if there's
+    * nothing bound (or rather a dummy texture, not that this case would
+    * return the right values).
+    */
+   if (0 && static_state->target != target) {
+      if (static_state->target == PIPE_TEXTURE_1D)
+         assert(target == PIPE_TEXTURE_1D_ARRAY);
+      else if (static_state->target == PIPE_TEXTURE_1D_ARRAY)
+         assert(target == PIPE_TEXTURE_1D);
+      else if (static_state->target == PIPE_TEXTURE_2D)
+         assert(target == PIPE_TEXTURE_2D_ARRAY);
+      else if (static_state->target == PIPE_TEXTURE_2D_ARRAY)
+         assert(target == PIPE_TEXTURE_2D);
+      else if (static_state->target == PIPE_TEXTURE_CUBE)
+         assert(target == PIPE_TEXTURE_CUBE_ARRAY);
+      else if (static_state->target == PIPE_TEXTURE_CUBE_ARRAY)
+         assert(target == PIPE_TEXTURE_CUBE);
+      else
+         assert(0);
    }
 
-   lp_build_sample_compare(&bld, r, texel_out);
+   dims = texture_dims(target);
+
+   switch (target) {
+   case PIPE_TEXTURE_1D_ARRAY:
+   case PIPE_TEXTURE_2D_ARRAY:
+      has_array = TRUE;
+      break;
+   default:
+      has_array = FALSE;
+      break;
+   }
+
+   assert(!int_type.floating);
+
+   lp_build_context_init(&bld_int_vec, gallivm, lp_type_int_vec(32, 128));
+
+   if (explicit_lod) {
+      /* FIXME: this needs to honor per-element lod */
+      lod = LLVMBuildExtractElement(gallivm->builder, explicit_lod, lp_build_const_int32(gallivm, 0), "");
+      first_level = dynamic_state->first_level(dynamic_state, gallivm, texture_unit);
+      level = LLVMBuildAdd(gallivm->builder, lod, first_level, "level");
+      lod = lp_build_broadcast_scalar(&bld_int_vec, level);
+   } else {
+      lod = bld_int_vec.zero;
+   }
+
+   if (need_nr_mips) {
+      size = bld_int_vec.zero;
+   }
+   else {
+      size = bld_int_vec.undef;
+   }
+
+   size = LLVMBuildInsertElement(gallivm->builder, size,
+                                 dynamic_state->width(dynamic_state, gallivm, texture_unit),
+                                 lp_build_const_int32(gallivm, 0), "");
+
+   if (dims >= 2) {
+      size = LLVMBuildInsertElement(gallivm->builder, size,
+                                    dynamic_state->height(dynamic_state, gallivm, texture_unit),
+                                    lp_build_const_int32(gallivm, 1), "");
+   }
 
-   apply_sampler_swizzle(&bld, texel_out);
+   if (dims >= 3) {
+      size = LLVMBuildInsertElement(gallivm->builder, size,
+                                    dynamic_state->depth(dynamic_state, gallivm, texture_unit),
+                                    lp_build_const_int32(gallivm, 2), "");
+   }
+
+   size = lp_build_minify(&bld_int_vec, size, lod);
+
+   if (has_array)
+      size = LLVMBuildInsertElement(gallivm->builder, size,
+                                    dynamic_state->depth(dynamic_state, gallivm, texture_unit),
+                                    lp_build_const_int32(gallivm, dims), "");
+
+   /*
+    * d3d10 requires zero for x/y/z values (but not w, i.e. mip levels)
+    * if level is out of bounds (note this can't cover unbound texture
+    * here, which also requires returning zero).
+    */
+   if (explicit_lod && need_nr_mips) {
+      LLVMValueRef last_level, out, out1;
+      struct lp_build_context leveli_bld;
+
+      /* everything is scalar for now */
+      lp_build_context_init(&leveli_bld, gallivm, lp_type_int_vec(32, 32));
+      last_level = dynamic_state->last_level(dynamic_state, gallivm, texture_unit);
+
+      out = lp_build_cmp(&leveli_bld, PIPE_FUNC_LESS, level, first_level);
+      out1 = lp_build_cmp(&leveli_bld, PIPE_FUNC_GREATER, level, last_level);
+      out = lp_build_or(&leveli_bld, out, out1);
+      if (num_lods == 1) {
+         out = lp_build_broadcast_scalar(&bld_int_vec, out);
+      }
+      else {
+         /* TODO */
+         assert(0);
+      }
+      size = lp_build_andnot(&bld_int_vec, size, out);
+   }
+   for (i = 0; i < dims + (has_array ? 1 : 0); i++) {
+      sizes_out[i] = lp_build_extract_broadcast(gallivm, bld_int_vec.type, int_type,
+                                                size,
+                                                lp_build_const_int32(gallivm, i));
+   }
+
+   /*
+    * if there's no explicit_lod (buffers, rects) queries requiring nr of
+    * mips would be illegal.
+    */
+   if (need_nr_mips && explicit_lod) {
+      struct lp_build_context bld_int_scalar;
+      LLVMValueRef num_levels;
+      lp_build_context_init(&bld_int_scalar, gallivm, lp_type_int(32));
+
+      if (static_state->level_zero_only) {
+         num_levels = bld_int_scalar.one;
+      }
+      else {
+         LLVMValueRef last_level;
+
+         last_level = dynamic_state->last_level(dynamic_state, gallivm, texture_unit);
+         num_levels = lp_build_sub(&bld_int_scalar, last_level, first_level);
+         num_levels = lp_build_add(&bld_int_scalar, num_levels, bld_int_scalar.one);
+      }
+      sizes_out[3] = lp_build_broadcast(gallivm, lp_build_vec_type(gallivm, int_type),
+                                        num_levels);
+   }
 }