/*
 * Copyright © 2017 Intel Corporation
 * SPDX-License-Identifier: MIT
 *
 * @file iris_program_cache.c
 *
 * The in-memory program cache.  This is basically a hash table mapping
 * API-specified shaders and a state key to a compiled variant.  It also
 * takes care of uploading shader assembly into a BO for use on the GPU.
 */

#include <stdio.h>
#include <errno.h>
#include "pipe/p_defines.h"
#include "pipe/p_state.h"
#include "pipe/p_context.h"
#include "pipe/p_screen.h"
#include "util/u_atomic.h"
#include "util/u_upload_mgr.h"
#include "compiler/nir/nir.h"
#include "compiler/nir/nir_builder.h"
#include "intel/compiler/brw/brw_compiler.h"
#include "intel/compiler/brw/brw_disasm.h"
#include "intel/compiler/brw/brw_nir.h"
#ifdef INTEL_USE_ELK
#include "intel/compiler/elk/elk_compiler.h"
#include "intel/compiler/elk/elk_nir.h"
#endif
#include "iris_context.h"
#include "iris_resource.h"

struct keybox {
   uint16_t size;
   enum iris_program_cache_id cache_id;
   uint8_t data[0];
};

static struct keybox *
make_keybox(void *mem_ctx,
            enum iris_program_cache_id cache_id,
            const void *key,
            uint32_t key_size)
{
   struct keybox *keybox =
      ralloc_size(mem_ctx, sizeof(struct keybox) + key_size);

   keybox->cache_id = cache_id;
   keybox->size = key_size;
   memcpy(keybox->data, key, key_size);

   return keybox;
}

static uint32_t
keybox_hash(const void *void_key)
{
   const struct keybox *key = void_key;
   return _mesa_hash_data(&key->cache_id, key->size + sizeof(key->cache_id));
}

static bool
keybox_equals(const void *void_a, const void *void_b)
{
   const struct keybox *a = void_a, *b = void_b;
   if (a->size != b->size)
      return false;

   return memcmp(a->data, b->data, a->size) == 0;
}

struct iris_compiled_shader *
iris_find_cached_shader(struct iris_context *ice,
                        enum iris_program_cache_id cache_id,
                        uint32_t key_size,
                        const void *key)
{
   struct keybox *keybox = make_keybox(NULL, cache_id, key, key_size);
   struct hash_entry *entry =
      _mesa_hash_table_search(ice->shaders.cache, keybox);

   ralloc_free(keybox);

   return entry ? entry->data : NULL;
}

void
iris_delete_shader_variant(struct iris_compiled_shader *shader)
{
   pipe_resource_reference(&shader->assembly.res, NULL);
   util_queue_fence_destroy(&shader->ready);
   ralloc_free(shader);
}

struct iris_compiled_shader *
iris_create_shader_variant(const struct iris_screen *screen,
                           void *mem_ctx,
                           mesa_shader_stage stage,
                           enum iris_program_cache_id cache_id,
                           uint32_t key_size,
                           const void *key)
{
#ifndef NDEBUG
   if (cache_id == IRIS_CACHE_BLORP) {
      /* Blorp shader must have a mem_ctx. */
      assert(mem_ctx != NULL);
   } else if (cache_id == IRIS_CACHE_TCS) {
      /* Pass-through tessellation control shaders (generated by the driver)
       * will have a mem_ctx, and other tessellation control shaders will not.
       */
   } else {
      /* Shaders that are neither blorp nor tessellation control must not have
       * a mem_ctx.
       */
      assert(mem_ctx == NULL);
   }
#endif

   struct iris_compiled_shader *shader =
      rzalloc_size(mem_ctx, sizeof(struct iris_compiled_shader) +
                   screen->vtbl.derived_program_state_size(cache_id));

   pipe_reference_init(&shader->ref, 1);
   util_queue_fence_init(&shader->ready);
   util_queue_fence_reset(&shader->ready);

   if (cache_id != IRIS_CACHE_BLORP) {
      assert(key_size <= sizeof(union iris_any_prog_key));
      memcpy(&shader->key, key, key_size);
   }

   shader->stage = stage;

   return shader;
}

