1/*
2 * Copyright © 2019 Google LLC
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24#include "tu_private.h"
25
26#include "spirv/nir_spirv.h"
27#include "util/mesa-sha1.h"
28
29#include "ir3/ir3_nir.h"
30
31static nir_function *
32tu_spirv_to_nir(struct ir3_compiler *compiler,
33                const uint32_t *words,
34                size_t word_count,
35                gl_shader_stage stage,
36                const char *entry_point_name,
37                const VkSpecializationInfo *spec_info)
38{
39   /* TODO these are made-up */
40   const struct spirv_to_nir_options spirv_options = {
41      .lower_workgroup_access_to_offsets = true,
42      .lower_ubo_ssbo_access_to_offsets = true,
43      .caps = { false },
44   };
45   const nir_shader_compiler_options *nir_options =
46      ir3_get_compiler_options(compiler);
47
48   /* convert VkSpecializationInfo */
49   struct nir_spirv_specialization *spec = NULL;
50   uint32_t num_spec = 0;
51   if (spec_info && spec_info->mapEntryCount) {
52      spec = malloc(sizeof(*spec) * spec_info->mapEntryCount);
53      if (!spec)
54         return NULL;
55
56      for (uint32_t i = 0; i < spec_info->mapEntryCount; i++) {
57         const VkSpecializationMapEntry *entry = &spec_info->pMapEntries[i];
58         const void *data = spec_info->pData + entry->offset;
59         assert(data + entry->size <= spec_info->pData + spec_info->dataSize);
60         spec[i].id = entry->constantID;
61         if (entry->size == 8)
62            spec[i].data64 = *(const uint64_t *) data;
63         else
64            spec[i].data32 = *(const uint32_t *) data;
65         spec[i].defined_on_module = false;
66      }
67
68      num_spec = spec_info->mapEntryCount;
69   }
70
71   nir_function *entry_point =
72      spirv_to_nir(words, word_count, spec, num_spec, stage, entry_point_name,
73                   &spirv_options, nir_options);
74
75   free(spec);
76
77   assert(entry_point->shader->info.stage == stage);
78   nir_validate_shader(entry_point->shader, "after spirv_to_nir");
79
80   return entry_point;
81}
82
83static void
84tu_sort_variables_by_location(struct exec_list *variables)
85{
86   struct exec_list sorted;
87   exec_list_make_empty(&sorted);
88
89   nir_foreach_variable_safe(var, variables)
90   {
91      exec_node_remove(&var->node);
92
93      /* insert the variable into the sorted list */
94      nir_variable *next = NULL;
95      nir_foreach_variable(tmp, &sorted)
96      {
97         if (var->data.location < tmp->data.location) {
98            next = tmp;
99            break;
100         }
101      }
102      if (next)
103         exec_node_insert_node_before(&next->node, &var->node);
104      else
105         exec_list_push_tail(&sorted, &var->node);
106   }
107
108   exec_list_move_nodes_to(&sorted, variables);
109}
110
111struct tu_shader *
112tu_shader_create(struct tu_device *dev,
113                 gl_shader_stage stage,
114                 const VkPipelineShaderStageCreateInfo *stage_info,
115                 const VkAllocationCallbacks *alloc)
116{
117   const struct tu_shader_module *module =
118      tu_shader_module_from_handle(stage_info->module);
119   struct tu_shader *shader;
120
121   const uint32_t max_variant_count = (stage == MESA_SHADER_VERTEX) ? 2 : 1;
122   shader = vk_zalloc2(
123      &dev->alloc, alloc,
124      sizeof(*shader) + sizeof(struct ir3_shader_variant) * max_variant_count,
125      8, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
126   if (!shader)
127      return NULL;
128
129   /* translate SPIR-V to NIR */
130   assert(module->code_size % 4 == 0);
131   nir_function *entry_point = tu_spirv_to_nir(
132      dev->compiler, (const uint32_t *) module->code, module->code_size / 4,
133      stage, stage_info->pName, stage_info->pSpecializationInfo);
134   if (!entry_point) {
135      vk_free2(&dev->alloc, alloc, shader);
136      return NULL;
137   }
138
139   nir_shader *nir = entry_point->shader;
140
141   if (unlikely(dev->physical_device->instance->debug_flags & TU_DEBUG_NIR)) {
142      fprintf(stderr, "translated nir:\n");
143      nir_print_shader(nir, stderr);
144   }
145
146   /* TODO what needs to happen? */
147
148   switch (stage) {
149   case MESA_SHADER_VERTEX:
150      tu_sort_variables_by_location(&nir->outputs);
151      break;
152   case MESA_SHADER_TESS_CTRL:
153   case MESA_SHADER_TESS_EVAL:
154   case MESA_SHADER_GEOMETRY:
155      tu_sort_variables_by_location(&nir->inputs);
156      tu_sort_variables_by_location(&nir->outputs);
157      break;
158   case MESA_SHADER_FRAGMENT:
159      tu_sort_variables_by_location(&nir->inputs);
160      break;
161   case MESA_SHADER_COMPUTE:
162      break;
163   default:
164      unreachable("invalid gl_shader_stage");
165      break;
166   }
167
168   nir_assign_var_locations(&nir->inputs, &nir->num_inputs,
169                            ir3_glsl_type_size);
170   nir_assign_var_locations(&nir->outputs, &nir->num_outputs,
171                            ir3_glsl_type_size);
172   nir_assign_var_locations(&nir->uniforms, &nir->num_uniforms,
173                            ir3_glsl_type_size);
174
175   NIR_PASS_V(nir, nir_lower_system_values);
176   NIR_PASS_V(nir, nir_lower_frexp);
177   NIR_PASS_V(nir, nir_lower_io, nir_var_all, ir3_glsl_type_size, 0);
178
179   nir_shader_gather_info(nir, entry_point->impl);
180
181   shader->ir3_shader.compiler = dev->compiler;
182   shader->ir3_shader.type = stage;
183   shader->ir3_shader.nir = nir;
184
185   return shader;
186}
187
188void
189tu_shader_destroy(struct tu_device *dev,
190                  struct tu_shader *shader,
191                  const VkAllocationCallbacks *alloc)
192{
193   if (shader->ir3_shader.nir)
194      ralloc_free(shader->ir3_shader.nir);
195
196   for (uint32_t i = 0; i < 1 + shader->has_binning_pass; i++) {
197      if (shader->variants[i].ir)
198         ir3_destroy(shader->variants[i].ir);
199      if (shader->variants[i].immediates)
200         free(shader->variants[i].immediates);
201   }
202
203   if (shader->binary)
204      free(shader->binary);
205   if (shader->binning_binary)
206      free(shader->binning_binary);
207
208   vk_free2(&dev->alloc, alloc, shader);
209}
210
211void
212tu_shader_compile_options_init(
213   struct tu_shader_compile_options *options,
214   const VkGraphicsPipelineCreateInfo *pipeline_info)
215{
216   *options = (struct tu_shader_compile_options) {
217      /* TODO ir3_key */
218
219      .optimize = !(pipeline_info->flags &
220                    VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT),
221      .include_binning_pass = true,
222   };
223}
224
225static uint32_t *
226tu_compile_shader_variant(struct ir3_shader *shader,
227                          const struct ir3_shader_key *key,
228                          bool binning_pass,
229                          struct ir3_shader_variant *variant)
230{
231   variant->shader = shader;
232   variant->type = shader->type;
233   variant->key = *key;
234   variant->binning_pass = binning_pass;
235
236   int ret = ir3_compile_shader_nir(shader->compiler, variant);
237   if (ret)
238      return NULL;
239
240   /* when assemble fails, we rely on tu_shader_destroy to clean up the
241    * variant
242    */
243   return ir3_shader_assemble(variant, shader->compiler->gpu_id);
244}
245
246VkResult
247tu_shader_compile(struct tu_device *dev,
248                  struct tu_shader *shader,
249                  const struct tu_shader *next_stage,
250                  const struct tu_shader_compile_options *options,
251                  const VkAllocationCallbacks *alloc)
252{
253   if (options->optimize) {
254      /* ignore the key for the first pass of optimization */
255      ir3_optimize_nir(&shader->ir3_shader, shader->ir3_shader.nir, NULL);
256
257      if (unlikely(dev->physical_device->instance->debug_flags &
258                   TU_DEBUG_NIR)) {
259         fprintf(stderr, "optimized nir:\n");
260         nir_print_shader(shader->ir3_shader.nir, stderr);
261      }
262   }
263
264   shader->binary = tu_compile_shader_variant(
265      &shader->ir3_shader, &options->key, false, &shader->variants[0]);
266   if (!shader->binary)
267      return VK_ERROR_OUT_OF_HOST_MEMORY;
268
269   /* compile another variant for the binning pass */
270   if (options->include_binning_pass &&
271       shader->ir3_shader.type == MESA_SHADER_VERTEX) {
272      shader->binning_binary = tu_compile_shader_variant(
273         &shader->ir3_shader, &options->key, true, &shader->variants[1]);
274      if (!shader->binning_binary)
275         return VK_ERROR_OUT_OF_HOST_MEMORY;
276
277      shader->has_binning_pass = true;
278   }
279
280   if (unlikely(dev->physical_device->instance->debug_flags & TU_DEBUG_IR3)) {
281      fprintf(stderr, "disassembled ir3:\n");
282      fprintf(stderr, "shader: %s\n",
283              gl_shader_stage_name(shader->ir3_shader.type));
284      ir3_shader_disasm(&shader->variants[0], shader->binary, stderr);
285
286      if (shader->has_binning_pass) {
287         fprintf(stderr, "disassembled ir3:\n");
288         fprintf(stderr, "shader: %s (binning)\n",
289                 gl_shader_stage_name(shader->ir3_shader.type));
290         ir3_shader_disasm(&shader->variants[1], shader->binning_binary,
291                           stderr);
292      }
293   }
294
295   return VK_SUCCESS;
296}
297
298VkResult
299tu_CreateShaderModule(VkDevice _device,
300                      const VkShaderModuleCreateInfo *pCreateInfo,
301                      const VkAllocationCallbacks *pAllocator,
302                      VkShaderModule *pShaderModule)
303{
304   TU_FROM_HANDLE(tu_device, device, _device);
305   struct tu_shader_module *module;
306
307   assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
308   assert(pCreateInfo->flags == 0);
309   assert(pCreateInfo->codeSize % 4 == 0);
310
311   module = vk_alloc2(&device->alloc, pAllocator,
312                      sizeof(*module) + pCreateInfo->codeSize, 8,
313                      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
314   if (module == NULL)
315      return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
316
317   module->code_size = pCreateInfo->codeSize;
318   memcpy(module->code, pCreateInfo->pCode, pCreateInfo->codeSize);
319
320   _mesa_sha1_compute(module->code, module->code_size, module->sha1);
321
322   *pShaderModule = tu_shader_module_to_handle(module);
323
324   return VK_SUCCESS;
325}
326
327void
328tu_DestroyShaderModule(VkDevice _device,
329                       VkShaderModule _module,
330                       const VkAllocationCallbacks *pAllocator)
331{
332   TU_FROM_HANDLE(tu_device, device, _device);
333   TU_FROM_HANDLE(tu_shader_module, module, _module);
334
335   if (!module)
336      return;
337
338   vk_free2(&device->alloc, pAllocator, module);
339}
340