swr/rast: Add autogen of helper llvm intrinsics.
[mesa.git] / src / gallium / drivers / radeonsi / si_shader_tgsi_mem.c
index bd8ecb70f8cf6dd3b273ac162f386f7eded30e95..6a307c4ddba99f8c0a7483f68893a7427a8d9a00 100644 (file)
@@ -1,5 +1,6 @@
 /*
  * Copyright 2017 Advanced Micro Devices, Inc.
+ * All Rights Reserved.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -37,13 +38,6 @@ static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
 
 static const struct lp_build_tgsi_action tex_action;
 
-enum desc_type {
-       DESC_IMAGE,
-       DESC_BUFFER,
-       DESC_FMASK,
-       DESC_SAMPLER,
-};
-
 /**
  * Given a v8i32 resource descriptor for a buffer, extract the size of the
  * buffer in number of elements and return it as an i32.
@@ -53,13 +47,12 @@ static LLVMValueRef get_buffer_size(
        LLVMValueRef descriptor)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        LLVMValueRef size =
                LLVMBuildExtractElement(builder, descriptor,
                                        LLVMConstInt(ctx->i32, 2, 0), "");
 
-       if (ctx->screen->b.chip_class == VI) {
+       if (ctx->screen->info.chip_class == VI) {
                /* On VI, the descriptor contains the size in bytes,
                 * but TXQ must return the size in elements.
                 * The stride is always non-zero for resources using TXQ.
@@ -80,36 +73,22 @@ static LLVMValueRef get_buffer_size(
 
 static LLVMValueRef
 shader_buffer_fetch_rsrc(struct si_shader_context *ctx,
-                        const struct tgsi_full_src_register *reg)
+                        const struct tgsi_full_src_register *reg,
+                        bool ubo)
 {
        LLVMValueRef index;
-       LLVMValueRef rsrc_ptr = LLVMGetParam(ctx->main_fn,
-                                            ctx->param_const_and_shader_buffers);
 
        if (!reg->Register.Indirect) {
-               index = LLVMConstInt(ctx->i32,
-                                    si_get_shaderbuf_slot(reg->Register.Index), 0);
+               index = LLVMConstInt(ctx->i32, reg->Register.Index, false);
        } else {
-               index = si_get_bounded_indirect_index(ctx, &reg->Indirect,
-                                                     reg->Register.Index,
-                                                     ctx->num_shader_buffers);
-               index = LLVMBuildSub(ctx->gallivm.builder,
-                                    LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS - 1, 0),
-                                    index, "");
+               index = si_get_indirect_index(ctx, &reg->Indirect,
+                                             1, reg->Register.Index);
        }
 
-       return ac_build_indexed_load_const(&ctx->ac, rsrc_ptr, index);
-}
-
-static bool tgsi_is_array_sampler(unsigned target)
-{
-       return target == TGSI_TEXTURE_1D_ARRAY ||
-              target == TGSI_TEXTURE_SHADOW1D_ARRAY ||
-              target == TGSI_TEXTURE_2D_ARRAY ||
-              target == TGSI_TEXTURE_SHADOW2D_ARRAY ||
-              target == TGSI_TEXTURE_CUBE_ARRAY ||
-              target == TGSI_TEXTURE_SHADOWCUBE_ARRAY ||
-              target == TGSI_TEXTURE_2D_ARRAY_MSAA;
+       if (ubo)
+               return ctx->abi.load_ubo(&ctx->abi, index);
+       else
+               return ctx->abi.load_ssbo(&ctx->abi, index, false);
 }
 
 static bool tgsi_is_array_image(unsigned target)
@@ -136,36 +115,41 @@ static bool tgsi_is_array_image(unsigned target)
 static LLVMValueRef force_dcc_off(struct si_shader_context *ctx,
                                  LLVMValueRef rsrc)
 {
-       if (ctx->screen->b.chip_class <= CIK) {
+       if (ctx->screen->info.chip_class <= CIK) {
                return rsrc;
        } else {
-               LLVMBuilderRef builder = ctx->gallivm.builder;
                LLVMValueRef i32_6 = LLVMConstInt(ctx->i32, 6, 0);
                LLVMValueRef i32_C = LLVMConstInt(ctx->i32, C_008F28_COMPRESSION_EN, 0);
                LLVMValueRef tmp;
 
-               tmp = LLVMBuildExtractElement(builder, rsrc, i32_6, "");
-               tmp = LLVMBuildAnd(builder, tmp, i32_C, "");
-               return LLVMBuildInsertElement(builder, rsrc, tmp, i32_6, "");
+               tmp = LLVMBuildExtractElement(ctx->ac.builder, rsrc, i32_6, "");
+               tmp = LLVMBuildAnd(ctx->ac.builder, tmp, i32_C, "");
+               return LLVMBuildInsertElement(ctx->ac.builder, rsrc, tmp, i32_6, "");
        }
 }
 
-static LLVMValueRef load_image_desc(struct si_shader_context *ctx,
-                                   LLVMValueRef list, LLVMValueRef index,
-                                   unsigned target)
+LLVMValueRef si_load_image_desc(struct si_shader_context *ctx,
+                               LLVMValueRef list, LLVMValueRef index,
+                               enum ac_descriptor_type desc_type, bool dcc_off)
 {
-       LLVMBuilderRef builder = ctx->gallivm.builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
+       LLVMValueRef rsrc;
 
-       if (target == TGSI_TEXTURE_BUFFER) {
+       if (desc_type == AC_DESC_BUFFER) {
                index = LLVMBuildMul(builder, index,
                                     LLVMConstInt(ctx->i32, 2, 0), "");
                index = LLVMBuildAdd(builder, index,
                                     ctx->i32_1, "");
                list = LLVMBuildPointerCast(builder, list,
-                                           si_const_array(ctx->v4i32, 0), "");
+                                           ac_array_in_const32_addr_space(ctx->v4i32), "");
+       } else {
+               assert(desc_type == AC_DESC_IMAGE);
        }
 
-       return ac_build_indexed_load_const(&ctx->ac, list, index);
+       rsrc = ac_build_load_to_sgpr(&ctx->ac, list, index);
+       if (desc_type == AC_DESC_IMAGE && dcc_off)
+               rsrc = force_dcc_off(ctx, rsrc);
+       return rsrc;
 }
 
 /**
@@ -184,8 +168,6 @@ image_fetch_rsrc(
        LLVMValueRef index;
        bool dcc_off = is_store;
 
-       assert(image->Register.File == TGSI_FILE_IMAGE);
-
        if (!image->Register.Indirect) {
                const struct tgsi_shader_info *info = bld_base->info;
                unsigned images_writemask = info->images_store |
@@ -209,14 +191,30 @@ image_fetch_rsrc(
                index = si_get_bounded_indirect_index(ctx, &image->Indirect,
                                                      image->Register.Index,
                                                      ctx->num_images);
-               index = LLVMBuildSub(ctx->gallivm.builder,
+               index = LLVMBuildSub(ctx->ac.builder,
                                     LLVMConstInt(ctx->i32, SI_NUM_IMAGES - 1, 0),
                                     index, "");
        }
 
-       *rsrc = load_image_desc(ctx, rsrc_ptr, index, target);
-       if (dcc_off && target != TGSI_TEXTURE_BUFFER)
-               *rsrc = force_dcc_off(ctx, *rsrc);
+       if (image->Register.File != TGSI_FILE_IMAGE) {
+               /* Bindless descriptors are accessible from a different pair of
+                * user SGPR indices.
+                */
+               rsrc_ptr = LLVMGetParam(ctx->main_fn,
+                                       ctx->param_bindless_samplers_and_images);
+               index = lp_build_emit_fetch_src(bld_base, image,
+                                               TGSI_TYPE_UNSIGNED, 0);
+
+               /* For simplicity, bindless image descriptors use fixed
+                * 16-dword slots for now.
+                */
+               index = LLVMBuildMul(ctx->ac.builder, index,
+                                    LLVMConstInt(ctx->i32, 2, 0), "");
+       }
+
+       *rsrc = si_load_image_desc(ctx, rsrc_ptr, index,
+                                  target == TGSI_TEXTURE_BUFFER ? AC_DESC_BUFFER : AC_DESC_IMAGE,
+                                  dcc_off);
 }
 
 static LLVMValueRef image_fetch_coords(
@@ -225,8 +223,7 @@ static LLVMValueRef image_fetch_coords(
                unsigned src, LLVMValueRef desc)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        unsigned target = inst->Memory.Texture;
        unsigned num_coords = tgsi_util_get_texture_coord_dim(target);
        LLVMValueRef coords[4];
@@ -235,11 +232,11 @@ static LLVMValueRef image_fetch_coords(
 
        for (chan = 0; chan < num_coords; ++chan) {
                tmp = lp_build_emit_fetch(bld_base, inst, src, chan);
-               tmp = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               tmp = ac_to_integer(&ctx->ac, tmp);
                coords[chan] = tmp;
        }
 
-       if (ctx->screen->b.chip_class >= GFX9) {
+       if (ctx->screen->info.chip_class >= GFX9) {
                /* 1D textures are allocated and used as 2D on GFX9. */
                if (target == TGSI_TEXTURE_1D) {
                        coords[1] = ctx->i32_0;
@@ -275,7 +272,7 @@ static LLVMValueRef image_fetch_coords(
                num_coords = 4;
        }
 
-       return lp_build_gather_values(gallivm, coords, num_coords);
+       return lp_build_gather_values(&ctx->gallivm, coords, num_coords);
 }
 
 /**
@@ -300,7 +297,7 @@ static void image_append_args(
        LLVMValueRef slc = i1false;
        LLVMValueRef lwe = i1false;
 
-       if (atomic || (HAVE_LLVM <= 0x0309)) {
+       if (atomic) {
                emit_data->args[emit_data->arg_count++] = r128;
                emit_data->args[emit_data->arg_count++] = da;
                if (!atomic) {
@@ -310,7 +307,6 @@ static void image_append_args(
                return;
        }
 
-       /* HAVE_LLVM >= 0x0400 */
        emit_data->args[emit_data->arg_count++] = glc;
        emit_data->args[emit_data->arg_count++] = slc;
        emit_data->args[emit_data->arg_count++] = lwe;
@@ -354,26 +350,27 @@ static void load_fetch_args(
                struct lp_build_emit_data * emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        unsigned target = inst->Memory.Texture;
        LLVMValueRef rsrc;
 
        emit_data->dst_type = ctx->v4f32;
 
-       if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
-               LLVMBuilderRef builder = gallivm->builder;
+       if (inst->Src[0].Register.File == TGSI_FILE_BUFFER ||
+                  inst->Src[0].Register.File == TGSI_FILE_CONSTBUF) {
                LLVMValueRef offset;
                LLVMValueRef tmp;
 
-               rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0]);
+               bool ubo = inst->Src[0].Register.File == TGSI_FILE_CONSTBUF;
+               rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0], ubo);
 
                tmp = lp_build_emit_fetch(bld_base, inst, 1, 0);
-               offset = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               offset = ac_to_integer(&ctx->ac, tmp);
 
                buffer_append_args(ctx, emit_data, rsrc, ctx->i32_0,
                                   offset, false, false);
-       } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE) {
+       } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE ||
+                  tgsi_is_bindless_image_file(inst->Src[0].Register.File)) {
                LLVMValueRef coords;
 
                image_fetch_rsrc(bld_base, &inst->Src[0], false, target, &rsrc);
@@ -393,68 +390,50 @@ static void load_fetch_args(
        }
 }
 