void
iris_upload_shader(struct iris_screen *screen,
                   struct iris_uncompiled_shader *ish,
                   struct iris_compiled_shader *shader,
                   struct hash_table *driver_shaders,
                   struct u_upload_mgr *uploader,
                   enum iris_program_cache_id cache_id,
                   uint32_t key_size,
                   const void *key,
                   const void *assembly)
{
   u_upload_alloc_ref(uploader, 0, shader->program_size, 64,
                  &shader->assembly.offset, &shader->assembly.res,
                  &shader->map);
   memcpy(shader->map, assembly, shader->program_size);

   struct iris_resource *res = (void *) shader->assembly.res;
   uint64_t shader_data_addr = res->bo->address +
                               shader->assembly.offset +
                               shader->const_data_offset;

   struct intel_shader_reloc_value reloc_values[] = {
      {
         .id = INTEL_SHADER_RELOC_CONST_DATA_ADDR_LOW,
         .value = shader_data_addr,
      },
      {
         .id = INTEL_SHADER_RELOC_CONST_DATA_ADDR_HIGH,
         .value = shader_data_addr >> 32,
      },
   };
   if (screen->brw) {
      brw_write_shader_relocs(&screen->brw->isa, shader->map,
                              shader->brw_prog_data, reloc_values,
                              ARRAY_SIZE(reloc_values));
   } else {
#ifdef INTEL_USE_ELK
      elk_write_shader_relocs(&screen->elk->isa, shader->map,
                              shader->elk_prog_data, reloc_values,
                              ARRAY_SIZE(reloc_values));
#else
      UNREACHABLE("no elk support");
#endif
   }

   /* Store the 3DSTATE shader packets and other derived state. */
   screen->vtbl.store_derived_program_state(screen, cache_id, shader);

   util_queue_fence_signal(&shader->ready);

   if (!ish) {
      struct keybox *keybox = make_keybox(shader, cache_id, key, key_size);
      _mesa_hash_table_insert(driver_shaders, keybox, shader);
   }

   if (INTEL_DEBUG(DEBUG_SHADERS_LINENO) && screen->brw) {
      if (!intel_shader_dump_filter ||
          (intel_shader_dump_filter && ish && intel_shader_dump_filter == ish->source_hash)) {
         int start = 0;
         /* dump each simd variant of shader */
         while (start < shader->brw_prog_data->program_size) {
            brw_disassemble_with_lineno(&screen->brw->isa, shader->stage, -1,
                                        ish ? ish->source_hash : 0, assembly, start,
                                        res->bo->address + shader->assembly.offset,
                                        stderr);
            start += align64(brw_disassemble_find_end(&screen->brw->isa,
                                                      assembly, start), 64);
         }
      }
   }
}

bool
iris_blorp_lookup_shader(struct blorp_batch *blorp_batch,
                         const void *key, uint32_t key_size,
                         uint32_t *kernel_out, void *prog_data_out)
{
   struct blorp_context *blorp = blorp_batch->blorp;
   struct iris_context *ice = blorp->driver_ctx;
   struct iris_batch *batch = blorp_batch->driver_batch;
   struct iris_compiled_shader *shader =
      iris_find_cached_shader(ice, IRIS_CACHE_BLORP, key_size, key);

   if (!shader)
      return false;

   struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
   *kernel_out =
      iris_bo_offset_from_base_address(bo) + shader->assembly.offset;
   *((void **) prog_data_out) =
#ifdef INTEL_USE_ELK
      batch->screen->elk ? (void *)shader->elk_prog_data :
#endif
      (void *)shader->brw_prog_data;

   iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);

   return true;
}

