OSDN Git Service

d99862ad5ba843eef7cdb08b51731a17e59eda15
[android-x86/external-mesa.git] / src / gallium / drivers / vc4 / vc4_program.c
1 /*
2  * Copyright (c) 2014 Scott Mansell
3  * Copyright © 2014 Broadcom
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24
25 #include <inttypes.h>
26 #include "util/u_format.h"
27 #include "util/u_hash.h"
28 #include "util/u_math.h"
29 #include "util/u_memory.h"
30 #include "util/ralloc.h"
31 #include "util/hash_table.h"
32 #include "tgsi/tgsi_dump.h"
33 #include "tgsi/tgsi_parse.h"
34 #include "compiler/nir/nir.h"
35 #include "compiler/nir/nir_builder.h"
36 #include "nir/tgsi_to_nir.h"
37 #include "vc4_context.h"
38 #include "vc4_qpu.h"
39 #include "vc4_qir.h"
40 #ifdef USE_VC4_SIMULATOR
41 #include "simpenrose/simpenrose.h"
42 #endif
43
44 static struct qreg
45 ntq_get_src(struct vc4_compile *c, nir_src src, int i);
46
47 static void
48 resize_qreg_array(struct vc4_compile *c,
49                   struct qreg **regs,
50                   uint32_t *size,
51                   uint32_t decl_size)
52 {
53         if (*size >= decl_size)
54                 return;
55
56         uint32_t old_size = *size;
57         *size = MAX2(*size * 2, decl_size);
58         *regs = reralloc(c, *regs, struct qreg, *size);
59         if (!*regs) {
60                 fprintf(stderr, "Malloc failure\n");
61                 abort();
62         }
63
64         for (uint32_t i = old_size; i < *size; i++)
65                 (*regs)[i] = c->undef;
66 }
67
68 static struct qreg
69 indirect_uniform_load(struct vc4_compile *c, nir_intrinsic_instr *intr)
70 {
71         struct qreg indirect_offset = ntq_get_src(c, intr->src[0], 0);
72         uint32_t offset = intr->const_index[0];
73         struct vc4_compiler_ubo_range *range = NULL;
74         unsigned i;
75         for (i = 0; i < c->num_uniform_ranges; i++) {
76                 range = &c->ubo_ranges[i];
77                 if (offset >= range->src_offset &&
78                     offset < range->src_offset + range->size) {
79                         break;
80                 }
81         }
82         /* The driver-location-based offset always has to be within a declared
83          * uniform range.
84          */
85         assert(range);
86         if (!range->used) {
87                 range->used = true;
88                 range->dst_offset = c->next_ubo_dst_offset;
89                 c->next_ubo_dst_offset += range->size;
90                 c->num_ubo_ranges++;
91         }
92
93         offset -= range->src_offset;
94
95         /* Adjust for where we stored the TGSI register base. */
96         indirect_offset = qir_ADD(c, indirect_offset,
97                                   qir_uniform_ui(c, (range->dst_offset +
98                                                      offset)));
99
100         /* Clamp to [0, array size).  Note that MIN/MAX are signed. */
101         indirect_offset = qir_MAX(c, indirect_offset, qir_uniform_ui(c, 0));
102         indirect_offset = qir_MIN(c, indirect_offset,
103                                   qir_uniform_ui(c, (range->dst_offset +
104                                                      range->size - 4)));
105
106         qir_TEX_DIRECT(c, indirect_offset, qir_uniform(c, QUNIFORM_UBO_ADDR, 0));
107         c->num_texture_samples++;
108         return qir_TEX_RESULT(c);
109 }
110
111 nir_ssa_def *vc4_nir_get_state_uniform(struct nir_builder *b,
112                                        enum quniform_contents contents)
113 {
114         nir_intrinsic_instr *intr =
115                 nir_intrinsic_instr_create(b->shader,
116                                            nir_intrinsic_load_uniform);
117         intr->const_index[0] = (VC4_NIR_STATE_UNIFORM_OFFSET + contents) * 4;
118         intr->num_components = 1;
119         intr->src[0] = nir_src_for_ssa(nir_imm_int(b, 0));
120         nir_ssa_dest_init(&intr->instr, &intr->dest, 1, 32, NULL);
121         nir_builder_instr_insert(b, &intr->instr);
122         return &intr->dest.ssa;
123 }
124
125 nir_ssa_def *
126 vc4_nir_get_swizzled_channel(nir_builder *b, nir_ssa_def **srcs, int swiz)
127 {
128         switch (swiz) {
129         default:
130         case UTIL_FORMAT_SWIZZLE_NONE:
131                 fprintf(stderr, "warning: unknown swizzle\n");
132                 /* FALLTHROUGH */
133         case UTIL_FORMAT_SWIZZLE_0:
134                 return nir_imm_float(b, 0.0);
135         case UTIL_FORMAT_SWIZZLE_1:
136                 return nir_imm_float(b, 1.0);
137         case UTIL_FORMAT_SWIZZLE_X:
138         case UTIL_FORMAT_SWIZZLE_Y:
139         case UTIL_FORMAT_SWIZZLE_Z:
140         case UTIL_FORMAT_SWIZZLE_W:
141                 return srcs[swiz];
142         }
143 }
144
145 static struct qreg *
146 ntq_init_ssa_def(struct vc4_compile *c, nir_ssa_def *def)
147 {
148         struct qreg *qregs = ralloc_array(c->def_ht, struct qreg,
149                                           def->num_components);
150         _mesa_hash_table_insert(c->def_ht, def, qregs);
151         return qregs;
152 }
153
154 static struct qreg *
155 ntq_get_dest(struct vc4_compile *c, nir_dest *dest)
156 {
157         if (dest->is_ssa) {
158                 struct qreg *qregs = ntq_init_ssa_def(c, &dest->ssa);
159                 for (int i = 0; i < dest->ssa.num_components; i++)
160                         qregs[i] = c->undef;
161                 return qregs;
162         } else {
163                 nir_register *reg = dest->reg.reg;
164                 assert(dest->reg.base_offset == 0);
165                 assert(reg->num_array_elems == 0);
166                 struct hash_entry *entry =
167                         _mesa_hash_table_search(c->def_ht, reg);
168                 return entry->data;
169         }
170 }
171
172 static struct qreg
173 ntq_get_src(struct vc4_compile *c, nir_src src, int i)
174 {
175         struct hash_entry *entry;
176         if (src.is_ssa) {
177                 entry = _mesa_hash_table_search(c->def_ht, src.ssa);
178                 assert(i < src.ssa->num_components);
179         } else {
180                 nir_register *reg = src.reg.reg;
181                 entry = _mesa_hash_table_search(c->def_ht, reg);
182                 assert(reg->num_array_elems == 0);
183                 assert(src.reg.base_offset == 0);
184                 assert(i < reg->num_components);
185         }
186
187         struct qreg *qregs = entry->data;
188         return qregs[i];
189 }
190
191 static struct qreg
192 ntq_get_alu_src(struct vc4_compile *c, nir_alu_instr *instr,
193                 unsigned src)
194 {
195         assert(util_is_power_of_two(instr->dest.write_mask));
196         unsigned chan = ffs(instr->dest.write_mask) - 1;
197         struct qreg r = ntq_get_src(c, instr->src[src].src,
198                                     instr->src[src].swizzle[chan]);
199
200         assert(!instr->src[src].abs);
201         assert(!instr->src[src].negate);
202
203         return r;
204 };
205
206 static inline struct qreg
207 qir_SAT(struct vc4_compile *c, struct qreg val)
208 {
209         return qir_FMAX(c,
210                         qir_FMIN(c, val, qir_uniform_f(c, 1.0)),
211                         qir_uniform_f(c, 0.0));
212 }
213
214 static struct qreg
215 ntq_rcp(struct vc4_compile *c, struct qreg x)
216 {
217         struct qreg r = qir_RCP(c, x);
218
219         /* Apply a Newton-Raphson step to improve the accuracy. */
220         r = qir_FMUL(c, r, qir_FSUB(c,
221                                     qir_uniform_f(c, 2.0),
222                                     qir_FMUL(c, x, r)));
223
224         return r;
225 }
226
227 static struct qreg
228 ntq_rsq(struct vc4_compile *c, struct qreg x)
229 {
230         struct qreg r = qir_RSQ(c, x);
231
232         /* Apply a Newton-Raphson step to improve the accuracy. */
233         r = qir_FMUL(c, r, qir_FSUB(c,
234                                     qir_uniform_f(c, 1.5),
235                                     qir_FMUL(c,
236                                              qir_uniform_f(c, 0.5),
237                                              qir_FMUL(c, x,
238                                                       qir_FMUL(c, r, r)))));
239
240         return r;
241 }
242
243 static struct qreg
244 qir_srgb_decode(struct vc4_compile *c, struct qreg srgb)
245 {
246         struct qreg low = qir_FMUL(c, srgb, qir_uniform_f(c, 1.0 / 12.92));
247         struct qreg high = qir_POW(c,
248                                    qir_FMUL(c,
249                                             qir_FADD(c,
250                                                      srgb,
251                                                      qir_uniform_f(c, 0.055)),
252                                             qir_uniform_f(c, 1.0 / 1.055)),
253                                    qir_uniform_f(c, 2.4));
254
255         qir_SF(c, qir_FSUB(c, srgb, qir_uniform_f(c, 0.04045)));
256         return qir_SEL(c, QPU_COND_NS, low, high);
257 }
258
259 static struct qreg
260 ntq_umul(struct vc4_compile *c, struct qreg src0, struct qreg src1)
261 {
262         struct qreg src0_hi = qir_SHR(c, src0,
263                                       qir_uniform_ui(c, 24));
264         struct qreg src1_hi = qir_SHR(c, src1,
265                                       qir_uniform_ui(c, 24));
266
267         struct qreg hilo = qir_MUL24(c, src0_hi, src1);
268         struct qreg lohi = qir_MUL24(c, src0, src1_hi);
269         struct qreg lolo = qir_MUL24(c, src0, src1);
270
271         return qir_ADD(c, lolo, qir_SHL(c,
272                                         qir_ADD(c, hilo, lohi),
273                                         qir_uniform_ui(c, 24)));
274 }
275
276 static struct qreg
277 ntq_scale_depth_texture(struct vc4_compile *c, struct qreg src)
278 {
279         struct qreg depthf = qir_ITOF(c, qir_SHR(c, src,
280                                                  qir_uniform_ui(c, 8)));
281         return qir_FMUL(c, depthf, qir_uniform_f(c, 1.0f/0xffffff));
282 }
283
284 /**
285  * Emits a lowered TXF_MS from an MSAA texture.
286  *
287  * The addressing math has been lowered in NIR, and now we just need to read
288  * it like a UBO.
289  */
290 static void
291 ntq_emit_txf(struct vc4_compile *c, nir_tex_instr *instr)
292 {
293         uint32_t tile_width = 32;
294         uint32_t tile_height = 32;
295         uint32_t tile_size = (tile_height * tile_width *
296                               VC4_MAX_SAMPLES * sizeof(uint32_t));
297
298         unsigned unit = instr->texture_index;
299         uint32_t w = align(c->key->tex[unit].msaa_width, tile_width);
300         uint32_t w_tiles = w / tile_width;
301         uint32_t h = align(c->key->tex[unit].msaa_height, tile_height);
302         uint32_t h_tiles = h / tile_height;
303         uint32_t size = w_tiles * h_tiles * tile_size;
304
305         struct qreg addr;
306         assert(instr->num_srcs == 1);
307         assert(instr->src[0].src_type == nir_tex_src_coord);
308         addr = ntq_get_src(c, instr->src[0].src, 0);
309
310         /* Perform the clamping required by kernel validation. */
311         addr = qir_MAX(c, addr, qir_uniform_ui(c, 0));
312         addr = qir_MIN(c, addr,  qir_uniform_ui(c, size - 4));
313
314         qir_TEX_DIRECT(c, addr, qir_uniform(c, QUNIFORM_TEXTURE_MSAA_ADDR, unit));
315
316         struct qreg tex = qir_TEX_RESULT(c);
317         c->num_texture_samples++;
318
319         struct qreg *dest = ntq_get_dest(c, &instr->dest);
320         enum pipe_format format = c->key->tex[unit].format;
321         if (util_format_is_depth_or_stencil(format)) {
322                 struct qreg scaled = ntq_scale_depth_texture(c, tex);
323                 for (int i = 0; i < 4; i++)
324                         dest[i] = scaled;
325         } else {
326                 for (int i = 0; i < 4; i++)
327                         dest[i] = qir_UNPACK_8_F(c, tex, i);
328         }
329
330         for (int i = 0; i < 4; i++) {
331                 if (c->tex_srgb_decode[unit] & (1 << i))
332                         dest[i] = qir_srgb_decode(c, dest[i]);
333         }
334 }
335
336 static void
337 ntq_emit_tex(struct vc4_compile *c, nir_tex_instr *instr)
338 {
339         struct qreg s, t, r, lod, proj, compare;
340         bool is_txb = false, is_txl = false, has_proj = false;
341         unsigned unit = instr->texture_index;
342
343         if (instr->op == nir_texop_txf) {
344                 ntq_emit_txf(c, instr);
345                 return;
346         }
347
348         for (unsigned i = 0; i < instr->num_srcs; i++) {
349                 switch (instr->src[i].src_type) {
350                 case nir_tex_src_coord:
351                         s = ntq_get_src(c, instr->src[i].src, 0);
352                         if (instr->sampler_dim == GLSL_SAMPLER_DIM_1D)
353                                 t = qir_uniform_f(c, 0.5);
354                         else
355                                 t = ntq_get_src(c, instr->src[i].src, 1);
356                         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE)
357                                 r = ntq_get_src(c, instr->src[i].src, 2);
358                         break;
359                 case nir_tex_src_bias:
360                         lod = ntq_get_src(c, instr->src[i].src, 0);
361                         is_txb = true;
362                         break;
363                 case nir_tex_src_lod:
364                         lod = ntq_get_src(c, instr->src[i].src, 0);
365                         is_txl = true;
366                         break;
367                 case nir_tex_src_comparitor:
368                         compare = ntq_get_src(c, instr->src[i].src, 0);
369                         break;
370                 case nir_tex_src_projector:
371                         proj = qir_RCP(c, ntq_get_src(c, instr->src[i].src, 0));
372                         s = qir_FMUL(c, s, proj);
373                         t = qir_FMUL(c, t, proj);
374                         has_proj = true;
375                         break;
376                 default:
377                         unreachable("unknown texture source");
378                 }
379         }
380
381         struct qreg texture_u[] = {
382                 qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P0, unit),
383                 qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P1, unit),
384                 qir_uniform(c, QUNIFORM_CONSTANT, 0),
385                 qir_uniform(c, QUNIFORM_CONSTANT, 0),
386         };
387         uint32_t next_texture_u = 0;
388
389         /* There is no native support for GL texture rectangle coordinates, so
390          * we have to rescale from ([0, width], [0, height]) to ([0, 1], [0,
391          * 1]).
392          */
393         if (instr->sampler_dim == GLSL_SAMPLER_DIM_RECT) {
394                 s = qir_FMUL(c, s,
395                              qir_uniform(c, QUNIFORM_TEXRECT_SCALE_X, unit));
396                 t = qir_FMUL(c, t,
397                              qir_uniform(c, QUNIFORM_TEXRECT_SCALE_Y, unit));
398         }
399
400         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE || is_txl) {
401                 texture_u[2] = qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P2,
402                                            unit | (is_txl << 16));
403         }
404
405         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
406                 struct qreg ma = qir_FMAXABS(c, qir_FMAXABS(c, s, t), r);
407                 struct qreg rcp_ma = qir_RCP(c, ma);
408                 s = qir_FMUL(c, s, rcp_ma);
409                 t = qir_FMUL(c, t, rcp_ma);
410                 r = qir_FMUL(c, r, rcp_ma);
411
412                 qir_TEX_R(c, r, texture_u[next_texture_u++]);
413         } else if (c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
414                    c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP ||
415                    c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
416                    c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP) {
417                 qir_TEX_R(c, qir_uniform(c, QUNIFORM_TEXTURE_BORDER_COLOR, unit),
418                           texture_u[next_texture_u++]);
419         }
420
421         if (c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP) {
422                 s = qir_SAT(c, s);
423         }
424
425         if (c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP) {
426                 t = qir_SAT(c, t);
427         }
428
429         qir_TEX_T(c, t, texture_u[next_texture_u++]);
430
431         if (is_txl || is_txb)
432                 qir_TEX_B(c, lod, texture_u[next_texture_u++]);
433
434         qir_TEX_S(c, s, texture_u[next_texture_u++]);
435
436         c->num_texture_samples++;
437         struct qreg tex = qir_TEX_RESULT(c);
438
439         enum pipe_format format = c->key->tex[unit].format;
440
441         struct qreg *dest = ntq_get_dest(c, &instr->dest);
442         if (util_format_is_depth_or_stencil(format)) {
443                 struct qreg normalized = ntq_scale_depth_texture(c, tex);
444                 struct qreg depth_output;
445
446                 struct qreg u0 = qir_uniform_f(c, 0.0f);
447                 struct qreg u1 = qir_uniform_f(c, 1.0f);
448                 if (c->key->tex[unit].compare_mode) {
449                         if (has_proj)
450                                 compare = qir_FMUL(c, compare, proj);
451
452                         switch (c->key->tex[unit].compare_func) {
453                         case PIPE_FUNC_NEVER:
454                                 depth_output = qir_uniform_f(c, 0.0f);
455                                 break;
456                         case PIPE_FUNC_ALWAYS:
457                                 depth_output = u1;
458                                 break;
459                         case PIPE_FUNC_EQUAL:
460                                 qir_SF(c, qir_FSUB(c, compare, normalized));
461                                 depth_output = qir_SEL(c, QPU_COND_ZS, u1, u0);
462                                 break;
463                         case PIPE_FUNC_NOTEQUAL:
464                                 qir_SF(c, qir_FSUB(c, compare, normalized));
465                                 depth_output = qir_SEL(c, QPU_COND_ZC, u1, u0);
466                                 break;
467                         case PIPE_FUNC_GREATER:
468                                 qir_SF(c, qir_FSUB(c, compare, normalized));
469                                 depth_output = qir_SEL(c, QPU_COND_NC, u1, u0);
470                                 break;
471                         case PIPE_FUNC_GEQUAL:
472                                 qir_SF(c, qir_FSUB(c, normalized, compare));
473                                 depth_output = qir_SEL(c, QPU_COND_NS, u1, u0);
474                                 break;
475                         case PIPE_FUNC_LESS:
476                                 qir_SF(c, qir_FSUB(c, compare, normalized));
477                                 depth_output = qir_SEL(c, QPU_COND_NS, u1, u0);
478                                 break;
479                         case PIPE_FUNC_LEQUAL:
480                                 qir_SF(c, qir_FSUB(c, normalized, compare));
481                                 depth_output = qir_SEL(c, QPU_COND_NC, u1, u0);
482                                 break;
483                         }
484                 } else {
485                         depth_output = normalized;
486                 }
487
488                 for (int i = 0; i < 4; i++)
489                         dest[i] = depth_output;
490         } else {
491                 for (int i = 0; i < 4; i++)
492                         dest[i] = qir_UNPACK_8_F(c, tex, i);
493         }
494
495         for (int i = 0; i < 4; i++) {
496                 if (c->tex_srgb_decode[unit] & (1 << i))
497                         dest[i] = qir_srgb_decode(c, dest[i]);
498         }
499 }
500
501 /**
502  * Computes x - floor(x), which is tricky because our FTOI truncates (rounds
503  * to zero).
504  */
505 static struct qreg
506 ntq_ffract(struct vc4_compile *c, struct qreg src)
507 {
508         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
509         struct qreg diff = qir_FSUB(c, src, trunc);
510         qir_SF(c, diff);
511         return qir_SEL(c, QPU_COND_NS,
512                        qir_FADD(c, diff, qir_uniform_f(c, 1.0)), diff);
513 }
514
515 /**
516  * Computes floor(x), which is tricky because our FTOI truncates (rounds to
517  * zero).
518  */
519 static struct qreg
520 ntq_ffloor(struct vc4_compile *c, struct qreg src)
521 {
522         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
523
524         /* This will be < 0 if we truncated and the truncation was of a value
525          * that was < 0 in the first place.
526          */
527         qir_SF(c, qir_FSUB(c, src, trunc));
528
529         return qir_SEL(c, QPU_COND_NS,
530                        qir_FSUB(c, trunc, qir_uniform_f(c, 1.0)), trunc);
531 }
532
533 /**
534  * Computes ceil(x), which is tricky because our FTOI truncates (rounds to
535  * zero).
536  */
537 static struct qreg
538 ntq_fceil(struct vc4_compile *c, struct qreg src)
539 {
540         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
541
542         /* This will be < 0 if we truncated and the truncation was of a value
543          * that was > 0 in the first place.
544          */
545         qir_SF(c, qir_FSUB(c, trunc, src));
546
547         return qir_SEL(c, QPU_COND_NS,
548                        qir_FADD(c, trunc, qir_uniform_f(c, 1.0)), trunc);
549 }
550
551 static struct qreg
552 ntq_fsin(struct vc4_compile *c, struct qreg src)
553 {
554         float coeff[] = {
555                 -2.0 * M_PI,
556                 pow(2.0 * M_PI, 3) / (3 * 2 * 1),
557                 -pow(2.0 * M_PI, 5) / (5 * 4 * 3 * 2 * 1),
558                 pow(2.0 * M_PI, 7) / (7 * 6 * 5 * 4 * 3 * 2 * 1),
559                 -pow(2.0 * M_PI, 9) / (9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
560         };
561
562         struct qreg scaled_x =
563                 qir_FMUL(c,
564                          src,
565                          qir_uniform_f(c, 1.0 / (M_PI * 2.0)));
566
567         struct qreg x = qir_FADD(c,
568                                  ntq_ffract(c, scaled_x),
569                                  qir_uniform_f(c, -0.5));
570         struct qreg x2 = qir_FMUL(c, x, x);
571         struct qreg sum = qir_FMUL(c, x, qir_uniform_f(c, coeff[0]));
572         for (int i = 1; i < ARRAY_SIZE(coeff); i++) {
573                 x = qir_FMUL(c, x, x2);
574                 sum = qir_FADD(c,
575                                sum,
576                                qir_FMUL(c,
577                                         x,
578                                         qir_uniform_f(c, coeff[i])));
579         }
580         return sum;
581 }
582
583 static struct qreg
584 ntq_fcos(struct vc4_compile *c, struct qreg src)
585 {
586         float coeff[] = {
587                 -1.0f,
588                 pow(2.0 * M_PI, 2) / (2 * 1),
589                 -pow(2.0 * M_PI, 4) / (4 * 3 * 2 * 1),
590                 pow(2.0 * M_PI, 6) / (6 * 5 * 4 * 3 * 2 * 1),
591                 -pow(2.0 * M_PI, 8) / (8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
592                 pow(2.0 * M_PI, 10) / (10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
593         };
594
595         struct qreg scaled_x =
596                 qir_FMUL(c, src,
597                          qir_uniform_f(c, 1.0f / (M_PI * 2.0f)));
598         struct qreg x_frac = qir_FADD(c,
599                                       ntq_ffract(c, scaled_x),
600                                       qir_uniform_f(c, -0.5));
601
602         struct qreg sum = qir_uniform_f(c, coeff[0]);
603         struct qreg x2 = qir_FMUL(c, x_frac, x_frac);
604         struct qreg x = x2; /* Current x^2, x^4, or x^6 */
605         for (int i = 1; i < ARRAY_SIZE(coeff); i++) {
606                 if (i != 1)
607                         x = qir_FMUL(c, x, x2);
608
609                 struct qreg mul = qir_FMUL(c,
610                                            x,
611                                            qir_uniform_f(c, coeff[i]));
612                 if (i == 0)
613                         sum = mul;
614                 else
615                         sum = qir_FADD(c, sum, mul);
616         }
617         return sum;
618 }
619
620 static struct qreg
621 ntq_fsign(struct vc4_compile *c, struct qreg src)
622 {
623         struct qreg t = qir_get_temp(c);
624
625         qir_SF(c, src);
626         qir_MOV_dest(c, t, qir_uniform_f(c, 0.0));
627         qir_MOV_dest(c, t, qir_uniform_f(c, 1.0))->cond = QPU_COND_ZC;
628         qir_MOV_dest(c, t, qir_uniform_f(c, -1.0))->cond = QPU_COND_NS;
629         return t;
630 }
631
632 static void
633 emit_vertex_input(struct vc4_compile *c, int attr)
634 {
635         enum pipe_format format = c->vs_key->attr_formats[attr];
636         uint32_t attr_size = util_format_get_blocksize(format);
637
638         c->vattr_sizes[attr] = align(attr_size, 4);
639         for (int i = 0; i < align(attr_size, 4) / 4; i++) {
640                 struct qreg vpm = { QFILE_VPM, attr * 4 + i };
641                 c->inputs[attr * 4 + i] = qir_MOV(c, vpm);
642                 c->num_inputs++;
643         }
644 }
645
646 static void
647 emit_fragcoord_input(struct vc4_compile *c, int attr)
648 {
649         c->inputs[attr * 4 + 0] = qir_FRAG_X(c);
650         c->inputs[attr * 4 + 1] = qir_FRAG_Y(c);
651         c->inputs[attr * 4 + 2] =
652                 qir_FMUL(c,
653                          qir_ITOF(c, qir_FRAG_Z(c)),
654                          qir_uniform_f(c, 1.0 / 0xffffff));
655         c->inputs[attr * 4 + 3] = qir_RCP(c, qir_FRAG_W(c));
656 }
657
658 static struct qreg
659 emit_fragment_varying(struct vc4_compile *c, gl_varying_slot slot,
660                       uint8_t swizzle)
661 {
662         uint32_t i = c->num_input_slots++;
663         struct qreg vary = {
664                 QFILE_VARY,
665                 i
666         };
667
668         if (c->num_input_slots >= c->input_slots_array_size) {
669                 c->input_slots_array_size =
670                         MAX2(4, c->input_slots_array_size * 2);
671
672                 c->input_slots = reralloc(c, c->input_slots,
673                                           struct vc4_varying_slot,
674                                           c->input_slots_array_size);
675         }
676
677         c->input_slots[i].slot = slot;
678         c->input_slots[i].swizzle = swizzle;
679
680         return qir_VARY_ADD_C(c, qir_FMUL(c, vary, qir_FRAG_W(c)));
681 }
682
683 static void
684 emit_fragment_input(struct vc4_compile *c, int attr, gl_varying_slot slot)
685 {
686         for (int i = 0; i < 4; i++) {
687                 c->inputs[attr * 4 + i] =
688                         emit_fragment_varying(c, slot, i);
689                 c->num_inputs++;
690         }
691 }
692
693 static void
694 add_output(struct vc4_compile *c,
695            uint32_t decl_offset,
696            uint8_t slot,
697            uint8_t swizzle)
698 {
699         uint32_t old_array_size = c->outputs_array_size;
700         resize_qreg_array(c, &c->outputs, &c->outputs_array_size,
701                           decl_offset + 1);
702
703         if (old_array_size != c->outputs_array_size) {
704                 c->output_slots = reralloc(c,
705                                            c->output_slots,
706                                            struct vc4_varying_slot,
707                                            c->outputs_array_size);
708         }
709
710         c->output_slots[decl_offset].slot = slot;
711         c->output_slots[decl_offset].swizzle = swizzle;
712 }
713
714 static void
715 declare_uniform_range(struct vc4_compile *c, uint32_t start, uint32_t size)
716 {
717         unsigned array_id = c->num_uniform_ranges++;
718         if (array_id >= c->ubo_ranges_array_size) {
719                 c->ubo_ranges_array_size = MAX2(c->ubo_ranges_array_size * 2,
720                                                 array_id + 1);
721                 c->ubo_ranges = reralloc(c, c->ubo_ranges,
722                                          struct vc4_compiler_ubo_range,
723                                          c->ubo_ranges_array_size);
724         }
725
726         c->ubo_ranges[array_id].dst_offset = 0;
727         c->ubo_ranges[array_id].src_offset = start;
728         c->ubo_ranges[array_id].size = size;
729         c->ubo_ranges[array_id].used = false;
730 }
731
732 static bool
733 ntq_src_is_only_ssa_def_user(nir_src *src)
734 {
735         if (!src->is_ssa)
736                 return false;
737
738         if (!list_empty(&src->ssa->if_uses))
739                 return false;
740
741         return (src->ssa->uses.next == &src->use_link &&
742                 src->ssa->uses.next->next == &src->ssa->uses);
743 }
744
745 /**
746  * In general, emits a nir_pack_unorm_4x8 as a series of MOVs with the pack
747  * bit set.
748  *
749  * However, as an optimization, it tries to find the instructions generating
750  * the sources to be packed and just emit the pack flag there, if possible.
751  */
752 static void
753 ntq_emit_pack_unorm_4x8(struct vc4_compile *c, nir_alu_instr *instr)
754 {
755         struct qreg result = qir_get_temp(c);
756         struct nir_alu_instr *vec4 = NULL;
757
758         /* If packing from a vec4 op (as expected), identify it so that we can
759          * peek back at what generated its sources.
760          */
761         if (instr->src[0].src.is_ssa &&
762             instr->src[0].src.ssa->parent_instr->type == nir_instr_type_alu &&
763             nir_instr_as_alu(instr->src[0].src.ssa->parent_instr)->op ==
764             nir_op_vec4) {
765                 vec4 = nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
766         }
767
768         /* If the pack is replicating the same channel 4 times, use the 8888
769          * pack flag.  This is common for blending using the alpha
770          * channel.
771          */
772         if (instr->src[0].swizzle[0] == instr->src[0].swizzle[1] &&
773             instr->src[0].swizzle[0] == instr->src[0].swizzle[2] &&
774             instr->src[0].swizzle[0] == instr->src[0].swizzle[3]) {
775                 struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
776                 *dest = qir_PACK_8888_F(c,
777                                         ntq_get_src(c, instr->src[0].src,
778                                                     instr->src[0].swizzle[0]));
779                 return;
780         }
781
782         for (int i = 0; i < 4; i++) {
783                 int swiz = instr->src[0].swizzle[i];
784                 struct qreg src;
785                 if (vec4) {
786                         src = ntq_get_src(c, vec4->src[swiz].src,
787                                           vec4->src[swiz].swizzle[0]);
788                 } else {
789                         src = ntq_get_src(c, instr->src[0].src, swiz);
790                 }
791
792                 if (vec4 &&
793                     ntq_src_is_only_ssa_def_user(&vec4->src[swiz].src) &&
794                     src.file == QFILE_TEMP &&
795                     c->defs[src.index] &&
796                     qir_is_mul(c->defs[src.index]) &&
797                     !c->defs[src.index]->dst.pack) {
798                         struct qinst *rewrite = c->defs[src.index];
799                         c->defs[src.index] = NULL;
800                         rewrite->dst = result;
801                         rewrite->dst.pack = QPU_PACK_MUL_8A + i;
802                         continue;
803                 }
804
805                 qir_PACK_8_F(c, result, src, i);
806         }
807
808         struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
809         *dest = result;
810 }
811
812 /** Handles sign-extended bitfield extracts for 16 bits. */
813 static struct qreg
814 ntq_emit_ibfe(struct vc4_compile *c, struct qreg base, struct qreg offset,
815               struct qreg bits)
816 {
817         assert(bits.file == QFILE_UNIF &&
818                c->uniform_contents[bits.index] == QUNIFORM_CONSTANT &&
819                c->uniform_data[bits.index] == 16);
820
821         assert(offset.file == QFILE_UNIF &&
822                c->uniform_contents[offset.index] == QUNIFORM_CONSTANT);
823         int offset_bit = c->uniform_data[offset.index];
824         assert(offset_bit % 16 == 0);
825
826         return qir_UNPACK_16_I(c, base, offset_bit / 16);
827 }
828
829 /** Handles unsigned bitfield extracts for 8 bits. */
830 static struct qreg
831 ntq_emit_ubfe(struct vc4_compile *c, struct qreg base, struct qreg offset,
832               struct qreg bits)
833 {
834         assert(bits.file == QFILE_UNIF &&
835                c->uniform_contents[bits.index] == QUNIFORM_CONSTANT &&
836                c->uniform_data[bits.index] == 8);
837
838         assert(offset.file == QFILE_UNIF &&
839                c->uniform_contents[offset.index] == QUNIFORM_CONSTANT);
840         int offset_bit = c->uniform_data[offset.index];
841         assert(offset_bit % 8 == 0);
842
843         return qir_UNPACK_8_I(c, base, offset_bit / 8);
844 }
845
846 /**
847  * If compare_instr is a valid comparison instruction, emits the
848  * compare_instr's comparison and returns the sel_instr's return value based
849  * on the compare_instr's result.
850  */
851 static bool
852 ntq_emit_comparison(struct vc4_compile *c, struct qreg *dest,
853                     nir_alu_instr *compare_instr,
854                     nir_alu_instr *sel_instr)
855 {
856         enum qpu_cond cond;
857
858         switch (compare_instr->op) {
859         case nir_op_feq:
860         case nir_op_ieq:
861         case nir_op_seq:
862                 cond = QPU_COND_ZS;
863                 break;
864         case nir_op_fne:
865         case nir_op_ine:
866         case nir_op_sne:
867                 cond = QPU_COND_ZC;
868                 break;
869         case nir_op_fge:
870         case nir_op_ige:
871         case nir_op_uge:
872         case nir_op_sge:
873                 cond = QPU_COND_NC;
874                 break;
875         case nir_op_flt:
876         case nir_op_ilt:
877         case nir_op_slt:
878                 cond = QPU_COND_NS;
879                 break;
880         default:
881                 return false;
882         }
883
884         struct qreg src0 = ntq_get_alu_src(c, compare_instr, 0);
885         struct qreg src1 = ntq_get_alu_src(c, compare_instr, 1);
886
887         unsigned unsized_type =
888                 nir_alu_type_get_base_type(nir_op_infos[compare_instr->op].input_types[0]);
889         if (unsized_type == nir_type_float)
890                 qir_SF(c, qir_FSUB(c, src0, src1));
891         else
892                 qir_SF(c, qir_SUB(c, src0, src1));
893
894         switch (sel_instr->op) {
895         case nir_op_seq:
896         case nir_op_sne:
897         case nir_op_sge:
898         case nir_op_slt:
899                 *dest = qir_SEL(c, cond,
900                                 qir_uniform_f(c, 1.0), qir_uniform_f(c, 0.0));
901                 break;
902
903         case nir_op_bcsel:
904                 *dest = qir_SEL(c, cond,
905                                 ntq_get_alu_src(c, sel_instr, 1),
906                                 ntq_get_alu_src(c, sel_instr, 2));
907                 break;
908
909         default:
910                 *dest = qir_SEL(c, cond,
911                                 qir_uniform_ui(c, ~0), qir_uniform_ui(c, 0));
912                 break;
913         }
914
915         return true;
916 }
917
918 /**
919  * Attempts to fold a comparison generating a boolean result into the
920  * condition code for selecting between two values, instead of comparing the
921  * boolean result against 0 to generate the condition code.
922  */
923 static struct qreg ntq_emit_bcsel(struct vc4_compile *c, nir_alu_instr *instr,
924                                   struct qreg *src)
925 {
926         if (!instr->src[0].src.is_ssa)
927                 goto out;
928         nir_alu_instr *compare =
929                 nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
930         if (!compare)
931                 goto out;
932
933         struct qreg dest;
934         if (ntq_emit_comparison(c, &dest, compare, instr))
935                 return dest;
936
937 out:
938         qir_SF(c, src[0]);
939         return qir_SEL(c, QPU_COND_NS, src[1], src[2]);
940 }
941
942 static void
943 ntq_emit_alu(struct vc4_compile *c, nir_alu_instr *instr)
944 {
945         /* Vectors are special in that they have non-scalarized writemasks,
946          * and just take the first swizzle channel for each argument in order
947          * into each writemask channel.
948          */
949         if (instr->op == nir_op_vec2 ||
950             instr->op == nir_op_vec3 ||
951             instr->op == nir_op_vec4) {
952                 struct qreg srcs[4];
953                 for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
954                         srcs[i] = ntq_get_src(c, instr->src[i].src,
955                                               instr->src[i].swizzle[0]);
956                 struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
957                 for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
958                         dest[i] = srcs[i];
959                 return;
960         }
961
962         if (instr->op == nir_op_pack_unorm_4x8) {
963                 ntq_emit_pack_unorm_4x8(c, instr);
964                 return;
965         }
966
967         if (instr->op == nir_op_unpack_unorm_4x8) {
968                 struct qreg src = ntq_get_src(c, instr->src[0].src,
969                                               instr->src[0].swizzle[0]);
970                 struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
971                 for (int i = 0; i < 4; i++) {
972                         if (instr->dest.write_mask & (1 << i))
973                                 dest[i] = qir_UNPACK_8_F(c, src, i);
974                 }
975                 return;
976         }
977
978         /* General case: We can just grab the one used channel per src. */
979         struct qreg src[nir_op_infos[instr->op].num_inputs];
980         for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
981                 src[i] = ntq_get_alu_src(c, instr, i);
982         }
983
984         /* Pick the channel to store the output in. */
985         assert(!instr->dest.saturate);
986         struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
987         assert(util_is_power_of_two(instr->dest.write_mask));
988         dest += ffs(instr->dest.write_mask) - 1;
989
990         switch (instr->op) {
991         case nir_op_fmov:
992         case nir_op_imov:
993                 *dest = qir_MOV(c, src[0]);
994                 break;
995         case nir_op_fmul:
996                 *dest = qir_FMUL(c, src[0], src[1]);
997                 break;
998         case nir_op_fadd:
999                 *dest = qir_FADD(c, src[0], src[1]);
1000                 break;
1001         case nir_op_fsub:
1002                 *dest = qir_FSUB(c, src[0], src[1]);
1003                 break;
1004         case nir_op_fmin:
1005                 *dest = qir_FMIN(c, src[0], src[1]);
1006                 break;
1007         case nir_op_fmax:
1008                 *dest = qir_FMAX(c, src[0], src[1]);
1009                 break;
1010
1011         case nir_op_f2i:
1012         case nir_op_f2u:
1013                 *dest = qir_FTOI(c, src[0]);
1014                 break;
1015         case nir_op_i2f:
1016         case nir_op_u2f:
1017                 *dest = qir_ITOF(c, src[0]);
1018                 break;
1019         case nir_op_b2f:
1020                 *dest = qir_AND(c, src[0], qir_uniform_f(c, 1.0));
1021                 break;
1022         case nir_op_b2i:
1023                 *dest = qir_AND(c, src[0], qir_uniform_ui(c, 1));
1024                 break;
1025         case nir_op_i2b:
1026         case nir_op_f2b:
1027                 qir_SF(c, src[0]);
1028                 *dest = qir_SEL(c, QPU_COND_ZC,
1029                                 qir_uniform_ui(c, ~0),
1030                                 qir_uniform_ui(c, 0));
1031                 break;
1032
1033         case nir_op_iadd:
1034                 *dest = qir_ADD(c, src[0], src[1]);
1035                 break;
1036         case nir_op_ushr:
1037                 *dest = qir_SHR(c, src[0], src[1]);
1038                 break;
1039         case nir_op_isub:
1040                 *dest = qir_SUB(c, src[0], src[1]);
1041                 break;
1042         case nir_op_ishr:
1043                 *dest = qir_ASR(c, src[0], src[1]);
1044                 break;
1045         case nir_op_ishl:
1046                 *dest = qir_SHL(c, src[0], src[1]);
1047                 break;
1048         case nir_op_imin:
1049                 *dest = qir_MIN(c, src[0], src[1]);
1050                 break;
1051         case nir_op_imax:
1052                 *dest = qir_MAX(c, src[0], src[1]);
1053                 break;
1054         case nir_op_iand:
1055                 *dest = qir_AND(c, src[0], src[1]);
1056                 break;
1057         case nir_op_ior:
1058                 *dest = qir_OR(c, src[0], src[1]);
1059                 break;
1060         case nir_op_ixor:
1061                 *dest = qir_XOR(c, src[0], src[1]);
1062                 break;
1063         case nir_op_inot:
1064                 *dest = qir_NOT(c, src[0]);
1065                 break;
1066
1067         case nir_op_imul:
1068                 *dest = ntq_umul(c, src[0], src[1]);
1069                 break;
1070
1071         case nir_op_seq:
1072         case nir_op_sne:
1073         case nir_op_sge:
1074         case nir_op_slt:
1075         case nir_op_feq:
1076         case nir_op_fne:
1077         case nir_op_fge:
1078         case nir_op_flt:
1079         case nir_op_ieq:
1080         case nir_op_ine:
1081         case nir_op_ige:
1082         case nir_op_uge:
1083         case nir_op_ilt:
1084                 if (!ntq_emit_comparison(c, dest, instr, instr)) {
1085                         fprintf(stderr, "Bad comparison instruction\n");
1086                 }
1087                 break;
1088
1089         case nir_op_bcsel:
1090                 *dest = ntq_emit_bcsel(c, instr, src);
1091                 break;
1092         case nir_op_fcsel:
1093                 qir_SF(c, src[0]);
1094                 *dest = qir_SEL(c, QPU_COND_ZC, src[1], src[2]);
1095                 break;
1096
1097         case nir_op_frcp:
1098                 *dest = ntq_rcp(c, src[0]);
1099                 break;
1100         case nir_op_frsq:
1101                 *dest = ntq_rsq(c, src[0]);
1102                 break;
1103         case nir_op_fexp2:
1104                 *dest = qir_EXP2(c, src[0]);
1105                 break;
1106         case nir_op_flog2:
1107                 *dest = qir_LOG2(c, src[0]);
1108                 break;
1109
1110         case nir_op_ftrunc:
1111                 *dest = qir_ITOF(c, qir_FTOI(c, src[0]));
1112                 break;
1113         case nir_op_fceil:
1114                 *dest = ntq_fceil(c, src[0]);
1115                 break;
1116         case nir_op_ffract:
1117                 *dest = ntq_ffract(c, src[0]);
1118                 break;
1119         case nir_op_ffloor:
1120                 *dest = ntq_ffloor(c, src[0]);
1121                 break;
1122
1123         case nir_op_fsin:
1124                 *dest = ntq_fsin(c, src[0]);
1125                 break;
1126         case nir_op_fcos:
1127                 *dest = ntq_fcos(c, src[0]);
1128                 break;
1129
1130         case nir_op_fsign:
1131                 *dest = ntq_fsign(c, src[0]);
1132                 break;
1133
1134         case nir_op_fabs:
1135                 *dest = qir_FMAXABS(c, src[0], src[0]);
1136                 break;
1137         case nir_op_iabs:
1138                 *dest = qir_MAX(c, src[0],
1139                                 qir_SUB(c, qir_uniform_ui(c, 0), src[0]));
1140                 break;
1141
1142         case nir_op_ibitfield_extract:
1143                 *dest = ntq_emit_ibfe(c, src[0], src[1], src[2]);
1144                 break;
1145
1146         case nir_op_ubitfield_extract:
1147                 *dest = ntq_emit_ubfe(c, src[0], src[1], src[2]);
1148                 break;
1149
1150         case nir_op_usadd_4x8:
1151                 *dest = qir_V8ADDS(c, src[0], src[1]);
1152                 break;
1153
1154         case nir_op_ussub_4x8:
1155                 *dest = qir_V8SUBS(c, src[0], src[1]);
1156                 break;
1157
1158         case nir_op_umin_4x8:
1159                 *dest = qir_V8MIN(c, src[0], src[1]);
1160                 break;
1161
1162         case nir_op_umax_4x8:
1163                 *dest = qir_V8MAX(c, src[0], src[1]);
1164                 break;
1165
1166         case nir_op_umul_unorm_4x8:
1167                 *dest = qir_V8MULD(c, src[0], src[1]);
1168                 break;
1169
1170         default:
1171                 fprintf(stderr, "unknown NIR ALU inst: ");
1172                 nir_print_instr(&instr->instr, stderr);
1173                 fprintf(stderr, "\n");
1174                 abort();
1175         }
1176 }
1177
1178 static void
1179 emit_frag_end(struct vc4_compile *c)
1180 {
1181         struct qreg color;
1182         if (c->output_color_index != -1) {
1183                 color = c->outputs[c->output_color_index];
1184         } else {
1185                 color = qir_uniform_ui(c, 0);
1186         }
1187
1188         uint32_t discard_cond = QPU_COND_ALWAYS;
1189         if (c->discard.file != QFILE_NULL) {
1190                 qir_SF(c, c->discard);
1191                 discard_cond = QPU_COND_ZS;
1192         }
1193
1194         if (c->fs_key->stencil_enabled) {
1195                 qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 0));
1196                 if (c->fs_key->stencil_twoside) {
1197                         qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 1));
1198                 }
1199                 if (c->fs_key->stencil_full_writemasks) {
1200                         qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 2));
1201                 }
1202         }
1203
1204         if (c->output_sample_mask_index != -1) {
1205                 qir_MS_MASK(c, c->outputs[c->output_sample_mask_index]);
1206         }
1207
1208         if (c->fs_key->depth_enabled) {
1209                 struct qreg z;
1210                 if (c->output_position_index != -1) {
1211                         z = qir_FTOI(c, qir_FMUL(c, c->outputs[c->output_position_index + 2],
1212                                                  qir_uniform_f(c, 0xffffff)));
1213                 } else {
1214                         z = qir_FRAG_Z(c);
1215                 }
1216                 struct qinst *inst = qir_TLB_Z_WRITE(c, z);
1217                 inst->cond = discard_cond;
1218         }
1219
1220         if (!c->msaa_per_sample_output) {
1221                 struct qinst *inst = qir_TLB_COLOR_WRITE(c, color);
1222                 inst->cond = discard_cond;
1223         } else {
1224                 for (int i = 0; i < VC4_MAX_SAMPLES; i++) {
1225                         struct qinst *inst = qir_TLB_COLOR_WRITE_MS(c, c->sample_colors[i]);
1226                         inst->cond = discard_cond;
1227                 }
1228         }
1229 }
1230
1231 static void
1232 emit_scaled_viewport_write(struct vc4_compile *c, struct qreg rcp_w)
1233 {
1234         struct qreg packed = qir_get_temp(c);
1235
1236         for (int i = 0; i < 2; i++) {
1237                 struct qreg scale =
1238                         qir_uniform(c, QUNIFORM_VIEWPORT_X_SCALE + i, 0);
1239
1240                 struct qreg packed_chan = packed;
1241                 packed_chan.pack = QPU_PACK_A_16A + i;
1242
1243                 qir_FTOI_dest(c, packed_chan,
1244                               qir_FMUL(c,
1245                                        qir_FMUL(c,
1246                                                 c->outputs[c->output_position_index + i],
1247                                                 scale),
1248                                        rcp_w));
1249         }
1250
1251         qir_VPM_WRITE(c, packed);
1252 }
1253
1254 static void
1255 emit_zs_write(struct vc4_compile *c, struct qreg rcp_w)
1256 {
1257         struct qreg zscale = qir_uniform(c, QUNIFORM_VIEWPORT_Z_SCALE, 0);
1258         struct qreg zoffset = qir_uniform(c, QUNIFORM_VIEWPORT_Z_OFFSET, 0);
1259
1260         qir_VPM_WRITE(c, qir_FADD(c, qir_FMUL(c, qir_FMUL(c,
1261                                                           c->outputs[c->output_position_index + 2],
1262                                                           zscale),
1263                                               rcp_w),
1264                                   zoffset));
1265 }
1266
1267 static void
1268 emit_rcp_wc_write(struct vc4_compile *c, struct qreg rcp_w)
1269 {
1270         qir_VPM_WRITE(c, rcp_w);
1271 }
1272
1273 static void
1274 emit_point_size_write(struct vc4_compile *c)
1275 {
1276         struct qreg point_size;
1277
1278         if (c->output_point_size_index != -1)
1279                 point_size = c->outputs[c->output_point_size_index];
1280         else
1281                 point_size = qir_uniform_f(c, 1.0);
1282
1283         /* Workaround: HW-2726 PTB does not handle zero-size points (BCM2835,
1284          * BCM21553).
1285          */
1286         point_size = qir_FMAX(c, point_size, qir_uniform_f(c, .125));
1287
1288         qir_VPM_WRITE(c, point_size);
1289 }
1290
1291 /**
1292  * Emits a VPM read of the stub vertex attribute set up by vc4_draw.c.
1293  *
1294  * The simulator insists that there be at least one vertex attribute, so
1295  * vc4_draw.c will emit one if it wouldn't have otherwise.  The simulator also
1296  * insists that all vertex attributes loaded get read by the VS/CS, so we have
1297  * to consume it here.
1298  */
1299 static void
1300 emit_stub_vpm_read(struct vc4_compile *c)
1301 {
1302         if (c->num_inputs)
1303                 return;
1304
1305         c->vattr_sizes[0] = 4;
1306         struct qreg vpm = { QFILE_VPM, 0 };
1307         (void)qir_MOV(c, vpm);
1308         c->num_inputs++;
1309 }
1310
1311 static void
1312 emit_vert_end(struct vc4_compile *c,
1313               struct vc4_varying_slot *fs_inputs,
1314               uint32_t num_fs_inputs)
1315 {
1316         struct qreg rcp_w = qir_RCP(c, c->outputs[c->output_position_index + 3]);
1317
1318         emit_stub_vpm_read(c);
1319
1320         emit_scaled_viewport_write(c, rcp_w);
1321         emit_zs_write(c, rcp_w);
1322         emit_rcp_wc_write(c, rcp_w);
1323         if (c->vs_key->per_vertex_point_size)
1324                 emit_point_size_write(c);
1325
1326         for (int i = 0; i < num_fs_inputs; i++) {
1327                 struct vc4_varying_slot *input = &fs_inputs[i];
1328                 int j;
1329
1330                 for (j = 0; j < c->num_outputs; j++) {
1331                         struct vc4_varying_slot *output =
1332                                 &c->output_slots[j];
1333
1334                         if (input->slot == output->slot &&
1335                             input->swizzle == output->swizzle) {
1336                                 qir_VPM_WRITE(c, c->outputs[j]);
1337                                 break;
1338                         }
1339                 }
1340                 /* Emit padding if we didn't find a declared VS output for
1341                  * this FS input.
1342                  */
1343                 if (j == c->num_outputs)
1344                         qir_VPM_WRITE(c, qir_uniform_f(c, 0.0));
1345         }
1346 }
1347
1348 static void
1349 emit_coord_end(struct vc4_compile *c)
1350 {
1351         struct qreg rcp_w = qir_RCP(c, c->outputs[c->output_position_index + 3]);
1352
1353         emit_stub_vpm_read(c);
1354
1355         for (int i = 0; i < 4; i++)
1356                 qir_VPM_WRITE(c, c->outputs[c->output_position_index + i]);
1357
1358         emit_scaled_viewport_write(c, rcp_w);
1359         emit_zs_write(c, rcp_w);
1360         emit_rcp_wc_write(c, rcp_w);
1361         if (c->vs_key->per_vertex_point_size)
1362                 emit_point_size_write(c);
1363 }
1364
1365 static void
1366 vc4_optimize_nir(struct nir_shader *s)
1367 {
1368         bool progress;
1369
1370         do {
1371                 progress = false;
1372
1373                 NIR_PASS_V(s, nir_lower_vars_to_ssa);
1374                 NIR_PASS_V(s, nir_lower_alu_to_scalar);
1375
1376                 NIR_PASS(progress, s, nir_copy_prop);
1377                 NIR_PASS(progress, s, nir_opt_dce);
1378                 NIR_PASS(progress, s, nir_opt_cse);
1379                 NIR_PASS(progress, s, nir_opt_peephole_select);
1380                 NIR_PASS(progress, s, nir_opt_algebraic);
1381                 NIR_PASS(progress, s, nir_opt_constant_folding);
1382                 NIR_PASS(progress, s, nir_opt_undef);
1383         } while (progress);
1384 }
1385
1386 static int
1387 driver_location_compare(const void *in_a, const void *in_b)
1388 {
1389         const nir_variable *const *a = in_a;
1390         const nir_variable *const *b = in_b;
1391
1392         return (*a)->data.driver_location - (*b)->data.driver_location;
1393 }
1394
1395 static void
1396 ntq_setup_inputs(struct vc4_compile *c)
1397 {
1398         unsigned num_entries = 0;
1399         nir_foreach_variable(var, &c->s->inputs)
1400                 num_entries++;
1401
1402         nir_variable *vars[num_entries];
1403
1404         unsigned i = 0;
1405         nir_foreach_variable(var, &c->s->inputs)
1406                 vars[i++] = var;
1407
1408         /* Sort the variables so that we emit the input setup in
1409          * driver_location order.  This is required for VPM reads, whose data
1410          * is fetched into the VPM in driver_location (TGSI register index)
1411          * order.
1412          */
1413         qsort(&vars, num_entries, sizeof(*vars), driver_location_compare);
1414
1415         for (unsigned i = 0; i < num_entries; i++) {
1416                 nir_variable *var = vars[i];
1417                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1418                 unsigned loc = var->data.driver_location;
1419
1420                 assert(array_len == 1);
1421                 (void)array_len;
1422                 resize_qreg_array(c, &c->inputs, &c->inputs_array_size,
1423                                   (loc + 1) * 4);
1424
1425                 if (c->stage == QSTAGE_FRAG) {
1426                         if (var->data.location == VARYING_SLOT_POS) {
1427                                 emit_fragcoord_input(c, loc);
1428                         } else if (var->data.location == VARYING_SLOT_FACE) {
1429                                 c->inputs[loc * 4 + 0] = qir_FRAG_REV_FLAG(c);
1430                         } else if (var->data.location >= VARYING_SLOT_VAR0 &&
1431                                    (c->fs_key->point_sprite_mask &
1432                                     (1 << (var->data.location -
1433                                            VARYING_SLOT_VAR0)))) {
1434                                 c->inputs[loc * 4 + 0] = c->point_x;
1435                                 c->inputs[loc * 4 + 1] = c->point_y;
1436                         } else {
1437                                 emit_fragment_input(c, loc, var->data.location);
1438                         }
1439                 } else {
1440                         emit_vertex_input(c, loc);
1441                 }
1442         }
1443 }
1444
1445 static void
1446 ntq_setup_outputs(struct vc4_compile *c)
1447 {
1448         nir_foreach_variable(var, &c->s->outputs) {
1449                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1450                 unsigned loc = var->data.driver_location * 4;
1451
1452                 assert(array_len == 1);
1453                 (void)array_len;
1454
1455                 for (int i = 0; i < 4; i++)
1456                         add_output(c, loc + i, var->data.location, i);
1457
1458                 if (c->stage == QSTAGE_FRAG) {
1459                         switch (var->data.location) {
1460                         case FRAG_RESULT_COLOR:
1461                         case FRAG_RESULT_DATA0:
1462                                 c->output_color_index = loc;
1463                                 break;
1464                         case FRAG_RESULT_DEPTH:
1465                                 c->output_position_index = loc;
1466                                 break;
1467                         case FRAG_RESULT_SAMPLE_MASK:
1468                                 c->output_sample_mask_index = loc;
1469                                 break;
1470                         }
1471                 } else {
1472                         switch (var->data.location) {
1473                         case VARYING_SLOT_POS:
1474                                 c->output_position_index = loc;
1475                                 break;
1476                         case VARYING_SLOT_PSIZ:
1477                                 c->output_point_size_index = loc;
1478                                 break;
1479                         }
1480                 }
1481         }
1482 }
1483
1484 static void
1485 ntq_setup_uniforms(struct vc4_compile *c)
1486 {
1487         nir_foreach_variable(var, &c->s->uniforms) {
1488                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1489                 unsigned array_elem_size = 4 * sizeof(float);
1490
1491                 declare_uniform_range(c, var->data.driver_location * array_elem_size,
1492                                       array_len * array_elem_size);
1493
1494         }
1495 }
1496
1497 /**
1498  * Sets up the mapping from nir_register to struct qreg *.
1499  *
1500  * Each nir_register gets a struct qreg per 32-bit component being stored.
1501  */
1502 static void
1503 ntq_setup_registers(struct vc4_compile *c, struct exec_list *list)
1504 {
1505         foreach_list_typed(nir_register, nir_reg, node, list) {
1506                 unsigned array_len = MAX2(nir_reg->num_array_elems, 1);
1507                 struct qreg *qregs = ralloc_array(c->def_ht, struct qreg,
1508                                                   array_len *
1509                                                   nir_reg->num_components);
1510
1511                 _mesa_hash_table_insert(c->def_ht, nir_reg, qregs);
1512
1513                 for (int i = 0; i < array_len * nir_reg->num_components; i++)
1514                         qregs[i] = qir_uniform_ui(c, 0);
1515         }
1516 }
1517
1518 static void
1519 ntq_emit_load_const(struct vc4_compile *c, nir_load_const_instr *instr)
1520 {
1521         struct qreg *qregs = ntq_init_ssa_def(c, &instr->def);
1522         for (int i = 0; i < instr->def.num_components; i++)
1523                 qregs[i] = qir_uniform_ui(c, instr->value.u32[i]);
1524
1525         _mesa_hash_table_insert(c->def_ht, &instr->def, qregs);
1526 }
1527
1528 static void
1529 ntq_emit_ssa_undef(struct vc4_compile *c, nir_ssa_undef_instr *instr)
1530 {
1531         struct qreg *qregs = ntq_init_ssa_def(c, &instr->def);
1532
1533         /* QIR needs there to be *some* value, so pick 0 (same as for
1534          * ntq_setup_registers().
1535          */
1536         for (int i = 0; i < instr->def.num_components; i++)
1537                 qregs[i] = qir_uniform_ui(c, 0);
1538 }
1539
1540 static void
1541 ntq_emit_intrinsic(struct vc4_compile *c, nir_intrinsic_instr *instr)
1542 {
1543         const nir_intrinsic_info *info = &nir_intrinsic_infos[instr->intrinsic];
1544         nir_const_value *const_offset;
1545         unsigned offset;
1546         struct qreg *dest = NULL;
1547
1548         if (info->has_dest) {
1549                 dest = ntq_get_dest(c, &instr->dest);
1550         }
1551
1552         switch (instr->intrinsic) {
1553         case nir_intrinsic_load_uniform:
1554                 assert(instr->num_components == 1);
1555                 const_offset = nir_src_as_const_value(instr->src[0]);
1556                 if (const_offset) {
1557                         offset = instr->const_index[0] + const_offset->u32[0];
1558                         assert(offset % 4 == 0);
1559                         /* We need dwords */
1560                         offset = offset / 4;
1561                         if (offset < VC4_NIR_STATE_UNIFORM_OFFSET) {
1562                                 *dest = qir_uniform(c, QUNIFORM_UNIFORM,
1563                                                     offset);
1564                         } else {
1565                                 *dest = qir_uniform(c, offset -
1566                                                     VC4_NIR_STATE_UNIFORM_OFFSET,
1567                                                     0);
1568                         }
1569                 } else {
1570                         *dest = indirect_uniform_load(c, instr);
1571                 }
1572                 break;
1573
1574         case nir_intrinsic_load_user_clip_plane:
1575                 for (int i = 0; i < instr->num_components; i++) {
1576                         dest[i] = qir_uniform(c, QUNIFORM_USER_CLIP_PLANE,
1577                                               instr->const_index[0] * 4 + i);
1578                 }
1579                 break;
1580
1581         case nir_intrinsic_load_sample_mask_in:
1582                 *dest = qir_uniform(c, QUNIFORM_SAMPLE_MASK, 0);
1583                 break;
1584
1585         case nir_intrinsic_load_input:
1586                 assert(instr->num_components == 1);
1587                 const_offset = nir_src_as_const_value(instr->src[0]);
1588                 assert(const_offset && "vc4 doesn't support indirect inputs");
1589                 if (instr->const_index[0] >= VC4_NIR_TLB_COLOR_READ_INPUT) {
1590                         assert(const_offset->u32[0] == 0);
1591                         /* Reads of the per-sample color need to be done in
1592                          * order.
1593                          */
1594                         int sample_index = (instr->const_index[0] -
1595                                            VC4_NIR_TLB_COLOR_READ_INPUT);
1596                         for (int i = 0; i <= sample_index; i++) {
1597                                 if (c->color_reads[i].file == QFILE_NULL) {
1598                                         c->color_reads[i] =
1599                                                 qir_TLB_COLOR_READ(c);
1600                                 }
1601                         }
1602                         *dest = c->color_reads[sample_index];
1603                 } else {
1604                         offset = instr->const_index[0] + const_offset->u32[0];
1605                         *dest = c->inputs[offset];
1606                 }
1607                 break;
1608
1609         case nir_intrinsic_store_output:
1610                 const_offset = nir_src_as_const_value(instr->src[1]);
1611                 assert(const_offset && "vc4 doesn't support indirect outputs");
1612                 offset = instr->const_index[0] + const_offset->u32[0];
1613
1614                 /* MSAA color outputs are the only case where we have an
1615                  * output that's not lowered to being a store of a single 32
1616                  * bit value.
1617                  */
1618                 if (c->stage == QSTAGE_FRAG && instr->num_components == 4) {
1619                         assert(offset == c->output_color_index);
1620                         for (int i = 0; i < 4; i++) {
1621                                 c->sample_colors[i] =
1622                                         qir_MOV(c, ntq_get_src(c, instr->src[0],
1623                                                                i));
1624                         }
1625                 } else {
1626                         assert(instr->num_components == 1);
1627                         c->outputs[offset] =
1628                                 qir_MOV(c, ntq_get_src(c, instr->src[0], 0));
1629                         c->num_outputs = MAX2(c->num_outputs, offset + 1);
1630                 }
1631                 break;
1632
1633         case nir_intrinsic_discard:
1634                 c->discard = qir_uniform_ui(c, ~0);
1635                 break;
1636
1637         case nir_intrinsic_discard_if:
1638                 if (c->discard.file == QFILE_NULL)
1639                         c->discard = qir_uniform_ui(c, 0);
1640                 c->discard = qir_OR(c, c->discard,
1641                                     ntq_get_src(c, instr->src[0], 0));
1642                 break;
1643
1644         default:
1645                 fprintf(stderr, "Unknown intrinsic: ");
1646                 nir_print_instr(&instr->instr, stderr);
1647                 fprintf(stderr, "\n");
1648                 break;
1649         }
1650 }
1651
1652 static void
1653 ntq_emit_if(struct vc4_compile *c, nir_if *if_stmt)
1654 {
1655         fprintf(stderr, "general IF statements not handled.\n");
1656 }
1657
1658 static void
1659 ntq_emit_instr(struct vc4_compile *c, nir_instr *instr)
1660 {
1661         switch (instr->type) {
1662         case nir_instr_type_alu:
1663                 ntq_emit_alu(c, nir_instr_as_alu(instr));
1664                 break;
1665
1666         case nir_instr_type_intrinsic:
1667                 ntq_emit_intrinsic(c, nir_instr_as_intrinsic(instr));
1668                 break;
1669
1670         case nir_instr_type_load_const:
1671                 ntq_emit_load_const(c, nir_instr_as_load_const(instr));
1672                 break;
1673
1674         case nir_instr_type_ssa_undef:
1675                 ntq_emit_ssa_undef(c, nir_instr_as_ssa_undef(instr));
1676                 break;
1677
1678         case nir_instr_type_tex:
1679                 ntq_emit_tex(c, nir_instr_as_tex(instr));
1680                 break;
1681
1682         default:
1683                 fprintf(stderr, "Unknown NIR instr type: ");
1684                 nir_print_instr(instr, stderr);
1685                 fprintf(stderr, "\n");
1686                 abort();
1687         }
1688 }
1689
1690 static void
1691 ntq_emit_block(struct vc4_compile *c, nir_block *block)
1692 {
1693         nir_foreach_instr(block, instr) {
1694                 ntq_emit_instr(c, instr);
1695         }
1696 }
1697
1698 static void ntq_emit_cf_list(struct vc4_compile *c, struct exec_list *list);
1699
1700 static void
1701 ntq_emit_loop(struct vc4_compile *c, nir_loop *nloop)
1702 {
1703         fprintf(stderr, "LOOPS not fully handled. Rendering errors likely.\n");
1704         ntq_emit_cf_list(c, &nloop->body);
1705 }
1706
1707 static void
1708 ntq_emit_function(struct vc4_compile *c, nir_function_impl *func)
1709 {
1710         fprintf(stderr, "FUNCTIONS not handled.\n");
1711         abort();
1712 }
1713
1714 static void
1715 ntq_emit_cf_list(struct vc4_compile *c, struct exec_list *list)
1716 {
1717         foreach_list_typed(nir_cf_node, node, node, list) {
1718                 switch (node->type) {
1719                 case nir_cf_node_block:
1720                         ntq_emit_block(c, nir_cf_node_as_block(node));
1721                         break;
1722
1723                 case nir_cf_node_if:
1724                         ntq_emit_if(c, nir_cf_node_as_if(node));
1725                         break;
1726
1727                 case nir_cf_node_loop:
1728                         ntq_emit_loop(c, nir_cf_node_as_loop(node));
1729                         break;
1730
1731                 case nir_cf_node_function:
1732                         ntq_emit_function(c, nir_cf_node_as_function(node));
1733                         break;
1734
1735                 default:
1736                         fprintf(stderr, "Unknown NIR node type\n");
1737                         abort();
1738                 }
1739         }
1740 }
1741
1742 static void
1743 ntq_emit_impl(struct vc4_compile *c, nir_function_impl *impl)
1744 {
1745         ntq_setup_registers(c, &impl->registers);
1746         ntq_emit_cf_list(c, &impl->body);
1747 }
1748
1749 static void
1750 nir_to_qir(struct vc4_compile *c)
1751 {
1752         ntq_setup_inputs(c);
1753         ntq_setup_outputs(c);
1754         ntq_setup_uniforms(c);
1755         ntq_setup_registers(c, &c->s->registers);
1756
1757         /* Find the main function and emit the body. */
1758         nir_foreach_function(c->s, function) {
1759                 assert(strcmp(function->name, "main") == 0);
1760                 assert(function->impl);
1761                 ntq_emit_impl(c, function->impl);
1762         }
1763 }
1764
1765 static const nir_shader_compiler_options nir_options = {
1766         .lower_extract_byte = true,
1767         .lower_extract_word = true,
1768         .lower_ffma = true,
1769         .lower_flrp = true,
1770         .lower_fpow = true,
1771         .lower_fsat = true,
1772         .lower_fsqrt = true,
1773         .lower_negate = true,
1774 };
1775
1776 static bool
1777 count_nir_instrs_in_block(nir_block *block, void *state)
1778 {
1779         int *count = (int *) state;
1780         nir_foreach_instr(block, instr) {
1781                 *count = *count + 1;
1782         }
1783         return true;
1784 }
1785
1786 static int
1787 count_nir_instrs(nir_shader *nir)
1788 {
1789         int count = 0;
1790         nir_foreach_function(nir, function) {
1791                 if (!function->impl)
1792                         continue;
1793                 nir_foreach_block(function->impl, count_nir_instrs_in_block, &count);
1794         }
1795         return count;
1796 }
1797
1798 static struct vc4_compile *
1799 vc4_shader_ntq(struct vc4_context *vc4, enum qstage stage,
1800                        struct vc4_key *key)
1801 {
1802         struct vc4_compile *c = qir_compile_init();
1803
1804         c->stage = stage;
1805         c->shader_state = &key->shader_state->base;
1806         c->program_id = key->shader_state->program_id;
1807         c->variant_id = key->shader_state->compiled_variant_count++;
1808
1809         c->key = key;
1810         switch (stage) {
1811         case QSTAGE_FRAG:
1812                 c->fs_key = (struct vc4_fs_key *)key;
1813                 if (c->fs_key->is_points) {
1814                         c->point_x = emit_fragment_varying(c, ~0, 0);
1815                         c->point_y = emit_fragment_varying(c, ~0, 0);
1816                 } else if (c->fs_key->is_lines) {
1817                         c->line_x = emit_fragment_varying(c, ~0, 0);
1818                 }
1819                 break;
1820         case QSTAGE_VERT:
1821                 c->vs_key = (struct vc4_vs_key *)key;
1822                 break;
1823         case QSTAGE_COORD:
1824                 c->vs_key = (struct vc4_vs_key *)key;
1825                 break;
1826         }
1827
1828         const struct tgsi_token *tokens = key->shader_state->base.tokens;
1829
1830         if (vc4_debug & VC4_DEBUG_TGSI) {
1831                 fprintf(stderr, "%s prog %d/%d TGSI:\n",
1832                         qir_get_stage_name(c->stage),
1833                         c->program_id, c->variant_id);
1834                 tgsi_dump(tokens, 0);
1835         }
1836
1837         c->s = tgsi_to_nir(tokens, &nir_options);
1838         NIR_PASS_V(c->s, nir_opt_global_to_local);
1839         NIR_PASS_V(c->s, nir_convert_to_ssa);
1840
1841         if (stage == QSTAGE_FRAG)
1842                 NIR_PASS_V(c->s, vc4_nir_lower_blend, c);
1843
1844         struct nir_lower_tex_options tex_options = {
1845                 /* We would need to implement txs, but we don't want the
1846                  * int/float conversions
1847                  */
1848                 .lower_rect = false,
1849
1850                 /* We want to use this, but we don't want to newton-raphson
1851                  * its rcp.
1852                  */
1853                 .lower_txp = false,
1854
1855                 /* Apply swizzles to all samplers. */
1856                 .swizzle_result = ~0,
1857         };
1858
1859         /* Lower the format swizzle and ARB_texture_swizzle-style swizzle.
1860          * The format swizzling applies before sRGB decode, and
1861          * ARB_texture_swizzle is the last thing before returning the sample.
1862          */
1863         for (int i = 0; i < ARRAY_SIZE(key->tex); i++) {
1864                 enum pipe_format format = c->key->tex[i].format;
1865
1866                 if (!format)
1867                         continue;
1868
1869                 const uint8_t *format_swizzle = vc4_get_format_swizzle(format);
1870
1871                 for (int j = 0; j < 4; j++) {
1872                         uint8_t arb_swiz = c->key->tex[i].swizzle[j];
1873
1874                         if (arb_swiz <= 3) {
1875                                 tex_options.swizzles[i][j] =
1876                                         format_swizzle[arb_swiz];
1877                         } else {
1878                                 tex_options.swizzles[i][j] = arb_swiz;
1879                         }
1880
1881                         /* If ARB_texture_swizzle is reading from the R, G, or
1882                          * B channels of an sRGB texture, then we need to
1883                          * apply sRGB decode to this channel at sample time.
1884                          */
1885                         if (arb_swiz < 3 && util_format_is_srgb(format)) {
1886                                 c->tex_srgb_decode[i] |= (1 << j);
1887                         }
1888
1889                 }
1890         }
1891
1892         NIR_PASS_V(c->s, nir_lower_tex, &tex_options);
1893
1894         if (c->fs_key && c->fs_key->light_twoside)
1895                 NIR_PASS_V(c->s, nir_lower_two_sided_color);
1896
1897         if (stage == QSTAGE_FRAG)
1898                 NIR_PASS_V(c->s, nir_lower_clip_fs, c->key->ucp_enables);
1899         else
1900                 NIR_PASS_V(c->s, nir_lower_clip_vs, c->key->ucp_enables);
1901
1902         NIR_PASS_V(c->s, vc4_nir_lower_io, c);
1903         NIR_PASS_V(c->s, vc4_nir_lower_txf_ms, c);
1904         NIR_PASS_V(c->s, nir_lower_idiv);
1905         NIR_PASS_V(c->s, nir_lower_load_const_to_scalar);
1906
1907         vc4_optimize_nir(c->s);
1908
1909         NIR_PASS_V(c->s, nir_remove_dead_variables);
1910         NIR_PASS_V(c->s, nir_convert_from_ssa, true);
1911
1912         if (vc4_debug & VC4_DEBUG_SHADERDB) {
1913                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d NIR instructions\n",
1914                         qir_get_stage_name(c->stage),
1915                         c->program_id, c->variant_id,
1916                         count_nir_instrs(c->s));
1917         }
1918
1919         if (vc4_debug & VC4_DEBUG_NIR) {
1920                 fprintf(stderr, "%s prog %d/%d NIR:\n",
1921                         qir_get_stage_name(c->stage),
1922                         c->program_id, c->variant_id);
1923                 nir_print_shader(c->s, stderr);
1924         }
1925
1926         nir_to_qir(c);
1927
1928         switch (stage) {
1929         case QSTAGE_FRAG:
1930                 emit_frag_end(c);
1931                 break;
1932         case QSTAGE_VERT:
1933                 emit_vert_end(c,
1934                               vc4->prog.fs->input_slots,
1935                               vc4->prog.fs->num_inputs);
1936                 break;
1937         case QSTAGE_COORD:
1938                 emit_coord_end(c);
1939                 break;
1940         }
1941
1942         if (vc4_debug & VC4_DEBUG_QIR) {
1943                 fprintf(stderr, "%s prog %d/%d pre-opt QIR:\n",
1944                         qir_get_stage_name(c->stage),
1945                         c->program_id, c->variant_id);
1946                 qir_dump(c);
1947         }
1948
1949         qir_optimize(c);
1950         qir_lower_uniforms(c);
1951
1952         qir_schedule_instructions(c);
1953
1954         if (vc4_debug & VC4_DEBUG_QIR) {
1955                 fprintf(stderr, "%s prog %d/%d QIR:\n",
1956                         qir_get_stage_name(c->stage),
1957                         c->program_id, c->variant_id);
1958                 qir_dump(c);
1959         }
1960
1961         qir_reorder_uniforms(c);
1962         vc4_generate_code(vc4, c);
1963
1964         if (vc4_debug & VC4_DEBUG_SHADERDB) {
1965                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d instructions\n",
1966                         qir_get_stage_name(c->stage),
1967                         c->program_id, c->variant_id,
1968                         c->qpu_inst_count);
1969                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d uniforms\n",
1970                         qir_get_stage_name(c->stage),
1971                         c->program_id, c->variant_id,
1972                         c->num_uniforms);
1973         }
1974
1975         ralloc_free(c->s);
1976
1977         return c;
1978 }
1979
1980 static void *
1981 vc4_shader_state_create(struct pipe_context *pctx,
1982                         const struct pipe_shader_state *cso)
1983 {
1984         struct vc4_context *vc4 = vc4_context(pctx);
1985         struct vc4_uncompiled_shader *so = CALLOC_STRUCT(vc4_uncompiled_shader);
1986         if (!so)
1987                 return NULL;
1988
1989         so->base.tokens = tgsi_dup_tokens(cso->tokens);
1990         so->program_id = vc4->next_uncompiled_program_id++;
1991
1992         return so;
1993 }
1994
1995 static void
1996 copy_uniform_state_to_shader(struct vc4_compiled_shader *shader,
1997                              struct vc4_compile *c)
1998 {
1999         int count = c->num_uniforms;
2000         struct vc4_shader_uniform_info *uinfo = &shader->uniforms;
2001
2002         uinfo->count = count;
2003         uinfo->data = ralloc_array(shader, uint32_t, count);
2004         memcpy(uinfo->data, c->uniform_data,
2005                count * sizeof(*uinfo->data));
2006         uinfo->contents = ralloc_array(shader, enum quniform_contents, count);
2007         memcpy(uinfo->contents, c->uniform_contents,
2008                count * sizeof(*uinfo->contents));
2009         uinfo->num_texture_samples = c->num_texture_samples;
2010
2011         vc4_set_shader_uniform_dirty_flags(shader);
2012 }
2013
2014 static struct vc4_compiled_shader *
2015 vc4_get_compiled_shader(struct vc4_context *vc4, enum qstage stage,
2016                         struct vc4_key *key)
2017 {
2018         struct hash_table *ht;
2019         uint32_t key_size;
2020         if (stage == QSTAGE_FRAG) {
2021                 ht = vc4->fs_cache;
2022                 key_size = sizeof(struct vc4_fs_key);
2023         } else {
2024                 ht = vc4->vs_cache;
2025                 key_size = sizeof(struct vc4_vs_key);
2026         }
2027
2028         struct vc4_compiled_shader *shader;
2029         struct hash_entry *entry = _mesa_hash_table_search(ht, key);
2030         if (entry)
2031                 return entry->data;
2032
2033         struct vc4_compile *c = vc4_shader_ntq(vc4, stage, key);
2034         shader = rzalloc(NULL, struct vc4_compiled_shader);
2035
2036         shader->program_id = vc4->next_compiled_program_id++;
2037         if (stage == QSTAGE_FRAG) {
2038                 bool input_live[c->num_input_slots];
2039
2040                 memset(input_live, 0, sizeof(input_live));
2041                 list_for_each_entry(struct qinst, inst, &c->instructions, link) {
2042                         for (int i = 0; i < qir_get_op_nsrc(inst->op); i++) {
2043                                 if (inst->src[i].file == QFILE_VARY)
2044                                         input_live[inst->src[i].index] = true;
2045                         }
2046                 }
2047
2048                 shader->input_slots = ralloc_array(shader,
2049                                                    struct vc4_varying_slot,
2050                                                    c->num_input_slots);
2051
2052                 for (int i = 0; i < c->num_input_slots; i++) {
2053                         struct vc4_varying_slot *slot = &c->input_slots[i];
2054
2055                         if (!input_live[i])
2056                                 continue;
2057
2058                         /* Skip non-VS-output inputs. */
2059                         if (slot->slot == (uint8_t)~0)
2060                                 continue;
2061
2062                         if (slot->slot == VARYING_SLOT_COL0 ||
2063                             slot->slot == VARYING_SLOT_COL1 ||
2064                             slot->slot == VARYING_SLOT_BFC0 ||
2065                             slot->slot == VARYING_SLOT_BFC1) {
2066                                 shader->color_inputs |= (1 << shader->num_inputs);
2067                         }
2068
2069                         shader->input_slots[shader->num_inputs] = *slot;
2070                         shader->num_inputs++;
2071                 }
2072         } else {
2073                 shader->num_inputs = c->num_inputs;
2074
2075                 shader->vattr_offsets[0] = 0;
2076                 for (int i = 0; i < 8; i++) {
2077                         shader->vattr_offsets[i + 1] =
2078                                 shader->vattr_offsets[i] + c->vattr_sizes[i];
2079
2080                         if (c->vattr_sizes[i])
2081                                 shader->vattrs_live |= (1 << i);
2082                 }
2083         }
2084
2085         copy_uniform_state_to_shader(shader, c);
2086         shader->bo = vc4_bo_alloc_shader(vc4->screen, c->qpu_insts,
2087                                          c->qpu_inst_count * sizeof(uint64_t));
2088
2089         /* Copy the compiler UBO range state to the compiled shader, dropping
2090          * out arrays that were never referenced by an indirect load.
2091          *
2092          * (Note that QIR dead code elimination of an array access still
2093          * leaves that array alive, though)
2094          */
2095         if (c->num_ubo_ranges) {
2096                 shader->num_ubo_ranges = c->num_ubo_ranges;
2097                 shader->ubo_ranges = ralloc_array(shader, struct vc4_ubo_range,
2098                                                   c->num_ubo_ranges);
2099                 uint32_t j = 0;
2100                 for (int i = 0; i < c->num_uniform_ranges; i++) {
2101                         struct vc4_compiler_ubo_range *range =
2102                                 &c->ubo_ranges[i];
2103                         if (!range->used)
2104                                 continue;
2105
2106                         shader->ubo_ranges[j].dst_offset = range->dst_offset;
2107                         shader->ubo_ranges[j].src_offset = range->src_offset;
2108                         shader->ubo_ranges[j].size = range->size;
2109                         shader->ubo_size += c->ubo_ranges[i].size;
2110                         j++;
2111                 }
2112         }
2113         if (shader->ubo_size) {
2114                 if (vc4_debug & VC4_DEBUG_SHADERDB) {
2115                         fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d UBO uniforms\n",
2116                                 qir_get_stage_name(c->stage),
2117                                 c->program_id, c->variant_id,
2118                                 shader->ubo_size / 4);
2119                 }
2120         }
2121
2122         qir_compile_destroy(c);
2123
2124         struct vc4_key *dup_key;
2125         dup_key = ralloc_size(shader, key_size);
2126         memcpy(dup_key, key, key_size);
2127         _mesa_hash_table_insert(ht, dup_key, shader);
2128
2129         return shader;
2130 }
2131
2132 static void
2133 vc4_setup_shared_key(struct vc4_context *vc4, struct vc4_key *key,
2134                      struct vc4_texture_stateobj *texstate)
2135 {
2136         for (int i = 0; i < texstate->num_textures; i++) {
2137                 struct pipe_sampler_view *sampler = texstate->textures[i];
2138                 struct pipe_sampler_state *sampler_state =
2139                         texstate->samplers[i];
2140
2141                 if (!sampler)
2142                         continue;
2143
2144                 key->tex[i].format = sampler->format;
2145                 key->tex[i].swizzle[0] = sampler->swizzle_r;
2146                 key->tex[i].swizzle[1] = sampler->swizzle_g;
2147                 key->tex[i].swizzle[2] = sampler->swizzle_b;
2148                 key->tex[i].swizzle[3] = sampler->swizzle_a;
2149
2150                 if (sampler->texture->nr_samples > 1) {
2151                         key->tex[i].msaa_width = sampler->texture->width0;
2152                         key->tex[i].msaa_height = sampler->texture->height0;
2153                 } else if (sampler){
2154                         key->tex[i].compare_mode = sampler_state->compare_mode;
2155                         key->tex[i].compare_func = sampler_state->compare_func;
2156                         key->tex[i].wrap_s = sampler_state->wrap_s;
2157                         key->tex[i].wrap_t = sampler_state->wrap_t;
2158                 }
2159         }
2160
2161         key->ucp_enables = vc4->rasterizer->base.clip_plane_enable;
2162 }
2163
2164 static void
2165 vc4_update_compiled_fs(struct vc4_context *vc4, uint8_t prim_mode)
2166 {
2167         struct vc4_fs_key local_key;
2168         struct vc4_fs_key *key = &local_key;
2169
2170         if (!(vc4->dirty & (VC4_DIRTY_PRIM_MODE |
2171                             VC4_DIRTY_BLEND |
2172                             VC4_DIRTY_FRAMEBUFFER |
2173                             VC4_DIRTY_ZSA |
2174                             VC4_DIRTY_RASTERIZER |
2175                             VC4_DIRTY_FRAGTEX |
2176                             VC4_DIRTY_TEXSTATE |
2177                             VC4_DIRTY_UNCOMPILED_FS))) {
2178                 return;
2179         }
2180
2181         memset(key, 0, sizeof(*key));
2182         vc4_setup_shared_key(vc4, &key->base, &vc4->fragtex);
2183         key->base.shader_state = vc4->prog.bind_fs;
2184         key->is_points = (prim_mode == PIPE_PRIM_POINTS);
2185         key->is_lines = (prim_mode >= PIPE_PRIM_LINES &&
2186                          prim_mode <= PIPE_PRIM_LINE_STRIP);
2187         key->blend = vc4->blend->rt[0];
2188         if (vc4->blend->logicop_enable) {
2189                 key->logicop_func = vc4->blend->logicop_func;
2190         } else {
2191                 key->logicop_func = PIPE_LOGICOP_COPY;
2192         }
2193         key->msaa = vc4->rasterizer->base.multisample;
2194         key->sample_coverage = (vc4->rasterizer->base.multisample &&
2195                                 vc4->sample_mask != (1 << VC4_MAX_SAMPLES) - 1);
2196         key->sample_alpha_to_coverage = vc4->blend->alpha_to_coverage;
2197         key->sample_alpha_to_one = vc4->blend->alpha_to_one;
2198         if (vc4->framebuffer.cbufs[0])
2199                 key->color_format = vc4->framebuffer.cbufs[0]->format;
2200
2201         key->stencil_enabled = vc4->zsa->stencil_uniforms[0] != 0;
2202         key->stencil_twoside = vc4->zsa->stencil_uniforms[1] != 0;
2203         key->stencil_full_writemasks = vc4->zsa->stencil_uniforms[2] != 0;
2204         key->depth_enabled = (vc4->zsa->base.depth.enabled ||
2205                               key->stencil_enabled);
2206         if (vc4->zsa->base.alpha.enabled) {
2207                 key->alpha_test = true;
2208                 key->alpha_test_func = vc4->zsa->base.alpha.func;
2209         }
2210
2211         if (key->is_points) {
2212                 key->point_sprite_mask =
2213                         vc4->rasterizer->base.sprite_coord_enable;
2214                 key->point_coord_upper_left =
2215                         (vc4->rasterizer->base.sprite_coord_mode ==
2216                          PIPE_SPRITE_COORD_UPPER_LEFT);
2217         }
2218
2219         key->light_twoside = vc4->rasterizer->base.light_twoside;
2220
2221         struct vc4_compiled_shader *old_fs = vc4->prog.fs;
2222         vc4->prog.fs = vc4_get_compiled_shader(vc4, QSTAGE_FRAG, &key->base);
2223         if (vc4->prog.fs == old_fs)
2224                 return;
2225
2226         vc4->dirty |= VC4_DIRTY_COMPILED_FS;
2227         if (vc4->rasterizer->base.flatshade &&
2228             old_fs && vc4->prog.fs->color_inputs != old_fs->color_inputs) {
2229                 vc4->dirty |= VC4_DIRTY_FLAT_SHADE_FLAGS;
2230         }
2231 }
2232
2233 static void
2234 vc4_update_compiled_vs(struct vc4_context *vc4, uint8_t prim_mode)
2235 {
2236         struct vc4_vs_key local_key;
2237         struct vc4_vs_key *key = &local_key;
2238
2239         if (!(vc4->dirty & (VC4_DIRTY_PRIM_MODE |
2240                             VC4_DIRTY_RASTERIZER |
2241                             VC4_DIRTY_VERTTEX |
2242                             VC4_DIRTY_TEXSTATE |
2243                             VC4_DIRTY_VTXSTATE |
2244                             VC4_DIRTY_UNCOMPILED_VS |
2245                             VC4_DIRTY_COMPILED_FS))) {
2246                 return;
2247         }
2248
2249         memset(key, 0, sizeof(*key));
2250         vc4_setup_shared_key(vc4, &key->base, &vc4->verttex);
2251         key->base.shader_state = vc4->prog.bind_vs;
2252         key->compiled_fs_id = vc4->prog.fs->program_id;
2253
2254         for (int i = 0; i < ARRAY_SIZE(key->attr_formats); i++)
2255                 key->attr_formats[i] = vc4->vtx->pipe[i].src_format;
2256
2257         key->per_vertex_point_size =
2258                 (prim_mode == PIPE_PRIM_POINTS &&
2259                  vc4->rasterizer->base.point_size_per_vertex);
2260
2261         struct vc4_compiled_shader *vs =
2262                 vc4_get_compiled_shader(vc4, QSTAGE_VERT, &key->base);
2263         if (vs != vc4->prog.vs) {
2264                 vc4->prog.vs = vs;
2265                 vc4->dirty |= VC4_DIRTY_COMPILED_VS;
2266         }
2267
2268         key->is_coord = true;
2269         struct vc4_compiled_shader *cs =
2270                 vc4_get_compiled_shader(vc4, QSTAGE_COORD, &key->base);
2271         if (cs != vc4->prog.cs) {
2272                 vc4->prog.cs = cs;
2273                 vc4->dirty |= VC4_DIRTY_COMPILED_CS;
2274         }
2275 }
2276
2277 void
2278 vc4_update_compiled_shaders(struct vc4_context *vc4, uint8_t prim_mode)
2279 {
2280         vc4_update_compiled_fs(vc4, prim_mode);
2281         vc4_update_compiled_vs(vc4, prim_mode);
2282 }
2283
2284 static uint32_t
2285 fs_cache_hash(const void *key)
2286 {
2287         return _mesa_hash_data(key, sizeof(struct vc4_fs_key));
2288 }
2289
2290 static uint32_t
2291 vs_cache_hash(const void *key)
2292 {
2293         return _mesa_hash_data(key, sizeof(struct vc4_vs_key));
2294 }
2295
2296 static bool
2297 fs_cache_compare(const void *key1, const void *key2)
2298 {
2299         return memcmp(key1, key2, sizeof(struct vc4_fs_key)) == 0;
2300 }
2301
2302 static bool
2303 vs_cache_compare(const void *key1, const void *key2)
2304 {
2305         return memcmp(key1, key2, sizeof(struct vc4_vs_key)) == 0;
2306 }
2307
2308 static void
2309 delete_from_cache_if_matches(struct hash_table *ht,
2310                              struct hash_entry *entry,
2311                              struct vc4_uncompiled_shader *so)
2312 {
2313         const struct vc4_key *key = entry->key;
2314
2315         if (key->shader_state == so) {
2316                 struct vc4_compiled_shader *shader = entry->data;
2317                 _mesa_hash_table_remove(ht, entry);
2318                 vc4_bo_unreference(&shader->bo);
2319                 ralloc_free(shader);
2320         }
2321 }
2322
2323 static void
2324 vc4_shader_state_delete(struct pipe_context *pctx, void *hwcso)
2325 {
2326         struct vc4_context *vc4 = vc4_context(pctx);
2327         struct vc4_uncompiled_shader *so = hwcso;
2328
2329         struct hash_entry *entry;
2330         hash_table_foreach(vc4->fs_cache, entry)
2331                 delete_from_cache_if_matches(vc4->fs_cache, entry, so);
2332         hash_table_foreach(vc4->vs_cache, entry)
2333                 delete_from_cache_if_matches(vc4->vs_cache, entry, so);
2334
2335         free((void *)so->base.tokens);
2336         free(so);
2337 }
2338
2339 static void
2340 vc4_fp_state_bind(struct pipe_context *pctx, void *hwcso)
2341 {
2342         struct vc4_context *vc4 = vc4_context(pctx);
2343         vc4->prog.bind_fs = hwcso;
2344         vc4->dirty |= VC4_DIRTY_UNCOMPILED_FS;
2345 }
2346
2347 static void
2348 vc4_vp_state_bind(struct pipe_context *pctx, void *hwcso)
2349 {
2350         struct vc4_context *vc4 = vc4_context(pctx);
2351         vc4->prog.bind_vs = hwcso;
2352         vc4->dirty |= VC4_DIRTY_UNCOMPILED_VS;
2353 }
2354
2355 void
2356 vc4_program_init(struct pipe_context *pctx)
2357 {
2358         struct vc4_context *vc4 = vc4_context(pctx);
2359
2360         pctx->create_vs_state = vc4_shader_state_create;
2361         pctx->delete_vs_state = vc4_shader_state_delete;
2362
2363         pctx->create_fs_state = vc4_shader_state_create;
2364         pctx->delete_fs_state = vc4_shader_state_delete;
2365
2366         pctx->bind_fs_state = vc4_fp_state_bind;
2367         pctx->bind_vs_state = vc4_vp_state_bind;
2368
2369         vc4->fs_cache = _mesa_hash_table_create(pctx, fs_cache_hash,
2370                                                 fs_cache_compare);
2371         vc4->vs_cache = _mesa_hash_table_create(pctx, vs_cache_hash,
2372                                                 vs_cache_compare);
2373 }
2374
2375 void
2376 vc4_program_fini(struct pipe_context *pctx)
2377 {
2378         struct vc4_context *vc4 = vc4_context(pctx);
2379
2380         struct hash_entry *entry;
2381         hash_table_foreach(vc4->fs_cache, entry) {
2382                 struct vc4_compiled_shader *shader = entry->data;
2383                 vc4_bo_unreference(&shader->bo);
2384                 ralloc_free(shader);
2385                 _mesa_hash_table_remove(vc4->fs_cache, entry);
2386         }
2387
2388         hash_table_foreach(vc4->vs_cache, entry) {
2389                 struct vc4_compiled_shader *shader = entry->data;
2390                 vc4_bo_unreference(&shader->bo);
2391                 ralloc_free(shader);
2392                 _mesa_hash_table_remove(vc4->vs_cache, entry);
2393         }
2394 }