-static unsigned get_load_intr_attribs(bool readonly_memory)
-{
-       /* READNONE means writes can't affect it, while READONLY means that
-        * writes can affect it. */
-       return readonly_memory && HAVE_LLVM >= 0x0400 ?
-                                LP_FUNC_ATTR_READNONE :
-                                LP_FUNC_ATTR_READONLY;
-}
-
-static unsigned get_store_intr_attribs(bool writeonly_memory)
-{
-       return writeonly_memory && HAVE_LLVM >= 0x0400 ?
-                                 LP_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
-                                 LP_FUNC_ATTR_WRITEONLY;
-}
-
 static void load_emit_buffer(struct si_shader_context *ctx,
                             struct lp_build_emit_data *emit_data,
-                            bool readonly_memory)
+                            bool can_speculate, bool allow_smem)
 {
        const struct tgsi_full_instruction *inst = emit_data->inst;
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
        uint writemask = inst->Dst[0].Register.WriteMask;
        uint count = util_last_bit(writemask);
-       const char *intrinsic_name;
-       LLVMTypeRef dst_type;
+       LLVMValueRef *args = emit_data->args;
 
-       switch (count) {
-       case 1:
-               intrinsic_name = "llvm.amdgcn.buffer.load.f32";
-               dst_type = ctx->f32;
-               break;
-       case 2:
-               intrinsic_name = "llvm.amdgcn.buffer.load.v2f32";
-               dst_type = LLVMVectorType(ctx->f32, 2);
-               break;
-       default: // 3 & 4
-               intrinsic_name = "llvm.amdgcn.buffer.load.v4f32";
-               dst_type = ctx->v4f32;
-               count = 4;
-       }
+       /* Don't use SMEM for shader buffer loads, because LLVM doesn't
+        * select SMEM for SI.load.const with a non-constant offset, and
+        * constant offsets practically don't exist with shader buffers.
+        *
+        * Also, SI.load.const doesn't use inst_offset when it's lowered
+        * to VMEM, so we just end up with more VALU instructions in the end
+        * and no benefit.
+        *
+        * TODO: Remove this line once LLVM can select SMEM with a non-constant
+        *       offset, and can derive inst_offset when VMEM is selected.
+        *       After that, si_memory_barrier should invalidate sL1 for shader
+        *       buffers.
+        */
 
-       emit_data->output[emit_data->chan] = lp_build_intrinsic(
-                       builder, intrinsic_name, dst_type,
-                       emit_data->args, emit_data->arg_count,
-                       get_load_intr_attribs(readonly_memory));
+       assert(LLVMConstIntGetZExtValue(args[1]) == 0); /* vindex */
+       emit_data->output[emit_data->chan] =
+               ac_build_buffer_load(&ctx->ac, args[0], count, NULL,
+                                    args[2], NULL, 0,
+                                    LLVMConstIntGetZExtValue(args[3]),
+                                    LLVMConstIntGetZExtValue(args[4]),
+                                    can_speculate, allow_smem);
 }
 
 static LLVMValueRef get_memory_ptr(struct si_shader_context *ctx,
                                    const struct tgsi_full_instruction *inst,
                                    LLVMTypeRef type, int arg)
 {
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        LLVMValueRef offset, ptr;
        int addr_space;
 
        offset = lp_build_emit_fetch(&ctx->bld_base, inst, arg, 0);
-       offset = LLVMBuildBitCast(builder, offset, ctx->i32, "");
+       offset = ac_to_integer(&ctx->ac, offset);
 
-       ptr = ctx->shared_memory;
+       ptr = ctx->ac.lds;
        ptr = LLVMBuildGEP(builder, ptr, &offset, 1, "");
        addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
        ptr = LLVMBuildBitCast(builder, ptr, LLVMPointerType(type, addr_space), "");
@@ -467,8 +446,6 @@ static void load_emit_memory(
                struct lp_build_emit_data *emit_data)
 {
        const struct tgsi_full_instruction *inst = emit_data->inst;
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
        unsigned writemask = inst->Dst[0].Register.WriteMask;
        LLVMValueRef channels[4], ptr, derived_ptr, index;
        int chan;
@@ -482,10 +459,10 @@ static void load_emit_memory(
                }
 
                index = LLVMConstInt(ctx->i32, chan, 0);
-               derived_ptr = LLVMBuildGEP(builder, ptr, &index, 1, "");
-               channels[chan] = LLVMBuildLoad(builder, derived_ptr, "");
+               derived_ptr = LLVMBuildGEP(ctx->ac.builder, ptr, &index, 1, "");
+               channels[chan] = LLVMBuildLoad(ctx->ac.builder, derived_ptr, "");
        }
-       emit_data->output[emit_data->chan] = lp_build_gather_values(gallivm, channels, 4);
+       emit_data->output[emit_data->chan] = lp_build_gather_values(&ctx->gallivm, channels, 4);
 }
 
 /**
@@ -538,8 +515,9 @@ static bool is_oneway_access_only(const struct tgsi_full_instruction *inst,
         * images.
         */
        if (inst->Src[0].Register.File == TGSI_FILE_BUFFER ||
-           (inst->Src[0].Register.File == TGSI_FILE_IMAGE &&
-            inst->Memory.Texture == TGSI_TEXTURE_BUFFER)) {
+           (inst->Memory.Texture == TGSI_TEXTURE_BUFFER &&
+            (inst->Src[0].Register.File == TGSI_FILE_IMAGE ||
+             tgsi_is_bindless_image_file(inst->Src[0].Register.File)))) {
                if (!shader_buffers_reverse_access_mask &&
                    !(info->images_buffers & images_reverse_access_mask))
                        return true;
@@ -556,22 +534,26 @@ static void load_emit(
                struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        const struct tgsi_shader_info *info = &ctx->shader->selector->info;
        char intrinsic_name[64];
-       bool readonly_memory = false;
+       bool can_speculate = false;
 
        if (inst->Src[0].Register.File == TGSI_FILE_MEMORY) {
                load_emit_memory(ctx, emit_data);
                return;
        }
 
+       if (inst->Src[0].Register.File == TGSI_FILE_CONSTBUF) {
+               load_emit_buffer(ctx, emit_data, true, true);
+               return;
+       }
+
        if (inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE)
-               si_emit_waitcnt(ctx, VM_CNT);
+               ac_build_waitcnt(&ctx->ac, VM_CNT);
 
-       readonly_memory = !(inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE) &&
+       can_speculate = !(inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE) &&
                          is_oneway_access_only(inst, info,
                                                info->shader_buffers_store |
                                                info->shader_buffers_atomic,
@@ -579,16 +561,22 @@ static void load_emit(
                                                info->images_atomic);
 
        if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
-               load_emit_buffer(ctx, emit_data, readonly_memory);
+               load_emit_buffer(ctx, emit_data, can_speculate, false);
                return;
        }
 
        if (inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
+               unsigned num_channels = util_last_bit(inst->Dst[0].Register.WriteMask);
+               LLVMValueRef result =
+                       ac_build_buffer_load_format(&ctx->ac,
+                                                   emit_data->args[0],
+                                                   emit_data->args[1],
+                                                   emit_data->args[2],
+                                                   num_channels,
+                                                   LLVMConstIntGetZExtValue(emit_data->args[3]),
+                                                   can_speculate);
                emit_data->output[emit_data->chan] =
-                       lp_build_intrinsic(
-                               builder, "llvm.amdgcn.buffer.load.format.v4f32", emit_data->dst_type,
-                               emit_data->args, emit_data->arg_count,
-                               get_load_intr_attribs(readonly_memory));
+                       ac_build_expand_to_vec4(&ctx->ac, result, num_channels);
        } else {
                ac_get_image_intr_name("llvm.amdgcn.image.load",
                                       emit_data->dst_type,             /* vdata */
@@ -600,7 +588,7 @@ static void load_emit(
                        lp_build_intrinsic(
                                builder, intrinsic_name, emit_data->dst_type,
                                emit_data->args, emit_data->arg_count,
-                               get_load_intr_attribs(readonly_memory));
+                               ac_get_load_intr_attribs(can_speculate));
        }
 }
 
@@ -609,8 +597,6 @@ static void store_fetch_args(
                struct lp_build_emit_data * emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        struct tgsi_full_src_register memory;
        LLVMValueRef chans[4];
@@ -618,12 +604,12 @@ static void store_fetch_args(
        LLVMValueRef rsrc;
        unsigned chan;
 
-       emit_data->dst_type = LLVMVoidTypeInContext(gallivm->context);
+       emit_data->dst_type = ctx->voidt;
 
        for (chan = 0; chan < 4; ++chan) {
                chans[chan] = lp_build_emit_fetch(bld_base, inst, 1, chan);
        }
-       data = lp_build_gather_values(gallivm, chans, 4);
+       data = lp_build_gather_values(&ctx->gallivm, chans, 4);
 
        emit_data->args[emit_data->arg_count++] = data;
 
@@ -633,14 +619,15 @@ static void store_fetch_args(
                LLVMValueRef offset;
                LLVMValueRef tmp;
 
-               rsrc = shader_buffer_fetch_rsrc(ctx, &memory);
+               rsrc = shader_buffer_fetch_rsrc(ctx, &memory, false);
 
                tmp = lp_build_emit_fetch(bld_base, inst, 0, 0);
-               offset = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               offset = ac_to_integer(&ctx->ac, tmp);
 
                buffer_append_args(ctx, emit_data, rsrc, ctx->i32_0,
                                   offset, false, false);
-       } else if (inst->Dst[0].Register.File == TGSI_FILE_IMAGE) {
+       } else if (inst->Dst[0].Register.File == TGSI_FILE_IMAGE ||
+                  tgsi_is_bindless_image_file(inst->Dst[0].Register.File)) {
                unsigned target = inst->Memory.Texture;
                LLVMValueRef coords;
 
@@ -650,7 +637,7 @@ static void store_fetch_args(
                 * The only way to get unaligned stores in radeonsi is through
                 * shader images.
                 */
-               bool force_glc = ctx->screen->b.chip_class == SI;
+               bool force_glc = ctx->screen->info.chip_class == SI;
 
                image_fetch_rsrc(bld_base, &memory, true, target, &rsrc);
                coords = image_fetch_coords(bld_base, inst, 0, rsrc);
@@ -675,8 +662,7 @@ static void store_emit_buffer(
                bool writeonly_memory)
 {
        const struct tgsi_full_instruction *inst = emit_data->inst;
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        LLVMValueRef base_data = emit_data->args[0];
        LLVMValueRef base_offset = emit_data->args[3];
        unsigned writemask = inst->Dst[0].Register.WriteMask;
@@ -738,7 +724,7 @@ static void store_emit_buffer(
                lp_build_intrinsic(
                        builder, intrinsic_name, emit_data->dst_type,
                        emit_data->args, emit_data->arg_count,
-                       get_store_intr_attribs(writeonly_memory));
+                       ac_get_store_intr_attribs(writeonly_memory));
        }
 }
 
@@ -747,8 +733,7 @@ static void store_emit_memory(
                struct lp_build_emit_data *emit_data)
 {
        const struct tgsi_full_instruction *inst = emit_data->inst;
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        unsigned writemask = inst->Dst[0].Register.WriteMask;
        LLVMValueRef ptr, derived_ptr, data, index;
        int chan;
@@ -772,8 +757,7 @@ static void store_emit(
                struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        const struct tgsi_shader_info *info = &ctx->shader->selector->info;
        unsigned target = inst->Memory.Texture;
@@ -786,7 +770,7 @@ static void store_emit(
        }
 
        if (inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE)
-               si_emit_waitcnt(ctx, VM_CNT);
+               ac_build_waitcnt(&ctx->ac, VM_CNT);
 
        writeonly_memory = is_oneway_access_only(inst, info,
                                                 info->shader_buffers_load |
@@ -804,7 +788,7 @@ static void store_emit(
                        builder, "llvm.amdgcn.buffer.store.format.v4f32",
                        emit_data->dst_type, emit_data->args,
                        emit_data->arg_count,
-                       get_store_intr_attribs(writeonly_memory));
+                       ac_get_store_intr_attribs(writeonly_memory));
        } else {
                ac_get_image_intr_name("llvm.amdgcn.image.store",
                                       LLVMTypeOf(emit_data->args[0]), /* vdata */
@@ -816,7 +800,7 @@ static void store_emit(
                        lp_build_intrinsic(
                                builder, intrinsic_name, emit_data->dst_type,
                                emit_data->args, emit_data->arg_count,
-                               get_store_intr_attribs(writeonly_memory));
+                               ac_get_store_intr_attribs(writeonly_memory));
        }
 }
 
@@ -825,8 +809,6 @@ static void atomic_fetch_args(
                struct lp_build_emit_data * emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        LLVMValueRef data1, data2;
        LLVMValueRef rsrc;
@@ -835,11 +817,11 @@ static void atomic_fetch_args(
        emit_data->dst_type = ctx->f32;
 
        tmp = lp_build_emit_fetch(bld_base, inst, 2, 0);
-       data1 = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+       data1 = ac_to_integer(&ctx->ac, tmp);
 
        if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS) {
                tmp = lp_build_emit_fetch(bld_base, inst, 3, 0);
-               data2 = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               data2 = ac_to_integer(&ctx->ac, tmp);
        }
 
        /* llvm.amdgcn.image/buffer.atomic.cmpswap reflect the hardware order
@@ -852,14 +834,15 @@ static void atomic_fetch_args(
        if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
                LLVMValueRef offset;
 
-               rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0]);
+               rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0], false);
 
                tmp = lp_build_emit_fetch(bld_base, inst, 1, 0);
-               offset = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               offset = ac_to_integer(&ctx->ac, tmp);
 
                buffer_append_args(ctx, emit_data, rsrc, ctx->i32_0,
                                   offset, true, false);
-       } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE) {
+       } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE ||
+                  tgsi_is_bindless_image_file(inst->Src[0].Register.File)) {
                unsigned target = inst->Memory.Texture;
                LLVMValueRef coords;
 
@@ -880,22 +863,21 @@ static void atomic_fetch_args(
 
 static void atomic_emit_memory(struct si_shader_context *ctx,
                                struct lp_build_emit_data *emit_data) {
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        LLVMValueRef ptr, result, arg;
 
        ptr = get_memory_ptr(ctx, inst, ctx->i32, 1);
 
        arg = lp_build_emit_fetch(&ctx->bld_base, inst, 2, 0);
-       arg = LLVMBuildBitCast(builder, arg, ctx->i32, "");
+       arg = ac_to_integer(&ctx->ac, arg);
 
        if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS) {
                LLVMValueRef new_data;
                new_data = lp_build_emit_fetch(&ctx->bld_base,
                                               inst, 3, 0);
 
-               new_data = LLVMBuildBitCast(builder, new_data, ctx->i32, "");
+               new_data = ac_to_integer(&ctx->ac, new_data);
 
                result = LLVMBuildAtomicCmpXchg(builder, ptr, arg, new_data,
                                       LLVMAtomicOrderingSequentiallyConsistent,
@@ -951,8 +933,7 @@ static void atomic_emit(
                struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        const struct tgsi_full_instruction * inst = emit_data->inst;
        char intrinsic_name[40];
        LLVMValueRef tmp;
@@ -984,8 +965,7 @@ static void atomic_emit(
        tmp = lp_build_intrinsic(
                builder, intrinsic_name, ctx->i32,
                emit_data->args, emit_data->arg_count, 0);
-       emit_data->output[emit_data->chan] =
-               LLVMBuildBitCast(builder, tmp, ctx->f32, "");
+       emit_data->output[emit_data->chan] = ac_to_float(&ctx->ac, tmp);
 }
 
 static void set_tex_fetch_args(struct si_shader_context *ctx,
@@ -995,7 +975,6 @@ static void set_tex_fetch_args(struct si_shader_context *ctx,
                               LLVMValueRef *param, unsigned count,
                               unsigned dmask)
 {
-       struct gallivm_state *gallivm = &ctx->gallivm;
        struct ac_image_args args = {};
 
        /* Pad to power of two vector */
@@ -1003,7 +982,7 @@ static void set_tex_fetch_args(struct si_shader_context *ctx,
                param[count++] = LLVMGetUndef(ctx->i32);
 
        if (count > 1)
-               args.addr = lp_build_gather_values(gallivm, param, count);
+               args.addr = lp_build_gather_values(&ctx->gallivm, param, count);
        else
                args.addr = param[0];
 
@@ -1022,10 +1001,10 @@ static void set_tex_fetch_args(struct si_shader_context *ctx,
 static LLVMValueRef fix_resinfo(struct si_shader_context *ctx,
                                unsigned target, LLVMValueRef out)
 {
-       LLVMBuilderRef builder = ctx->gallivm.builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
 
        /* 1D textures are allocated and used as 2D on GFX9. */
-        if (ctx->screen->b.chip_class >= GFX9 &&
+        if (ctx->screen->info.chip_class >= GFX9 &&
            (target == TGSI_TEXTURE_1D_ARRAY ||
             target == TGSI_TEXTURE_SHADOW1D_ARRAY)) {
                LLVMValueRef layers =
@@ -1059,7 +1038,7 @@ static void resq_fetch_args(
        emit_data->dst_type = ctx->v4i32;
 
        if (reg->Register.File == TGSI_FILE_BUFFER) {
-               emit_data->args[0] = shader_buffer_fetch_rsrc(ctx, reg);
+               emit_data->args[0] = shader_buffer_fetch_rsrc(ctx, reg, false);
                emit_data->arg_count = 1;
        } else if (inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
                image_fetch_rsrc(bld_base, reg, false, inst->Memory.Texture,
@@ -1088,8 +1067,7 @@ static void resq_emit(
                struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
        const struct tgsi_full_instruction *inst = emit_data->inst;
        LLVMValueRef out;
 
@@ -1114,40 +1092,39 @@ static void resq_emit(
 /**
  * Load an image view, fmask view. or sampler state descriptor.
  */
-static LLVMValueRef load_sampler_desc(struct si_shader_context *ctx,
-                                     LLVMValueRef list, LLVMValueRef index,
-                                     enum desc_type type)
+LLVMValueRef si_load_sampler_desc(struct si_shader_context *ctx,
+                                 LLVMValueRef list, LLVMValueRef index,
+                                 enum ac_descriptor_type type)
 {
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
 
        switch (type) {
-       case DESC_IMAGE:
+       case AC_DESC_IMAGE:
                /* The image is at [0:7]. */
                index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
                break;
-       case DESC_BUFFER:
+       case AC_DESC_BUFFER:
                /* The buffer is in [4:7]. */
                index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
                index = LLVMBuildAdd(builder, index, ctx->i32_1, "");
                list = LLVMBuildPointerCast(builder, list,
-                                           si_const_array(ctx->v4i32, 0), "");
+                                           ac_array_in_const32_addr_space(ctx->v4i32), "");
                break;
-       case DESC_FMASK:
+       case AC_DESC_FMASK:
                /* The FMASK is at [8:15]. */
                index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
                index = LLVMBuildAdd(builder, index, ctx->i32_1, "");
                break;
-       case DESC_SAMPLER:
+       case AC_DESC_SAMPLER:
                /* The sampler state is at [12:15]. */
                index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
                index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 3, 0), "");
                list = LLVMBuildPointerCast(builder, list,
-                                           si_const_array(ctx->v4i32, 0), "");
+                                           ac_array_in_const32_addr_space(ctx->v4i32), "");
                break;
        }
 
-       return ac_build_indexed_load_const(&ctx->ac, list, index);
+       return ac_build_load_to_sgpr(&ctx->ac, list, index);
 }
 
 /* Disable anisotropic filtering if BASE_LEVEL == LAST_LEVEL.
@@ -1164,18 +1141,17 @@ static LLVMValueRef load_sampler_desc(struct si_shader_context *ctx,
 static LLVMValueRef sici_fix_sampler_aniso(struct si_shader_context *ctx,
                                           LLVMValueRef res, LLVMValueRef samp)
 {
-       LLVMBuilderRef builder = ctx->gallivm.builder;
        LLVMValueRef img7, samp0;
 
-       if (ctx->screen->b.chip_class >= VI)
+       if (ctx->screen->info.chip_class >= VI)
                return samp;
 
-       img7 = LLVMBuildExtractElement(builder, res,
+       img7 = LLVMBuildExtractElement(ctx->ac.builder, res,
                                       LLVMConstInt(ctx->i32, 7, 0), "");
-       samp0 = LLVMBuildExtractElement(builder, samp,
+       samp0 = LLVMBuildExtractElement(ctx->ac.builder, samp,
                                        ctx->i32_0, "");
-       samp0 = LLVMBuildAnd(builder, samp0, img7, "");
-       return LLVMBuildInsertElement(builder, samp, samp0,
+       samp0 = LLVMBuildAnd(ctx->ac.builder, samp0, img7, "");
+       return LLVMBuildInsertElement(ctx->ac.builder, samp, samp0,
                                      ctx->i32_0, "");
 }
 
@@ -1200,17 +1176,27 @@ static void tex_fetch_ptrs(
                                                      &reg->Indirect,
                                                      reg->Register.Index,
                                                      ctx->num_samplers);
-               index = LLVMBuildAdd(ctx->gallivm.builder, index,
+               index = LLVMBuildAdd(ctx->ac.builder, index,
                                     LLVMConstInt(ctx->i32, SI_NUM_IMAGES / 2, 0), "");
        } else {
                index = LLVMConstInt(ctx->i32,
                                     si_get_sampler_slot(reg->Register.Index), 0);
        }
 
+       if (reg->Register.File != TGSI_FILE_SAMPLER) {
+               /* Bindless descriptors are accessible from a different pair of
+                * user SGPR indices.
+                */
+               list = LLVMGetParam(ctx->main_fn,
+                                   ctx->param_bindless_samplers_and_images);
+               index = lp_build_emit_fetch_src(bld_base, reg,
+                                               TGSI_TYPE_UNSIGNED, 0);
+       }
+
        if (target == TGSI_TEXTURE_BUFFER)
-               *res_ptr = load_sampler_desc(ctx, list, index, DESC_BUFFER);
+               *res_ptr = si_load_sampler_desc(ctx, list, index, AC_DESC_BUFFER);
        else
-               *res_ptr = load_sampler_desc(ctx, list, index, DESC_IMAGE);
+               *res_ptr = si_load_sampler_desc(ctx, list, index, AC_DESC_IMAGE);
 
        if (samp_ptr)
                *samp_ptr = NULL;
@@ -1220,12 +1206,12 @@ static void tex_fetch_ptrs(
        if (target == TGSI_TEXTURE_2D_MSAA ||
            target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
                if (fmask_ptr)
-                       *fmask_ptr = load_sampler_desc(ctx, list, index,
-                                                      DESC_FMASK);
+                       *fmask_ptr = si_load_sampler_desc(ctx, list, index,
+                                                         AC_DESC_FMASK);
        } else if (target != TGSI_TEXTURE_BUFFER) {
                if (samp_ptr) {
-                       *samp_ptr = load_sampler_desc(ctx, list, index,
-                                                     DESC_SAMPLER);
+                       *samp_ptr = si_load_sampler_desc(ctx, list, index,
+                                                        AC_DESC_SAMPLER);
                        *samp_ptr = sici_fix_sampler_aniso(ctx, *res_ptr, *samp_ptr);
                }
        }
@@ -1283,7 +1269,6 @@ static void tex_fetch_args(
        struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
        const struct tgsi_full_instruction *inst = emit_data->inst;
        unsigned opcode = inst->Instruction.Opcode;
        unsigned target = inst->Texture.Texture;
@@ -1311,7 +1296,7 @@ static void tex_fetch_args(
 
        /* Fetch and project texture coordinates */
        coords[3] = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_W);
-       for (chan = 0; chan < 3; chan++ ) {
+       for (chan = 0; chan < 3; chan++) {
                coords[chan] = lp_build_emit_fetch(bld_base,
                                                   emit_data->inst, 0,
                                                   chan);
@@ -1323,7 +1308,7 @@ static void tex_fetch_args(
        }
 
        if (opcode == TGSI_OPCODE_TXP)
-               coords[3] = bld_base->base.one;
+               coords[3] = ctx->ac.f32_1;
 
        /* Pack offsets. */
        if (has_offset &&
@@ -1339,15 +1324,15 @@ static void tex_fetch_args(
                for (chan = 0; chan < 3; chan++) {
                        offset[chan] = lp_build_emit_fetch_texoffset(bld_base,
                                                                     emit_data->inst, 0, chan);
-                       offset[chan] = LLVMBuildAnd(gallivm->builder, offset[chan],
+                       offset[chan] = LLVMBuildAnd(ctx->ac.builder, offset[chan],
                                                    LLVMConstInt(ctx->i32, 0x3f, 0), "");
                        if (chan)
-                               offset[chan] = LLVMBuildShl(gallivm->builder, offset[chan],
+                               offset[chan] = LLVMBuildShl(ctx->ac.builder, offset[chan],
                                                            LLVMConstInt(ctx->i32, chan*8, 0), "");
                }
 
-               pack = LLVMBuildOr(gallivm->builder, offset[0], offset[1], "");
-               pack = LLVMBuildOr(gallivm->builder, pack, offset[2], "");
+               pack = LLVMBuildOr(ctx->ac.builder, offset[0], offset[1], "");
+               pack = LLVMBuildOr(ctx->ac.builder, pack, offset[2], "");
                address[count++] = pack;
        }
 
@@ -1368,15 +1353,28 @@ static void tex_fetch_args(
                        z = coords[ref_pos];
                }
 
-               /* TC-compatible HTILE promotes Z16 and Z24 to Z32_FLOAT,
+               /* Section 8.23.1 (Depth Texture Comparison Mode) of the
+                * OpenGL 4.5 spec says:
+                *
+                *    "If the texture’s internal format indicates a fixed-point
+                *     depth texture, then D_t and D_ref are clamped to the
+                *     range [0, 1]; otherwise no clamping is performed."
+                *
+                * TC-compatible HTILE promotes Z16 and Z24 to Z32_FLOAT,
                 * so the depth comparison value isn't clamped for Z16 and
                 * Z24 anymore. Do it manually here.
-                *
-                * It's unnecessary if the original texture format was
-                * Z32_FLOAT, but we don't know that here.
                 */
-               if (ctx->screen->b.chip_class == VI)
-                       z = ac_build_clamp(&ctx->ac, z);
+               if (ctx->screen->info.chip_class >= VI) {
+                       LLVMValueRef upgraded;
+                       LLVMValueRef clamped;
+                       upgraded = LLVMBuildExtractElement(ctx->ac.builder, samp_ptr,
+                                                          LLVMConstInt(ctx->i32, 3, false), "");
+                       upgraded = LLVMBuildLShr(ctx->ac.builder, upgraded,
+                                                LLVMConstInt(ctx->i32, 29, false), "");
+                       upgraded = LLVMBuildTrunc(ctx->ac.builder, upgraded, ctx->i1, "");
+                       clamped = ac_build_clamp(&ctx->ac, z);
+                       z = LLVMBuildSelect(ctx->ac.builder, upgraded, clamped, z, "");
+               }
 
                address[count++] = z;
        }
@@ -1417,7 +1415,7 @@ static void tex_fetch_args(
                        num_src_deriv_channels = 1;
 
                        /* 1D textures are allocated and used as 2D on GFX9. */
-                       if (ctx->screen->b.chip_class >= GFX9) {
+                       if (ctx->screen->info.chip_class >= GFX9) {
                                num_dst_deriv_channels = 2;
                                num_deriv_channels = 2;
                        } else {
@@ -1438,19 +1436,29 @@ static void tex_fetch_args(
                        for (chan = num_src_deriv_channels;
                             chan < num_dst_deriv_channels; chan++)
                                derivs[param * num_dst_deriv_channels + chan] =
-                                       bld_base->base.zero;
+                                       ctx->ac.f32_0;
                }
        }
 
        if (target == TGSI_TEXTURE_CUBE ||
            target == TGSI_TEXTURE_CUBE_ARRAY ||
            target == TGSI_TEXTURE_SHADOWCUBE ||
-           target == TGSI_TEXTURE_SHADOWCUBE_ARRAY)
+           target == TGSI_TEXTURE_SHADOWCUBE_ARRAY) {
                ac_prepare_cube_coords(&ctx->ac,
                                       opcode == TGSI_OPCODE_TXD,
                                       target == TGSI_TEXTURE_CUBE_ARRAY ||
                                       target == TGSI_TEXTURE_SHADOWCUBE_ARRAY,
+                                      opcode == TGSI_OPCODE_LODQ,
                                       coords, derivs);
+       } else if (tgsi_is_array_sampler(target) &&
+                  opcode != TGSI_OPCODE_TXF &&
+                  opcode != TGSI_OPCODE_TXF_LZ &&
+                  ctx->screen->info.chip_class <= VI) {
+               unsigned array_coord = target == TGSI_TEXTURE_1D_ARRAY ? 1 : 2;
+               coords[array_coord] =
+                       ac_build_intrinsic(&ctx->ac, "llvm.rint.f32", ctx->f32,
+                                          &coords[array_coord], 1, 0);
+       }
 
        if (opcode == TGSI_OPCODE_TXD)
                for (int i = 0; i < num_deriv_channels * 2; i++)
@@ -1464,11 +1472,12 @@ static void tex_fetch_args(
                address[count++] = coords[2];
 
        /* 1D textures are allocated and used as 2D on GFX9. */
-       if (ctx->screen->b.chip_class >= GFX9) {
+       if (ctx->screen->info.chip_class >= GFX9) {
                LLVMValueRef filler;
 
                /* Use 0.5, so that we don't sample the border color. */
-               if (opcode == TGSI_OPCODE_TXF)
+               if (opcode == TGSI_OPCODE_TXF ||
+                   opcode == TGSI_OPCODE_TXF_LZ)
                        filler = ctx->i32_0;
                else
                        filler = LLVMConstReal(ctx->f32, 0.5);
@@ -1495,85 +1504,13 @@ static void tex_fetch_args(
                count = 16;
        }
 
-       for (chan = 0; chan < count; chan++ ) {
-               address[chan] = LLVMBuildBitCast(gallivm->builder,
-                                                address[chan], ctx->i32, "");
-       }
+       for (chan = 0; chan < count; chan++)
+               address[chan] = ac_to_integer(&ctx->ac, address[chan]);
 
-       /* Adjust the sample index according to FMASK.
-        *
-        * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
-        * which is the identity mapping. Each nibble says which physical sample
-        * should be fetched to get that sample.
-        *
-        * For example, 0x11111100 means there are only 2 samples stored and
-        * the second sample covers 3/4 of the pixel. When reading samples 0
-        * and 1, return physical sample 0 (determined by the first two 0s
-        * in FMASK), otherwise return physical sample 1.
-        *
-        * The sample index should be adjusted as follows:
-        *   sample_index = (fmask >> (sample_index * 4)) & 0xF;
-        */
        if (target == TGSI_TEXTURE_2D_MSAA ||
            target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
-               struct lp_build_emit_data txf_emit_data = *emit_data;
-               LLVMValueRef txf_address[4];
-               /* We only need .xy for non-arrays, and .xyz for arrays. */
-               unsigned txf_count = target == TGSI_TEXTURE_2D_MSAA ? 2 : 3;
-               struct tgsi_full_instruction inst = {};
-
-               memcpy(txf_address, address, sizeof(txf_address));
-
-               /* Read FMASK using TXF_LZ. */
-               inst.Instruction.Opcode = TGSI_OPCODE_TXF_LZ;
-               inst.Texture.Texture = target;
-               txf_emit_data.inst = &inst;
-               txf_emit_data.chan = 0;
-               set_tex_fetch_args(ctx, &txf_emit_data,
-                                  target, fmask_ptr, NULL,
-                                  txf_address, txf_count, 0xf);
-               build_tex_intrinsic(&tex_action, bld_base, &txf_emit_data);
-
-               /* Initialize some constants. */
-               LLVMValueRef four = LLVMConstInt(ctx->i32, 4, 0);
-               LLVMValueRef F = LLVMConstInt(ctx->i32, 0xF, 0);
-
-               /* Apply the formula. */
-               LLVMValueRef fmask =
-                       LLVMBuildExtractElement(gallivm->builder,
-                                               txf_emit_data.output[0],
-                                               ctx->i32_0, "");
-
-               unsigned sample_chan = txf_count; /* the sample index is last */
-
-               LLVMValueRef sample_index4 =
-                       LLVMBuildMul(gallivm->builder, address[sample_chan], four, "");
-
-               LLVMValueRef shifted_fmask =
-                       LLVMBuildLShr(gallivm->builder, fmask, sample_index4, "");
-
-               LLVMValueRef final_sample =
-                       LLVMBuildAnd(gallivm->builder, shifted_fmask, F, "");
-
-               /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
-                * resource descriptor is 0 (invalid),
-                */
-               LLVMValueRef fmask_desc =
-                       LLVMBuildBitCast(gallivm->builder, fmask_ptr,
-                                        ctx->v8i32, "");
-
-               LLVMValueRef fmask_word1 =
-                       LLVMBuildExtractElement(gallivm->builder, fmask_desc,
-                                               ctx->i32_1, "");
-
-               LLVMValueRef word1_is_nonzero =
-                       LLVMBuildICmp(gallivm->builder, LLVMIntNE,
-                                     fmask_word1, ctx->i32_0, "");
-
-               /* Replace the MSAA sample index. */
-               address[sample_chan] =
-                       LLVMBuildSelect(gallivm->builder, word1_is_nonzero,
-                                       final_sample, address[sample_chan], "");
+               ac_apply_fmask_to_sample(&ctx->ac, fmask_ptr, address,
+                                        target == TGSI_TEXTURE_2D_ARRAY_MSAA);
        }
 
        if (opcode == TGSI_OPCODE_TXF ||
@@ -1651,12 +1588,21 @@ static void tex_fetch_args(
  *
  * The workaround is to subtract 0.5 from the unnormalized coordinates,
  * or (0.5 / size) from the normalized coordinates.
+ *
+ * However, cube textures with 8_8_8_8 data formats require a different
+ * workaround of overriding the num format to USCALED/SSCALED. This would lose
+ * precision in 32-bit data formats, so it needs to be applied dynamically at
+ * runtime. In this case, return an i1 value that indicates whether the
+ * descriptor was overridden (and hence a fixup of the sampler result is needed).
  */
-static void si_lower_gather4_integer(struct si_shader_context *ctx,
-                                    struct ac_image_args *args,
-                                    unsigned target)
+static LLVMValueRef
+si_lower_gather4_integer(struct si_shader_context *ctx,
+                        struct ac_image_args *args,
+                        unsigned target,
+                        enum tgsi_return_type return_type)
 {
-       LLVMBuilderRef builder = ctx->gallivm.builder;
+       LLVMBuilderRef builder = ctx->ac.builder;
+       LLVMValueRef wa_8888 = NULL;
        LLVMValueRef coord = args->addr;
        LLVMValueRef half_texel[2];
        /* Texture coordinates start after:
@@ -1666,12 +1612,54 @@ static void si_lower_gather4_integer(struct si_shader_context *ctx,
        unsigned coord_vgpr_index = (int)args->offset + (int)args->compare;
        int c;
 
+       assert(return_type == TGSI_RETURN_TYPE_SINT ||
+              return_type == TGSI_RETURN_TYPE_UINT);
+
+       if (target == TGSI_TEXTURE_CUBE ||
+           target == TGSI_TEXTURE_CUBE_ARRAY) {
+               LLVMValueRef formats;
+               LLVMValueRef data_format;
+               LLVMValueRef wa_formats;
+
+               formats = LLVMBuildExtractElement(builder, args->resource, ctx->i32_1, "");
+
+               data_format = LLVMBuildLShr(builder, formats,
+                                           LLVMConstInt(ctx->i32, 20, false), "");
+               data_format = LLVMBuildAnd(builder, data_format,
+                                          LLVMConstInt(ctx->i32, (1u << 6) - 1, false), "");
+               wa_8888 = LLVMBuildICmp(
+                       builder, LLVMIntEQ, data_format,
+                       LLVMConstInt(ctx->i32, V_008F14_IMG_DATA_FORMAT_8_8_8_8, false),
+                       "");
+
+               uint32_t wa_num_format =
+                       return_type == TGSI_RETURN_TYPE_UINT ?
+                       S_008F14_NUM_FORMAT_GFX6(V_008F14_IMG_NUM_FORMAT_USCALED) :
+                       S_008F14_NUM_FORMAT_GFX6(V_008F14_IMG_NUM_FORMAT_SSCALED);
+               wa_formats = LLVMBuildAnd(builder, formats,
+                                         LLVMConstInt(ctx->i32, C_008F14_NUM_FORMAT_GFX6, false),
+                                         "");
+               wa_formats = LLVMBuildOr(builder, wa_formats,
+                                       LLVMConstInt(ctx->i32, wa_num_format, false), "");
+
+               formats = LLVMBuildSelect(builder, wa_8888, wa_formats, formats, "");
+               args->resource = LLVMBuildInsertElement(
+                       builder, args->resource, formats, ctx->i32_1, "");
+       }
+
        if (target == TGSI_TEXTURE_RECT ||
            target == TGSI_TEXTURE_SHADOWRECT) {
+               assert(!wa_8888);
                half_texel[0] = half_texel[1] = LLVMConstReal(ctx->f32, -0.5);
        } else {
                struct tgsi_full_instruction txq_inst = {};
                struct lp_build_emit_data txq_emit_data = {};
+               struct lp_build_if_state if_ctx;
+
+               if (wa_8888) {
+                       /* Skip the texture size query entirely if we don't need it. */
+                       lp_build_if(&if_ctx, &ctx->gallivm, LLVMBuildNot(builder, wa_8888, ""));
+               }
 
                /* Query the texture size. */
                txq_inst.Texture.Texture = target;
@@ -1694,6 +1682,18 @@ static void si_lower_gather4_integer(struct si_shader_context *ctx,
                        half_texel[c] = LLVMBuildFMul(builder, half_texel[c],
                                                      LLVMConstReal(ctx->f32, -0.5), "");
                }
+
+               if (wa_8888) {
+                       lp_build_endif(&if_ctx);
+
+                       LLVMBasicBlockRef bb[2] = { if_ctx.true_block, if_ctx.entry_block };
+
+                       for (c = 0; c < 2; c++) {
+                               LLVMValueRef values[2] = { half_texel[c], ctx->ac.f32_0 };
+                               half_texel[c] = ac_build_phi(&ctx->ac, ctx->f32, 2,
+                                                            values, bb);
+                       }
+               }
        }
 
        for (c = 0; c < 2; c++) {
@@ -1701,13 +1701,49 @@ static void si_lower_gather4_integer(struct si_shader_context *ctx,
                LLVMValueRef index = LLVMConstInt(ctx->i32, coord_vgpr_index + c, 0);
 
                tmp = LLVMBuildExtractElement(builder, coord, index, "");
-               tmp = LLVMBuildBitCast(builder, tmp, ctx->f32, "");
+               tmp = ac_to_float(&ctx->ac, tmp);
                tmp = LLVMBuildFAdd(builder, tmp, half_texel[c], "");
-               tmp = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
+               tmp = ac_to_integer(&ctx->ac, tmp);
                coord = LLVMBuildInsertElement(builder, coord, tmp, index, "");
        }
 
        args->addr = coord;
+
+       return wa_8888;
+}
+
+/* The second half of the cube texture 8_8_8_8 integer workaround: adjust the
+ * result after the gather operation.
+ */
+static LLVMValueRef
+si_fix_gather4_integer_result(struct si_shader_context *ctx,
+                          LLVMValueRef result,
+                          enum tgsi_return_type return_type,
+                          LLVMValueRef wa)
+{
+       LLVMBuilderRef builder = ctx->ac.builder;
+
+       assert(return_type == TGSI_RETURN_TYPE_SINT ||
+              return_type == TGSI_RETURN_TYPE_UINT);
+
+       for (unsigned chan = 0; chan < 4; ++chan) {
+               LLVMValueRef chanv = LLVMConstInt(ctx->i32, chan, false);
+               LLVMValueRef value;
+               LLVMValueRef wa_value;
+
+               value = LLVMBuildExtractElement(builder, result, chanv, "");
+
+               if (return_type == TGSI_RETURN_TYPE_UINT)
+                       wa_value = LLVMBuildFPToUI(builder, value, ctx->i32, "");
+               else
+                       wa_value = LLVMBuildFPToSI(builder, value, ctx->i32, "");
+               wa_value = ac_to_float(&ctx->ac, wa_value);
+               value = LLVMBuildSelect(builder, wa, wa_value, value, "");
+
+               result = LLVMBuildInsertElement(builder, result, value, chanv, "");
+       }
+
+       return result;
 }
 
 static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
@@ -1721,12 +1757,16 @@ static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
        unsigned target = inst->Texture.Texture;
 
        if (target == TGSI_TEXTURE_BUFFER) {
-               emit_data->output[emit_data->chan] =
+               unsigned num_channels =
+                       util_last_bit(inst->Dst[0].Register.WriteMask);
+               LLVMValueRef result =
                        ac_build_buffer_load_format(&ctx->ac,
                                                    emit_data->args[0],
                                                    emit_data->args[2],
                                                    emit_data->args[1],
-                                                   true);
+                                                   num_channels, false, true);
+               emit_data->output[emit_data->chan] =
+                       ac_build_expand_to_vec4(&ctx->ac, result, num_channels);
                return;
        }
 
@@ -1782,20 +1822,30 @@ static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
        }
 
        /* The hardware needs special lowering for Gather4 with integer formats. */
-       if (ctx->screen->b.chip_class <= VI &&
-           opcode == TGSI_OPCODE_TG4) {
-               const unsigned src_idx = 2;
+       LLVMValueRef gather4_int_result_workaround = NULL;
 
-               assert(inst->Src[src_idx].Register.File == TGSI_FILE_SAMPLER);
+       if (ctx->screen->info.chip_class <= VI &&
+           opcode == TGSI_OPCODE_TG4) {
                assert(inst->Texture.ReturnType != TGSI_RETURN_TYPE_UNKNOWN);
 
                if (inst->Texture.ReturnType == TGSI_RETURN_TYPE_SINT ||
-                   inst->Texture.ReturnType == TGSI_RETURN_TYPE_UINT)
-                       si_lower_gather4_integer(ctx, &args, target);
+                   inst->Texture.ReturnType == TGSI_RETURN_TYPE_UINT) {
+                       gather4_int_result_workaround =
+                               si_lower_gather4_integer(ctx, &args, target,
+                                                        inst->Texture.ReturnType);
+               }
        }
 
-       emit_data->output[emit_data->chan] =
+       LLVMValueRef result =
                ac_build_image_opcode(&ctx->ac, &args);
+
+       if (gather4_int_result_workaround) {
+               result = si_fix_gather4_integer_result(ctx, result,
+                                                      inst->Texture.ReturnType,
+                                                      gather4_int_result_workaround);
+       }
+
+       emit_data->output[emit_data->chan] = result;
 }
 
 static void si_llvm_emit_txqs(
@@ -1804,8 +1854,6 @@ static void si_llvm_emit_txqs(
        struct lp_build_emit_data *emit_data)
 {
        struct si_shader_context *ctx = si_shader_context(bld_base);
-       struct gallivm_state *gallivm = &ctx->gallivm;
-       LLVMBuilderRef builder = gallivm->builder;
        LLVMValueRef res, samples;
        LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL;
 
@@ -1813,20 +1861,76 @@ static void si_llvm_emit_txqs(
 
 
        /* Read the samples from the descriptor directly. */
-       res = LLVMBuildBitCast(builder, res_ptr, ctx->v8i32, "");
-       samples = LLVMBuildExtractElement(
-               builder, res,
-               LLVMConstInt(ctx->i32, 3, 0), "");
-       samples = LLVMBuildLShr(builder, samples,
+       res = LLVMBuildBitCast(ctx->ac.builder, res_ptr, ctx->v8i32, "");
+       samples = LLVMBuildExtractElement(ctx->ac.builder, res,
+                                         LLVMConstInt(ctx->i32, 3, 0), "");
+       samples = LLVMBuildLShr(ctx->ac.builder, samples,
                                LLVMConstInt(ctx->i32, 16, 0), "");
-       samples = LLVMBuildAnd(builder, samples,
+       samples = LLVMBuildAnd(ctx->ac.builder, samples,
                               LLVMConstInt(ctx->i32, 0xf, 0), "");
-       samples = LLVMBuildShl(builder, ctx->i32_1,
+       samples = LLVMBuildShl(ctx->ac.builder, ctx->i32_1,
                               samples, "");
 
        emit_data->output[emit_data->chan] = samples;
 }
 
+static void si_llvm_emit_fbfetch(const struct lp_build_tgsi_action *action,
+                                struct lp_build_tgsi_context *bld_base,
+                                struct lp_build_emit_data *emit_data)
+{
+       struct si_shader_context *ctx = si_shader_context(bld_base);
+       struct ac_image_args args = {};
+       LLVMValueRef ptr, image, fmask, addr_vec;
+
+       /* Ignore src0, because KHR_blend_func_extended disallows multiple render
+        * targets.
+        */
+
+       /* Load the image descriptor. */
+       STATIC_ASSERT(SI_PS_IMAGE_COLORBUF0 % 2 == 0);
+       ptr = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
+       ptr = LLVMBuildPointerCast(ctx->ac.builder, ptr,
+                                  ac_array_in_const32_addr_space(ctx->v8i32), "");
+       image = ac_build_load_to_sgpr(&ctx->ac, ptr,
+                       LLVMConstInt(ctx->i32, SI_PS_IMAGE_COLORBUF0 / 2, 0));
+
+       LLVMValueRef addr[4];
+       unsigned chan = 0;
+
+       addr[chan++] = si_unpack_param(ctx, SI_PARAM_POS_FIXED_PT, 0, 16);
+
+       if (!ctx->shader->key.mono.u.ps.fbfetch_is_1D)
+               addr[chan++] = si_unpack_param(ctx, SI_PARAM_POS_FIXED_PT, 16, 16);
+
+       /* Get the current render target layer index. */
+       if (ctx->shader->key.mono.u.ps.fbfetch_layered)
+               addr[chan++] = si_unpack_param(ctx, SI_PARAM_ANCILLARY, 16, 11);
+
+       if (ctx->shader->key.mono.u.ps.fbfetch_msaa)
+               addr[chan++] = si_get_sample_id(ctx);
+
+       while (chan < 4)
+               addr[chan++] = LLVMGetUndef(ctx->i32);
+
+       if (ctx->shader->key.mono.u.ps.fbfetch_msaa) {
+               fmask = ac_build_load_to_sgpr(&ctx->ac, ptr,
+                       LLVMConstInt(ctx->i32, SI_PS_IMAGE_COLORBUF0_FMASK / 2, 0));
+
+               ac_apply_fmask_to_sample(&ctx->ac, fmask, addr, false);
+       }
+
+       addr_vec = ac_build_gather_values(&ctx->ac, addr, ARRAY_SIZE(addr));
+
+       args.opcode = ac_image_load;
+       args.resource = image;
+       args.addr = addr_vec;
+       args.dmask = 0xf;
+       args.da = ctx->shader->key.mono.u.ps.fbfetch_layered;
+
+       emit_data->output[emit_data->chan] =
+               ac_build_image_opcode(&ctx->ac, &args);
+}
+
 static const struct lp_build_tgsi_action tex_action = {
        .fetch_args = tex_fetch_args,
        .emit = build_tex_intrinsic,
@@ -1859,6 +1963,8 @@ void si_shader_context_init_mem(struct si_shader_context *ctx)
        bld_base->op_actions[TGSI_OPCODE_LODQ] = tex_action;
        bld_base->op_actions[TGSI_OPCODE_TXQS].emit = si_llvm_emit_txqs;
 
+       bld_base->op_actions[TGSI_OPCODE_FBFETCH].emit = si_llvm_emit_fbfetch;
+
        bld_base->op_actions[TGSI_OPCODE_LOAD].fetch_args = load_fetch_args;
        bld_base->op_actions[TGSI_OPCODE_LOAD].emit = load_emit;
        bld_base->op_actions[TGSI_OPCODE_STORE].fetch_args = store_fetch_args;