bool
iris_blorp_upload_shader(struct blorp_batch *blorp_batch, uint32_t stage,
                         const void *key, uint32_t key_size,
                         const void *kernel, UNUSED uint32_t kernel_size,
                         const void *prog_data_templ,
                         UNUSED uint32_t prog_data_size,
                         uint32_t *kernel_out, void *prog_data_out)
{
   struct blorp_context *blorp = blorp_batch->blorp;
   struct iris_context *ice = blorp->driver_ctx;
   struct iris_batch *batch = blorp_batch->driver_batch;
   struct iris_screen *screen = batch->screen;

   struct iris_binding_table bt;
   memset(&bt, 0, sizeof(bt));

   struct iris_compiled_shader *shader =
      iris_create_shader_variant(screen, ice->shaders.cache, stage,
                                 IRIS_CACHE_BLORP, key_size, key);

   void *prog_data = ralloc_size(NULL, prog_data_size);
   memcpy(prog_data, prog_data_templ, prog_data_size);

   if (screen->brw) {
      iris_apply_brw_prog_data(shader, prog_data, NULL);
   } else {
#ifdef INTEL_USE_ELK
      assert(screen->elk);
      iris_apply_elk_prog_data(shader, prog_data);
#else
      UNREACHABLE("no elk support");
#endif
   }

   iris_finalize_program(shader, NULL, NULL, 0, 0, &bt);

   iris_upload_shader(screen, NULL, shader, ice->shaders.cache,
                      ice->shaders.uploader_driver,
                      IRIS_CACHE_BLORP, key_size, key, kernel);

   struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
   *kernel_out =
      iris_bo_offset_from_base_address(bo) + shader->assembly.offset;
   *((void **) prog_data_out) =
#ifdef INTEL_USE_ELK
      screen->elk ? (void *)shader->elk_prog_data :
#endif
      (void*)shader->brw_prog_data;

   iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);

   return true;
}

void
iris_init_program_cache(struct iris_context *ice)
{
   ice->shaders.cache =
      _mesa_hash_table_create(ice, keybox_hash, keybox_equals);

   ice->shaders.uploader_driver =
      u_upload_create(&ice->ctx, 64 * 1024,
                      PIPE_BIND_CUSTOM, PIPE_USAGE_IMMUTABLE,
                      IRIS_RESOURCE_FLAG_SHADER_MEMZONE |
                      IRIS_RESOURCE_FLAG_DEVICE_MEM);
   ice->shaders.uploader_unsync =
      u_upload_create(&ice->ctx, 64 * 1024,
                      PIPE_BIND_CUSTOM, PIPE_USAGE_IMMUTABLE,
                      IRIS_RESOURCE_FLAG_SHADER_MEMZONE |
                      IRIS_RESOURCE_FLAG_DEVICE_MEM);
}

void
iris_destroy_program_cache(struct iris_context *ice)
{
   for (int i = 0; i < MESA_SHADER_STAGES; i++) {
      iris_shader_variant_reference(&ice->shaders.prog[i], NULL);
   }
   iris_shader_variant_reference(&ice->shaders.last_vue_shader, NULL);

   hash_table_foreach(ice->shaders.cache, entry) {
      struct iris_compiled_shader *shader = entry->data;
      iris_delete_shader_variant(shader);
   }

   u_upload_destroy(ice->shaders.uploader_driver);
   u_upload_destroy(ice->shaders.uploader_unsync);

   ralloc_free(ice->shaders.cache);
}

void
iris_ensure_indirect_generation_shader(struct iris_batch *batch)
{
   struct iris_context *ice = batch->ice;
   if (ice->draw.generation.shader)
      return;

   struct iris_screen *screen = (struct iris_screen *)ice->ctx.screen;
   const struct {
      char name[40];
   } key = {
      .name = "iris-generation-shader",
   };
   ice->draw.generation.shader =
      iris_find_cached_shader(ice, IRIS_CACHE_BLORP, sizeof(key), &key);
   if (ice->draw.generation.shader != NULL)
      return;

   const nir_shader_compiler_options *nir_options =
#ifdef INTEL_USE_ELK
      screen->elk ? screen->elk->nir_options[MESA_SHADER_COMPUTE] :
#endif
      &screen->brw->nir_options[MESA_SHADER_COMPUTE];

   nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_FRAGMENT,
                                                  nir_options,
                                                  "iris-indirect-generate");

   uint32_t uniform_size =
      screen->vtbl.call_generation_shader(screen, &b);
   uniform_size = align(uniform_size, REG_SIZE);

   nir_shader *nir = b.shader;

   NIR_PASS(_, nir, nir_lower_vars_to_ssa);
   NIR_PASS(_, nir, nir_opt_cse);
   NIR_PASS(_, nir, nir_opt_gcm, true);

   nir_opt_peephole_select_options peephole_select_options = {
      .limit = 1,
   };
   NIR_PASS(_, nir, nir_opt_peephole_select, &peephole_select_options);

   NIR_PASS(_, nir, nir_lower_variable_initializers, ~0);

   NIR_PASS(_, nir, nir_split_var_copies);
   NIR_PASS(_, nir, nir_split_per_member_structs);

   if (screen->brw) {
      struct brw_nir_compiler_opts opts = {};
      brw_preprocess_nir(screen->brw, nir, &opts);
   } else {
#ifdef INTEL_USE_ELK
      assert(screen->elk);
      struct elk_nir_compiler_opts opts = {};
      elk_preprocess_nir(screen->elk, nir, &opts);
#else
      UNREACHABLE("no elk support");
#endif
   }

   NIR_PASS(_, nir, nir_propagate_invariant, false);

   NIR_PASS(_, nir, nir_lower_input_attachments,
              &(nir_input_attachment_options) { });

   /* Reset sizes before gathering information */
   nir->global_mem_size = 0;
   nir->scratch_size = 0;
   nir->info.shared_size = 0;
   nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));

   NIR_PASS(_, nir, nir_opt_copy_prop);
   NIR_PASS(_, nir, nir_opt_constant_folding);
   NIR_PASS(_, nir, nir_opt_dce);

   /* Do vectorizing here. For some reason when trying to do it in the back
    * this just isn't working.
    */
   struct brw_nir_vectorize_mem_cb_data cb_data = {
      .devinfo = screen->devinfo,
   };
   nir_load_store_vectorize_options options = {
      .modes = nir_var_mem_ubo | nir_var_mem_ssbo | nir_var_mem_global,
      .callback = brw_nir_should_vectorize_mem,
      .cb_data = &cb_data,
      .robust_modes = (nir_variable_mode)0,
   };
   NIR_PASS(_, nir, nir_opt_load_store_vectorize, &options);

   nir->num_uniforms = uniform_size;

   struct iris_compiled_shader *shader =
      iris_create_shader_variant(screen, ice->shaders.cache,
                                 MESA_SHADER_FRAGMENT,
                                 IRIS_CACHE_BLORP,
                                 sizeof(key), &key);

   const unsigned *program;
   if (screen->brw) {
      union brw_any_prog_key prog_key;
      memset(&prog_key, 0, sizeof(prog_key));

      struct brw_fs_prog_data *prog_data = ralloc_size(NULL, sizeof(*prog_data));
      memset(prog_data, 0, sizeof(*prog_data));
      prog_data->base.push_sizes[0] = uniform_size;

      struct genisa_stats stats[3];
      struct brw_compile_fs_params params = {
         .base = {
            .nir = nir,
            .log_data = &ice->dbg,
            .debug_flag = DEBUG_WM,
            .stats = stats,
            .mem_ctx = nir,
         },
         .key = &prog_key.fs,
         .prog_data = prog_data,
      };
      program = brw_compile_fs(screen->brw, &params);
      assert(program);
      iris_apply_brw_prog_data(shader, &prog_data->base, NULL);
   } else {
#ifdef INTEL_USE_ELK
      union elk_any_prog_key prog_key;
      memset(&prog_key, 0, sizeof(prog_key));

      struct elk_fs_prog_data *prog_data = ralloc_size(NULL, sizeof(*prog_data));
      memset(prog_data, 0, sizeof(*prog_data));
      prog_data->base.nr_params = nir->num_uniforms / 4;

      elk_nir_analyze_ubo_ranges(screen->elk, nir, prog_data->base.ubo_ranges);

      struct elk_compile_stats stats[3];
      struct elk_compile_fs_params params = {
         .base = {
            .nir = nir,
            .log_data = &ice->dbg,
            .debug_flag = DEBUG_WM,
            .stats = stats,
            .mem_ctx = nir,
         },
         .key = &prog_key.fs,
         .prog_data = prog_data,
      };
      program = elk_compile_fs(screen->elk, &params);
      assert(program);
      iris_apply_elk_prog_data(shader, &prog_data->base);
#else
      UNREACHABLE("no elk support");
#endif
   }

   struct iris_binding_table bt;
   memset(&bt, 0, sizeof(bt));

   iris_finalize_program(shader, NULL, NULL, 0, 0, &bt);

   iris_upload_shader(screen, NULL, shader, ice->shaders.cache,
                      ice->shaders.uploader_driver,
                      IRIS_CACHE_BLORP, sizeof(key), &key, program);

   ralloc_free(nir);

   struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
   iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);

   ice->draw.generation.shader = shader;
}
