1 /*
2  * Copyright © 2011 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "brw_vec4.h"
25 #include "brw_fs.h"
26 #include "brw_cfg.h"
27 #include "brw_nir.h"
28 #include "brw_vec4_builder.h"
29 #include "brw_vec4_vs.h"
30 #include "brw_dead_control_flow.h"
31 #include "dev/gen_debug.h"
32 #include "program/prog_parameter.h"
33 #include "util/u_math.h"
34 
35 #define MAX_INSTRUCTION (1 << 30)
36 
37 using namespace brw;
38 
39 namespace brw {
40 
41 void
init()42 src_reg::init()
43 {
44    memset((void*)this, 0, sizeof(*this));
45    this->file = BAD_FILE;
46    this->type = BRW_REGISTER_TYPE_UD;
47 }
48 
src_reg(enum brw_reg_file file,int nr,const glsl_type * type)49 src_reg::src_reg(enum brw_reg_file file, int nr, const glsl_type *type)
50 {
51    init();
52 
53    this->file = file;
54    this->nr = nr;
55    if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
56       this->swizzle = brw_swizzle_for_size(type->vector_elements);
57    else
58       this->swizzle = BRW_SWIZZLE_XYZW;
59    if (type)
60       this->type = brw_type_for_base_type(type);
61 }
62 
63 /** Generic unset register constructor. */
src_reg()64 src_reg::src_reg()
65 {
66    init();
67 }
68 
src_reg(struct::brw_reg reg)69 src_reg::src_reg(struct ::brw_reg reg) :
70    backend_reg(reg)
71 {
72    this->offset = 0;
73    this->reladdr = NULL;
74 }
75 
src_reg(const dst_reg & reg)76 src_reg::src_reg(const dst_reg &reg) :
77    backend_reg(reg)
78 {
79    this->reladdr = reg.reladdr;
80    this->swizzle = brw_swizzle_for_mask(reg.writemask);
81 }
82 
83 void
init()84 dst_reg::init()
85 {
86    memset((void*)this, 0, sizeof(*this));
87    this->file = BAD_FILE;
88    this->type = BRW_REGISTER_TYPE_UD;
89    this->writemask = WRITEMASK_XYZW;
90 }
91 
dst_reg()92 dst_reg::dst_reg()
93 {
94    init();
95 }
96 
dst_reg(enum brw_reg_file file,int nr)97 dst_reg::dst_reg(enum brw_reg_file file, int nr)
98 {
99    init();
100 
101    this->file = file;
102    this->nr = nr;
103 }
104 
dst_reg(enum brw_reg_file file,int nr,const glsl_type * type,unsigned writemask)105 dst_reg::dst_reg(enum brw_reg_file file, int nr, const glsl_type *type,
106                  unsigned writemask)
107 {
108    init();
109 
110    this->file = file;
111    this->nr = nr;
112    this->type = brw_type_for_base_type(type);
113    this->writemask = writemask;
114 }
115 
dst_reg(enum brw_reg_file file,int nr,brw_reg_type type,unsigned writemask)116 dst_reg::dst_reg(enum brw_reg_file file, int nr, brw_reg_type type,
117                  unsigned writemask)
118 {
119    init();
120 
121    this->file = file;
122    this->nr = nr;
123    this->type = type;
124    this->writemask = writemask;
125 }
126 
dst_reg(struct::brw_reg reg)127 dst_reg::dst_reg(struct ::brw_reg reg) :
128    backend_reg(reg)
129 {
130    this->offset = 0;
131    this->reladdr = NULL;
132 }
133 
dst_reg(const src_reg & reg)134 dst_reg::dst_reg(const src_reg &reg) :
135    backend_reg(reg)
136 {
137    this->writemask = brw_mask_for_swizzle(reg.swizzle);
138    this->reladdr = reg.reladdr;
139 }
140 
141 bool
equals(const dst_reg & r) const142 dst_reg::equals(const dst_reg &r) const
143 {
144    return (this->backend_reg::equals(r) &&
145            (reladdr == r.reladdr ||
146             (reladdr && r.reladdr && reladdr->equals(*r.reladdr))));
147 }
148 
149 bool
is_send_from_grf() const150 vec4_instruction::is_send_from_grf() const
151 {
152    switch (opcode) {
153    case SHADER_OPCODE_SHADER_TIME_ADD:
154    case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
155    case VEC4_OPCODE_UNTYPED_ATOMIC:
156    case VEC4_OPCODE_UNTYPED_SURFACE_READ:
157    case VEC4_OPCODE_UNTYPED_SURFACE_WRITE:
158    case VEC4_OPCODE_URB_READ:
159    case TCS_OPCODE_URB_WRITE:
160    case TCS_OPCODE_RELEASE_INPUT:
161    case SHADER_OPCODE_BARRIER:
162       return true;
163    default:
164       return false;
165    }
166 }
167 
168 /**
169  * Returns true if this instruction's sources and destinations cannot
170  * safely be the same register.
171  *
172  * In most cases, a register can be written over safely by the same
173  * instruction that is its last use.  For a single instruction, the
174  * sources are dereferenced before writing of the destination starts
175  * (naturally).
176  *
177  * However, there are a few cases where this can be problematic:
178  *
179  * - Virtual opcodes that translate to multiple instructions in the
180  *   code generator: if src == dst and one instruction writes the
181  *   destination before a later instruction reads the source, then
182  *   src will have been clobbered.
183  *
184  * The register allocator uses this information to set up conflicts between
185  * GRF sources and the destination.
186  */
187 bool
has_source_and_destination_hazard() const188 vec4_instruction::has_source_and_destination_hazard() const
189 {
190    switch (opcode) {
191    case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
192    case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
193    case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
194       return true;
195    default:
196       /* 8-wide compressed DF operations are executed as two 4-wide operations,
197        * so we have a src/dst hazard if the first half of the instruction
198        * overwrites the source of the second half. Prevent this by marking
199        * compressed instructions as having src/dst hazards, so the register
200        * allocator assigns safe register regions for dst and srcs.
201        */
202       return size_written > REG_SIZE;
203    }
204 }
205 
206 unsigned
size_read(unsigned arg) const207 vec4_instruction::size_read(unsigned arg) const
208 {
209    switch (opcode) {
210    case SHADER_OPCODE_SHADER_TIME_ADD:
211    case VEC4_OPCODE_UNTYPED_ATOMIC:
212    case VEC4_OPCODE_UNTYPED_SURFACE_READ:
213    case VEC4_OPCODE_UNTYPED_SURFACE_WRITE:
214    case TCS_OPCODE_URB_WRITE:
215       if (arg == 0)
216          return mlen * REG_SIZE;
217       break;
218    case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
219       if (arg == 1)
220          return mlen * REG_SIZE;
221       break;
222    default:
223       break;
224    }
225 
226    switch (src[arg].file) {
227    case BAD_FILE:
228       return 0;
229    case IMM:
230    case UNIFORM:
231       return 4 * type_sz(src[arg].type);
232    default:
233       /* XXX - Represent actual vertical stride. */
234       return exec_size * type_sz(src[arg].type);
235    }
236 }
237 
238 bool
can_do_source_mods(const struct gen_device_info * devinfo)239 vec4_instruction::can_do_source_mods(const struct gen_device_info *devinfo)
240 {
241    if (devinfo->gen == 6 && is_math())
242       return false;
243 
244    if (is_send_from_grf())
245       return false;
246 
247    if (!backend_instruction::can_do_source_mods())
248       return false;
249 
250    return true;
251 }
252 
253 bool
can_do_cmod()254 vec4_instruction::can_do_cmod()
255 {
256    if (!backend_instruction::can_do_cmod())
257       return false;
258 
259    /* The accumulator result appears to get used for the conditional modifier
260     * generation.  When negating a UD value, there is a 33rd bit generated for
261     * the sign in the accumulator value, so now you can't check, for example,
262     * equality with a 32-bit value.  See piglit fs-op-neg-uvec4.
263     */
264    for (unsigned i = 0; i < 3; i++) {
265       if (src[i].file != BAD_FILE &&
266           type_is_unsigned_int(src[i].type) && src[i].negate)
267          return false;
268    }
269 
270    return true;
271 }
272 
273 bool
can_do_writemask(const struct gen_device_info * devinfo)274 vec4_instruction::can_do_writemask(const struct gen_device_info *devinfo)
275 {
276    switch (opcode) {
277    case SHADER_OPCODE_GEN4_SCRATCH_READ:
278    case VEC4_OPCODE_DOUBLE_TO_F32:
279    case VEC4_OPCODE_DOUBLE_TO_D32:
280    case VEC4_OPCODE_DOUBLE_TO_U32:
281    case VEC4_OPCODE_TO_DOUBLE:
282    case VEC4_OPCODE_PICK_LOW_32BIT:
283    case VEC4_OPCODE_PICK_HIGH_32BIT:
284    case VEC4_OPCODE_SET_LOW_32BIT:
285    case VEC4_OPCODE_SET_HIGH_32BIT:
286    case VS_OPCODE_PULL_CONSTANT_LOAD:
287    case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
288    case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
289    case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
290    case TES_OPCODE_CREATE_INPUT_READ_HEADER:
291    case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
292    case VEC4_OPCODE_URB_READ:
293    case SHADER_OPCODE_MOV_INDIRECT:
294       return false;
295    default:
296       /* The MATH instruction on Gen6 only executes in align1 mode, which does
297        * not support writemasking.
298        */
299       if (devinfo->gen == 6 && is_math())
300          return false;
301 
302       if (is_tex())
303          return false;
304 
305       return true;
306    }
307 }
308 
309 bool
can_change_types() const310 vec4_instruction::can_change_types() const
311 {
312    return dst.type == src[0].type &&
313           !src[0].abs && !src[0].negate && !saturate &&
314           (opcode == BRW_OPCODE_MOV ||
315            (opcode == BRW_OPCODE_SEL &&
316             dst.type == src[1].type &&
317             predicate != BRW_PREDICATE_NONE &&
318             !src[1].abs && !src[1].negate));
319 }
320 
321 /**
322  * Returns how many MRFs an opcode will write over.
323  *
324  * Note that this is not the 0 or 1 implied writes in an actual gen
325  * instruction -- the generate_* functions generate additional MOVs
326  * for setup.
327  */
328 unsigned
implied_mrf_writes() const329 vec4_instruction::implied_mrf_writes() const
330 {
331    if (mlen == 0 || is_send_from_grf())
332       return 0;
333 
334    switch (opcode) {
335    case SHADER_OPCODE_RCP:
336    case SHADER_OPCODE_RSQ:
337    case SHADER_OPCODE_SQRT:
338    case SHADER_OPCODE_EXP2:
339    case SHADER_OPCODE_LOG2:
340    case SHADER_OPCODE_SIN:
341    case SHADER_OPCODE_COS:
342       return 1;
343    case SHADER_OPCODE_INT_QUOTIENT:
344    case SHADER_OPCODE_INT_REMAINDER:
345    case SHADER_OPCODE_POW:
346    case TCS_OPCODE_THREAD_END:
347       return 2;
348    case VS_OPCODE_URB_WRITE:
349       return 1;
350    case VS_OPCODE_PULL_CONSTANT_LOAD:
351       return 2;
352    case SHADER_OPCODE_GEN4_SCRATCH_READ:
353       return 2;
354    case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
355       return 3;
356    case GS_OPCODE_URB_WRITE:
357    case GS_OPCODE_URB_WRITE_ALLOCATE:
358    case GS_OPCODE_THREAD_END:
359       return 0;
360    case GS_OPCODE_FF_SYNC:
361       return 1;
362    case TCS_OPCODE_URB_WRITE:
363       return 0;
364    case SHADER_OPCODE_SHADER_TIME_ADD:
365       return 0;
366    case SHADER_OPCODE_TEX:
367    case SHADER_OPCODE_TXL:
368    case SHADER_OPCODE_TXD:
369    case SHADER_OPCODE_TXF:
370    case SHADER_OPCODE_TXF_CMS:
371    case SHADER_OPCODE_TXF_CMS_W:
372    case SHADER_OPCODE_TXF_MCS:
373    case SHADER_OPCODE_TXS:
374    case SHADER_OPCODE_TG4:
375    case SHADER_OPCODE_TG4_OFFSET:
376    case SHADER_OPCODE_SAMPLEINFO:
377    case SHADER_OPCODE_GET_BUFFER_SIZE:
378       return header_size;
379    default:
380       unreachable("not reached");
381    }
382 }
383 
384 bool
equals(const src_reg & r) const385 src_reg::equals(const src_reg &r) const
386 {
387    return (this->backend_reg::equals(r) &&
388 	   !reladdr && !r.reladdr);
389 }
390 
391 bool
negative_equals(const src_reg & r) const392 src_reg::negative_equals(const src_reg &r) const
393 {
394    return this->backend_reg::negative_equals(r) &&
395           !reladdr && !r.reladdr;
396 }
397 
398 bool
opt_vector_float()399 vec4_visitor::opt_vector_float()
400 {
401    bool progress = false;
402 
403    foreach_block(block, cfg) {
404       unsigned last_reg = ~0u, last_offset = ~0u;
405       enum brw_reg_file last_reg_file = BAD_FILE;
406 
407       uint8_t imm[4] = { 0 };
408       int inst_count = 0;
409       vec4_instruction *imm_inst[4];
410       unsigned writemask = 0;
411       enum brw_reg_type dest_type = BRW_REGISTER_TYPE_F;
412 
413       foreach_inst_in_block_safe(vec4_instruction, inst, block) {
414          int vf = -1;
415          enum brw_reg_type need_type = BRW_REGISTER_TYPE_LAST;
416 
417          /* Look for unconditional MOVs from an immediate with a partial
418           * writemask.  Skip type-conversion MOVs other than integer 0,
419           * where the type doesn't matter.  See if the immediate can be
420           * represented as a VF.
421           */
422          if (inst->opcode == BRW_OPCODE_MOV &&
423              inst->src[0].file == IMM &&
424              inst->predicate == BRW_PREDICATE_NONE &&
425              inst->dst.writemask != WRITEMASK_XYZW &&
426              type_sz(inst->src[0].type) < 8 &&
427              (inst->src[0].type == inst->dst.type || inst->src[0].d == 0)) {
428 
429             vf = brw_float_to_vf(inst->src[0].d);
430             need_type = BRW_REGISTER_TYPE_D;
431 
432             if (vf == -1) {
433                vf = brw_float_to_vf(inst->src[0].f);
434                need_type = BRW_REGISTER_TYPE_F;
435             }
436          } else {
437             last_reg = ~0u;
438          }
439 
440          /* If this wasn't a MOV, or the destination register doesn't match,
441           * or we have to switch destination types, then this breaks our
442           * sequence.  Combine anything we've accumulated so far.
443           */
444          if (last_reg != inst->dst.nr ||
445              last_offset != inst->dst.offset ||
446              last_reg_file != inst->dst.file ||
447              (vf > 0 && dest_type != need_type)) {
448 
449             if (inst_count > 1) {
450                unsigned vf;
451                memcpy(&vf, imm, sizeof(vf));
452                vec4_instruction *mov = MOV(imm_inst[0]->dst, brw_imm_vf(vf));
453                mov->dst.type = dest_type;
454                mov->dst.writemask = writemask;
455                inst->insert_before(block, mov);
456 
457                for (int i = 0; i < inst_count; i++) {
458                   imm_inst[i]->remove(block);
459                }
460 
461                progress = true;
462             }
463 
464             inst_count = 0;
465             last_reg = ~0u;;
466             writemask = 0;
467             dest_type = BRW_REGISTER_TYPE_F;
468 
469             for (int i = 0; i < 4; i++) {
470                imm[i] = 0;
471             }
472          }
473 
474          /* Record this instruction's value (if it was representable). */
475          if (vf != -1) {
476             if ((inst->dst.writemask & WRITEMASK_X) != 0)
477                imm[0] = vf;
478             if ((inst->dst.writemask & WRITEMASK_Y) != 0)
479                imm[1] = vf;
480             if ((inst->dst.writemask & WRITEMASK_Z) != 0)
481                imm[2] = vf;
482             if ((inst->dst.writemask & WRITEMASK_W) != 0)
483                imm[3] = vf;
484 
485             writemask |= inst->dst.writemask;
486             imm_inst[inst_count++] = inst;
487 
488             last_reg = inst->dst.nr;
489             last_offset = inst->dst.offset;
490             last_reg_file = inst->dst.file;
491             if (vf > 0)
492                dest_type = need_type;
493          }
494       }
495    }
496 
497    if (progress)
498       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
499 
500    return progress;
501 }
502 
503 /* Replaces unused channels of a swizzle with channels that are used.
504  *
505  * For instance, this pass transforms
506  *
507  *    mov vgrf4.yz, vgrf5.wxzy
508  *
509  * into
510  *
511  *    mov vgrf4.yz, vgrf5.xxzx
512  *
513  * This eliminates false uses of some channels, letting dead code elimination
514  * remove the instructions that wrote them.
515  */
516 bool
opt_reduce_swizzle()517 vec4_visitor::opt_reduce_swizzle()
518 {
519    bool progress = false;
520 
521    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
522       if (inst->dst.file == BAD_FILE ||
523           inst->dst.file == ARF ||
524           inst->dst.file == FIXED_GRF ||
525           inst->is_send_from_grf())
526          continue;
527 
528       unsigned swizzle;
529 
530       /* Determine which channels of the sources are read. */
531       switch (inst->opcode) {
532       case VEC4_OPCODE_PACK_BYTES:
533       case BRW_OPCODE_DP4:
534       case BRW_OPCODE_DPH: /* FINISHME: DPH reads only three channels of src0,
535                             *           but all four of src1.
536                             */
537          swizzle = brw_swizzle_for_size(4);
538          break;
539       case BRW_OPCODE_DP3:
540          swizzle = brw_swizzle_for_size(3);
541          break;
542       case BRW_OPCODE_DP2:
543          swizzle = brw_swizzle_for_size(2);
544          break;
545 
546       case VEC4_OPCODE_TO_DOUBLE:
547       case VEC4_OPCODE_DOUBLE_TO_F32:
548       case VEC4_OPCODE_DOUBLE_TO_D32:
549       case VEC4_OPCODE_DOUBLE_TO_U32:
550       case VEC4_OPCODE_PICK_LOW_32BIT:
551       case VEC4_OPCODE_PICK_HIGH_32BIT:
552       case VEC4_OPCODE_SET_LOW_32BIT:
553       case VEC4_OPCODE_SET_HIGH_32BIT:
554          swizzle = brw_swizzle_for_size(4);
555          break;
556 
557       default:
558          swizzle = brw_swizzle_for_mask(inst->dst.writemask);
559          break;
560       }
561 
562       /* Update sources' swizzles. */
563       for (int i = 0; i < 3; i++) {
564          if (inst->src[i].file != VGRF &&
565              inst->src[i].file != ATTR &&
566              inst->src[i].file != UNIFORM)
567             continue;
568 
569          const unsigned new_swizzle =
570             brw_compose_swizzle(swizzle, inst->src[i].swizzle);
571          if (inst->src[i].swizzle != new_swizzle) {
572             inst->src[i].swizzle = new_swizzle;
573             progress = true;
574          }
575       }
576    }
577 
578    if (progress)
579       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
580 
581    return progress;
582 }
583 
584 void
split_uniform_registers()585 vec4_visitor::split_uniform_registers()
586 {
587    /* Prior to this, uniforms have been in an array sized according to
588     * the number of vector uniforms present, sparsely filled (so an
589     * aggregate results in reg indices being skipped over).  Now we're
590     * going to cut those aggregates up so each .nr index is one
591     * vector.  The goal is to make elimination of unused uniform
592     * components easier later.
593     */
594    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
595       for (int i = 0 ; i < 3; i++) {
596 	 if (inst->src[i].file != UNIFORM)
597 	    continue;
598 
599 	 assert(!inst->src[i].reladdr);
600 
601          inst->src[i].nr += inst->src[i].offset / 16;
602 	 inst->src[i].offset %= 16;
603       }
604    }
605 }
606 
607 /* This function returns the register number where we placed the uniform */
608 static int
set_push_constant_loc(const int nr_uniforms,int * new_uniform_count,const int src,const int size,const int channel_size,int * new_loc,int * new_chan,int * new_chans_used)609 set_push_constant_loc(const int nr_uniforms, int *new_uniform_count,
610                       const int src, const int size, const int channel_size,
611                       int *new_loc, int *new_chan,
612                       int *new_chans_used)
613 {
614    int dst;
615    /* Find the lowest place we can slot this uniform in. */
616    for (dst = 0; dst < nr_uniforms; dst++) {
617       if (ALIGN(new_chans_used[dst], channel_size) + size <= 4)
618          break;
619    }
620 
621    assert(dst < nr_uniforms);
622 
623    new_loc[src] = dst;
624    new_chan[src] = ALIGN(new_chans_used[dst], channel_size);
625    new_chans_used[dst] = ALIGN(new_chans_used[dst], channel_size) + size;
626 
627    *new_uniform_count = MAX2(*new_uniform_count, dst + 1);
628    return dst;
629 }
630 
631 void
pack_uniform_registers()632 vec4_visitor::pack_uniform_registers()
633 {
634    if (!compiler->compact_params)
635       return;
636 
637    uint8_t chans_used[this->uniforms];
638    int new_loc[this->uniforms];
639    int new_chan[this->uniforms];
640    bool is_aligned_to_dvec4[this->uniforms];
641    int new_chans_used[this->uniforms];
642    int channel_sizes[this->uniforms];
643 
644    memset(chans_used, 0, sizeof(chans_used));
645    memset(new_loc, 0, sizeof(new_loc));
646    memset(new_chan, 0, sizeof(new_chan));
647    memset(new_chans_used, 0, sizeof(new_chans_used));
648    memset(is_aligned_to_dvec4, 0, sizeof(is_aligned_to_dvec4));
649    memset(channel_sizes, 0, sizeof(channel_sizes));
650 
651    /* Find which uniform vectors are actually used by the program.  We
652     * expect unused vector elements when we've moved array access out
653     * to pull constants, and from some GLSL code generators like wine.
654     */
655    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
656       unsigned readmask;
657       switch (inst->opcode) {
658       case VEC4_OPCODE_PACK_BYTES:
659       case BRW_OPCODE_DP4:
660       case BRW_OPCODE_DPH:
661          readmask = 0xf;
662          break;
663       case BRW_OPCODE_DP3:
664          readmask = 0x7;
665          break;
666       case BRW_OPCODE_DP2:
667          readmask = 0x3;
668          break;
669       default:
670          readmask = inst->dst.writemask;
671          break;
672       }
673 
674       for (int i = 0 ; i < 3; i++) {
675          if (inst->src[i].file != UNIFORM)
676             continue;
677 
678          assert(type_sz(inst->src[i].type) % 4 == 0);
679          int channel_size = type_sz(inst->src[i].type) / 4;
680 
681          int reg = inst->src[i].nr;
682          for (int c = 0; c < 4; c++) {
683             if (!(readmask & (1 << c)))
684                continue;
685 
686             unsigned channel = BRW_GET_SWZ(inst->src[i].swizzle, c) + 1;
687             unsigned used = MAX2(chans_used[reg], channel * channel_size);
688             if (used <= 4) {
689                chans_used[reg] = used;
690                channel_sizes[reg] = MAX2(channel_sizes[reg], channel_size);
691             } else {
692                is_aligned_to_dvec4[reg] = true;
693                is_aligned_to_dvec4[reg + 1] = true;
694                chans_used[reg + 1] = used - 4;
695                channel_sizes[reg + 1] = MAX2(channel_sizes[reg + 1], channel_size);
696             }
697          }
698       }
699 
700       if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
701           inst->src[0].file == UNIFORM) {
702          assert(inst->src[2].file == BRW_IMMEDIATE_VALUE);
703          assert(inst->src[0].subnr == 0);
704 
705          unsigned bytes_read = inst->src[2].ud;
706          assert(bytes_read % 4 == 0);
707          unsigned vec4s_read = DIV_ROUND_UP(bytes_read, 16);
708 
709          /* We just mark every register touched by a MOV_INDIRECT as being
710           * fully used.  This ensures that it doesn't broken up piecewise by
711           * the next part of our packing algorithm.
712           */
713          int reg = inst->src[0].nr;
714          int channel_size = type_sz(inst->src[0].type) / 4;
715          for (unsigned i = 0; i < vec4s_read; i++) {
716             chans_used[reg + i] = 4;
717             channel_sizes[reg + i] = MAX2(channel_sizes[reg + i], channel_size);
718          }
719       }
720    }
721 
722    int new_uniform_count = 0;
723 
724    /* As the uniforms are going to be reordered, take the data from a temporary
725     * copy of the original param[].
726     */
727    uint32_t *param = ralloc_array(NULL, uint32_t, stage_prog_data->nr_params);
728    memcpy(param, stage_prog_data->param,
729           sizeof(uint32_t) * stage_prog_data->nr_params);
730 
731    /* Now, figure out a packing of the live uniform vectors into our
732     * push constants. Start with dvec{3,4} because they are aligned to
733     * dvec4 size (2 vec4).
734     */
735    for (int src = 0; src < uniforms; src++) {
736       int size = chans_used[src];
737 
738       if (size == 0 || !is_aligned_to_dvec4[src])
739          continue;
740 
741       /* dvec3 are aligned to dvec4 size, apply the alignment of the size
742        * to 4 to avoid moving last component of a dvec3 to the available
743        * location at the end of a previous dvec3. These available locations
744        * could be filled by smaller variables in next loop.
745        */
746       size = ALIGN(size, 4);
747       int dst = set_push_constant_loc(uniforms, &new_uniform_count,
748                                       src, size, channel_sizes[src],
749                                       new_loc, new_chan,
750                                       new_chans_used);
751       /* Move the references to the data */
752       for (int j = 0; j < size; j++) {
753          stage_prog_data->param[dst * 4 + new_chan[src] + j] =
754             param[src * 4 + j];
755       }
756    }
757 
758    /* Continue with the rest of data, which is aligned to vec4. */
759    for (int src = 0; src < uniforms; src++) {
760       int size = chans_used[src];
761 
762       if (size == 0 || is_aligned_to_dvec4[src])
763          continue;
764 
765       int dst = set_push_constant_loc(uniforms, &new_uniform_count,
766                                       src, size, channel_sizes[src],
767                                       new_loc, new_chan,
768                                       new_chans_used);
769       /* Move the references to the data */
770       for (int j = 0; j < size; j++) {
771          stage_prog_data->param[dst * 4 + new_chan[src] + j] =
772             param[src * 4 + j];
773       }
774    }
775 
776    ralloc_free(param);
777    this->uniforms = new_uniform_count;
778 
779    /* Now, update the instructions for our repacked uniforms. */
780    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
781       for (int i = 0 ; i < 3; i++) {
782          int src = inst->src[i].nr;
783 
784          if (inst->src[i].file != UNIFORM)
785             continue;
786 
787          int chan = new_chan[src] / channel_sizes[src];
788          inst->src[i].nr = new_loc[src];
789          inst->src[i].swizzle += BRW_SWIZZLE4(chan, chan, chan, chan);
790       }
791    }
792 }
793 
794 /**
795  * Does algebraic optimizations (0 * a = 0, 1 * a = a, a + 0 = a).
796  *
797  * While GLSL IR also performs this optimization, we end up with it in
798  * our instruction stream for a couple of reasons.  One is that we
799  * sometimes generate silly instructions, for example in array access
800  * where we'll generate "ADD offset, index, base" even if base is 0.
801  * The other is that GLSL IR's constant propagation doesn't track the
802  * components of aggregates, so some VS patterns (initialize matrix to
803  * 0, accumulate in vertex blending factors) end up breaking down to
804  * instructions involving 0.
805  */
806 bool
opt_algebraic()807 vec4_visitor::opt_algebraic()
808 {
809    bool progress = false;
810 
811    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
812       switch (inst->opcode) {
813       case BRW_OPCODE_MOV:
814          if (inst->src[0].file != IMM)
815             break;
816 
817          if (inst->saturate) {
818             /* Full mixed-type saturates don't happen.  However, we can end up
819              * with things like:
820              *
821              *    mov.sat(8) g21<1>DF       -1F
822              *
823              * Other mixed-size-but-same-base-type cases may also be possible.
824              */
825             if (inst->dst.type != inst->src[0].type &&
826                 inst->dst.type != BRW_REGISTER_TYPE_DF &&
827                 inst->src[0].type != BRW_REGISTER_TYPE_F)
828                assert(!"unimplemented: saturate mixed types");
829 
830             if (brw_saturate_immediate(inst->src[0].type,
831                                        &inst->src[0].as_brw_reg())) {
832                inst->saturate = false;
833                progress = true;
834             }
835          }
836          break;
837 
838       case BRW_OPCODE_OR:
839          if (inst->src[1].is_zero()) {
840             inst->opcode = BRW_OPCODE_MOV;
841             inst->src[1] = src_reg();
842             progress = true;
843          }
844          break;
845 
846       case VEC4_OPCODE_UNPACK_UNIFORM:
847          if (inst->src[0].file != UNIFORM) {
848             inst->opcode = BRW_OPCODE_MOV;
849             progress = true;
850          }
851          break;
852 
853       case BRW_OPCODE_ADD:
854 	 if (inst->src[1].is_zero()) {
855 	    inst->opcode = BRW_OPCODE_MOV;
856 	    inst->src[1] = src_reg();
857 	    progress = true;
858 	 }
859 	 break;
860 
861       case BRW_OPCODE_MUL:
862 	 if (inst->src[1].is_zero()) {
863 	    inst->opcode = BRW_OPCODE_MOV;
864 	    switch (inst->src[0].type) {
865 	    case BRW_REGISTER_TYPE_F:
866 	       inst->src[0] = brw_imm_f(0.0f);
867 	       break;
868 	    case BRW_REGISTER_TYPE_D:
869 	       inst->src[0] = brw_imm_d(0);
870 	       break;
871 	    case BRW_REGISTER_TYPE_UD:
872 	       inst->src[0] = brw_imm_ud(0u);
873 	       break;
874 	    default:
875 	       unreachable("not reached");
876 	    }
877 	    inst->src[1] = src_reg();
878 	    progress = true;
879 	 } else if (inst->src[1].is_one()) {
880 	    inst->opcode = BRW_OPCODE_MOV;
881 	    inst->src[1] = src_reg();
882 	    progress = true;
883          } else if (inst->src[1].is_negative_one()) {
884             inst->opcode = BRW_OPCODE_MOV;
885             inst->src[0].negate = !inst->src[0].negate;
886             inst->src[1] = src_reg();
887             progress = true;
888 	 }
889 	 break;
890       case SHADER_OPCODE_BROADCAST:
891          if (is_uniform(inst->src[0]) ||
892              inst->src[1].is_zero()) {
893             inst->opcode = BRW_OPCODE_MOV;
894             inst->src[1] = src_reg();
895             inst->force_writemask_all = true;
896             progress = true;
897          }
898          break;
899 
900       default:
901 	 break;
902       }
903    }
904 
905    if (progress)
906       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
907                           DEPENDENCY_INSTRUCTION_DETAIL);
908 
909    return progress;
910 }
911 
912 /**
913  * Only a limited number of hardware registers may be used for push
914  * constants, so this turns access to the overflowed constants into
915  * pull constants.
916  */
917 void
move_push_constants_to_pull_constants()918 vec4_visitor::move_push_constants_to_pull_constants()
919 {
920    int pull_constant_loc[this->uniforms];
921 
922    /* Only allow 32 registers (256 uniform components) as push constants,
923     * which is the limit on gen6.
924     *
925     * If changing this value, note the limitation about total_regs in
926     * brw_curbe.c.
927     */
928    int max_uniform_components = 32 * 8;
929    if (this->uniforms * 4 <= max_uniform_components)
930       return;
931 
932    /* Make some sort of choice as to which uniforms get sent to pull
933     * constants.  We could potentially do something clever here like
934     * look for the most infrequently used uniform vec4s, but leave
935     * that for later.
936     */
937    for (int i = 0; i < this->uniforms * 4; i += 4) {
938       pull_constant_loc[i / 4] = -1;
939 
940       if (i >= max_uniform_components) {
941          uint32_t *values = &stage_prog_data->param[i];
942 
943          /* Try to find an existing copy of this uniform in the pull
944           * constants if it was part of an array access already.
945           */
946          for (unsigned int j = 0; j < stage_prog_data->nr_pull_params; j += 4) {
947             int matches;
948 
949             for (matches = 0; matches < 4; matches++) {
950                if (stage_prog_data->pull_param[j + matches] != values[matches])
951                   break;
952             }
953 
954             if (matches == 4) {
955                pull_constant_loc[i / 4] = j / 4;
956                break;
957             }
958          }
959 
960          if (pull_constant_loc[i / 4] == -1) {
961             assert(stage_prog_data->nr_pull_params % 4 == 0);
962             pull_constant_loc[i / 4] = stage_prog_data->nr_pull_params / 4;
963 
964             for (int j = 0; j < 4; j++) {
965                stage_prog_data->pull_param[stage_prog_data->nr_pull_params++] =
966                   values[j];
967             }
968          }
969       }
970    }
971 
972    /* Now actually rewrite usage of the things we've moved to pull
973     * constants.
974     */
975    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
976       for (int i = 0 ; i < 3; i++) {
977          if (inst->src[i].file != UNIFORM ||
978              pull_constant_loc[inst->src[i].nr] == -1)
979             continue;
980 
981          int uniform = inst->src[i].nr;
982 
983          const glsl_type *temp_type = type_sz(inst->src[i].type) == 8 ?
984             glsl_type::dvec4_type : glsl_type::vec4_type;
985          dst_reg temp = dst_reg(this, temp_type);
986 
987          emit_pull_constant_load(block, inst, temp, inst->src[i],
988                                  pull_constant_loc[uniform], src_reg());
989 
990          inst->src[i].file = temp.file;
991          inst->src[i].nr = temp.nr;
992          inst->src[i].offset %= 16;
993          inst->src[i].reladdr = NULL;
994       }
995    }
996 
997    /* Repack push constants to remove the now-unused ones. */
998    pack_uniform_registers();
999 }
1000 
1001 /* Conditions for which we want to avoid setting the dependency control bits */
1002 bool
is_dep_ctrl_unsafe(const vec4_instruction * inst)1003 vec4_visitor::is_dep_ctrl_unsafe(const vec4_instruction *inst)
1004 {
1005 #define IS_DWORD(reg) \
1006    (reg.type == BRW_REGISTER_TYPE_UD || \
1007     reg.type == BRW_REGISTER_TYPE_D)
1008 
1009 #define IS_64BIT(reg) (reg.file != BAD_FILE && type_sz(reg.type) == 8)
1010 
1011    if (devinfo->gen >= 7) {
1012       if (IS_64BIT(inst->dst) || IS_64BIT(inst->src[0]) ||
1013           IS_64BIT(inst->src[1]) || IS_64BIT(inst->src[2]))
1014       return true;
1015    }
1016 
1017 #undef IS_64BIT
1018 #undef IS_DWORD
1019 
1020    /*
1021     * mlen:
1022     * In the presence of send messages, totally interrupt dependency
1023     * control. They're long enough that the chance of dependency
1024     * control around them just doesn't matter.
1025     *
1026     * predicate:
1027     * From the Ivy Bridge PRM, volume 4 part 3.7, page 80:
1028     * When a sequence of NoDDChk and NoDDClr are used, the last instruction that
1029     * completes the scoreboard clear must have a non-zero execution mask. This
1030     * means, if any kind of predication can change the execution mask or channel
1031     * enable of the last instruction, the optimization must be avoided. This is
1032     * to avoid instructions being shot down the pipeline when no writes are
1033     * required.
1034     *
1035     * math:
1036     * Dependency control does not work well over math instructions.
1037     * NB: Discovered empirically
1038     */
1039    return (inst->mlen || inst->predicate || inst->is_math());
1040 }
1041 
1042 /**
1043  * Sets the dependency control fields on instructions after register
1044  * allocation and before the generator is run.
1045  *
1046  * When you have a sequence of instructions like:
1047  *
1048  * DP4 temp.x vertex uniform[0]
1049  * DP4 temp.y vertex uniform[0]
1050  * DP4 temp.z vertex uniform[0]
1051  * DP4 temp.w vertex uniform[0]
1052  *
1053  * The hardware doesn't know that it can actually run the later instructions
1054  * while the previous ones are in flight, producing stalls.  However, we have
1055  * manual fields we can set in the instructions that let it do so.
1056  */
1057 void
opt_set_dependency_control()1058 vec4_visitor::opt_set_dependency_control()
1059 {
1060    vec4_instruction *last_grf_write[BRW_MAX_GRF];
1061    uint8_t grf_channels_written[BRW_MAX_GRF];
1062    vec4_instruction *last_mrf_write[BRW_MAX_GRF];
1063    uint8_t mrf_channels_written[BRW_MAX_GRF];
1064 
1065    assert(prog_data->total_grf ||
1066           !"Must be called after register allocation");
1067 
1068    foreach_block (block, cfg) {
1069       memset(last_grf_write, 0, sizeof(last_grf_write));
1070       memset(last_mrf_write, 0, sizeof(last_mrf_write));
1071 
1072       foreach_inst_in_block (vec4_instruction, inst, block) {
1073          /* If we read from a register that we were doing dependency control
1074           * on, don't do dependency control across the read.
1075           */
1076          for (int i = 0; i < 3; i++) {
1077             int reg = inst->src[i].nr + inst->src[i].offset / REG_SIZE;
1078             if (inst->src[i].file == VGRF) {
1079                last_grf_write[reg] = NULL;
1080             } else if (inst->src[i].file == FIXED_GRF) {
1081                memset(last_grf_write, 0, sizeof(last_grf_write));
1082                break;
1083             }
1084             assert(inst->src[i].file != MRF);
1085          }
1086 
1087          if (is_dep_ctrl_unsafe(inst)) {
1088             memset(last_grf_write, 0, sizeof(last_grf_write));
1089             memset(last_mrf_write, 0, sizeof(last_mrf_write));
1090             continue;
1091          }
1092 
1093          /* Now, see if we can do dependency control for this instruction
1094           * against a previous one writing to its destination.
1095           */
1096          int reg = inst->dst.nr + inst->dst.offset / REG_SIZE;
1097          if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1098             if (last_grf_write[reg] &&
1099                 last_grf_write[reg]->dst.offset == inst->dst.offset &&
1100                 !(inst->dst.writemask & grf_channels_written[reg])) {
1101                last_grf_write[reg]->no_dd_clear = true;
1102                inst->no_dd_check = true;
1103             } else {
1104                grf_channels_written[reg] = 0;
1105             }
1106 
1107             last_grf_write[reg] = inst;
1108             grf_channels_written[reg] |= inst->dst.writemask;
1109          } else if (inst->dst.file == MRF) {
1110             if (last_mrf_write[reg] &&
1111                 last_mrf_write[reg]->dst.offset == inst->dst.offset &&
1112                 !(inst->dst.writemask & mrf_channels_written[reg])) {
1113                last_mrf_write[reg]->no_dd_clear = true;
1114                inst->no_dd_check = true;
1115             } else {
1116                mrf_channels_written[reg] = 0;
1117             }
1118 
1119             last_mrf_write[reg] = inst;
1120             mrf_channels_written[reg] |= inst->dst.writemask;
1121          }
1122       }
1123    }
1124 }
1125 
1126 bool
can_reswizzle(const struct gen_device_info * devinfo,int dst_writemask,int swizzle,int swizzle_mask)1127 vec4_instruction::can_reswizzle(const struct gen_device_info *devinfo,
1128                                 int dst_writemask,
1129                                 int swizzle,
1130                                 int swizzle_mask)
1131 {
1132    /* Gen6 MATH instructions can not execute in align16 mode, so swizzles
1133     * are not allowed.
1134     */
1135    if (devinfo->gen == 6 && is_math() && swizzle != BRW_SWIZZLE_XYZW)
1136       return false;
1137 
1138    /* If we write to the flag register changing the swizzle would change
1139     * what channels are written to the flag register.
1140     */
1141    if (writes_flag())
1142       return false;
1143 
1144    /* We can't swizzle implicit accumulator access.  We'd have to
1145     * reswizzle the producer of the accumulator value in addition
1146     * to the consumer (i.e. both MUL and MACH).  Just skip this.
1147     */
1148    if (reads_accumulator_implicitly())
1149       return false;
1150 
1151    if (!can_do_writemask(devinfo) && dst_writemask != WRITEMASK_XYZW)
1152       return false;
1153 
1154    /* If this instruction sets anything not referenced by swizzle, then we'd
1155     * totally break it when we reswizzle.
1156     */
1157    if (dst.writemask & ~swizzle_mask)
1158       return false;
1159 
1160    if (mlen > 0)
1161       return false;
1162 
1163    for (int i = 0; i < 3; i++) {
1164       if (src[i].is_accumulator())
1165          return false;
1166    }
1167 
1168    return true;
1169 }
1170 
1171 /**
1172  * For any channels in the swizzle's source that were populated by this
1173  * instruction, rewrite the instruction to put the appropriate result directly
1174  * in those channels.
1175  *
1176  * e.g. for swizzle=yywx, MUL a.xy b c -> MUL a.yy_x b.yy z.yy_x
1177  */
1178 void
reswizzle(int dst_writemask,int swizzle)1179 vec4_instruction::reswizzle(int dst_writemask, int swizzle)
1180 {
1181    /* Destination write mask doesn't correspond to source swizzle for the dot
1182     * product and pack_bytes instructions.
1183     */
1184    if (opcode != BRW_OPCODE_DP4 && opcode != BRW_OPCODE_DPH &&
1185        opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2 &&
1186        opcode != VEC4_OPCODE_PACK_BYTES) {
1187       for (int i = 0; i < 3; i++) {
1188          if (src[i].file == BAD_FILE)
1189             continue;
1190 
1191          if (src[i].file == IMM) {
1192             assert(src[i].type != BRW_REGISTER_TYPE_V &&
1193                    src[i].type != BRW_REGISTER_TYPE_UV);
1194 
1195             /* Vector immediate types need to be reswizzled. */
1196             if (src[i].type == BRW_REGISTER_TYPE_VF) {
1197                const unsigned imm[] = {
1198                   (src[i].ud >>  0) & 0x0ff,
1199                   (src[i].ud >>  8) & 0x0ff,
1200                   (src[i].ud >> 16) & 0x0ff,
1201                   (src[i].ud >> 24) & 0x0ff,
1202                };
1203 
1204                src[i] = brw_imm_vf4(imm[BRW_GET_SWZ(swizzle, 0)],
1205                                     imm[BRW_GET_SWZ(swizzle, 1)],
1206                                     imm[BRW_GET_SWZ(swizzle, 2)],
1207                                     imm[BRW_GET_SWZ(swizzle, 3)]);
1208             }
1209 
1210             continue;
1211          }
1212 
1213          src[i].swizzle = brw_compose_swizzle(swizzle, src[i].swizzle);
1214       }
1215    }
1216 
1217    /* Apply the specified swizzle and writemask to the original mask of
1218     * written components.
1219     */
1220    dst.writemask = dst_writemask &
1221                    brw_apply_swizzle_to_mask(swizzle, dst.writemask);
1222 }
1223 
1224 /*
1225  * Tries to reduce extra MOV instructions by taking temporary GRFs that get
1226  * just written and then MOVed into another reg and making the original write
1227  * of the GRF write directly to the final destination instead.
1228  */
1229 bool
opt_register_coalesce()1230 vec4_visitor::opt_register_coalesce()
1231 {
1232    bool progress = false;
1233    int next_ip = 0;
1234    const vec4_live_variables &live = live_analysis.require();
1235 
1236    foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
1237       int ip = next_ip;
1238       next_ip++;
1239 
1240       if (inst->opcode != BRW_OPCODE_MOV ||
1241           (inst->dst.file != VGRF && inst->dst.file != MRF) ||
1242 	  inst->predicate ||
1243 	  inst->src[0].file != VGRF ||
1244 	  inst->dst.type != inst->src[0].type ||
1245 	  inst->src[0].abs || inst->src[0].negate || inst->src[0].reladdr)
1246 	 continue;
1247 
1248       /* Remove no-op MOVs */
1249       if (inst->dst.file == inst->src[0].file &&
1250           inst->dst.nr == inst->src[0].nr &&
1251           inst->dst.offset == inst->src[0].offset) {
1252          bool is_nop_mov = true;
1253 
1254          for (unsigned c = 0; c < 4; c++) {
1255             if ((inst->dst.writemask & (1 << c)) == 0)
1256                continue;
1257 
1258             if (BRW_GET_SWZ(inst->src[0].swizzle, c) != c) {
1259                is_nop_mov = false;
1260                break;
1261             }
1262          }
1263 
1264          if (is_nop_mov) {
1265             inst->remove(block);
1266             progress = true;
1267             continue;
1268          }
1269       }
1270 
1271       bool to_mrf = (inst->dst.file == MRF);
1272 
1273       /* Can't coalesce this GRF if someone else was going to
1274        * read it later.
1275        */
1276       if (live.var_range_end(var_from_reg(alloc, dst_reg(inst->src[0])), 8) > ip)
1277 	 continue;
1278 
1279       /* We need to check interference with the final destination between this
1280        * instruction and the earliest instruction involved in writing the GRF
1281        * we're eliminating.  To do that, keep track of which of our source
1282        * channels we've seen initialized.
1283        */
1284       const unsigned chans_needed =
1285          brw_apply_inv_swizzle_to_mask(inst->src[0].swizzle,
1286                                        inst->dst.writemask);
1287       unsigned chans_remaining = chans_needed;
1288 
1289       /* Now walk up the instruction stream trying to see if we can rewrite
1290        * everything writing to the temporary to write into the destination
1291        * instead.
1292        */
1293       vec4_instruction *_scan_inst = (vec4_instruction *)inst->prev;
1294       foreach_inst_in_block_reverse_starting_from(vec4_instruction, scan_inst,
1295                                                   inst) {
1296          _scan_inst = scan_inst;
1297 
1298          if (regions_overlap(inst->src[0], inst->size_read(0),
1299                              scan_inst->dst, scan_inst->size_written)) {
1300             /* Found something writing to the reg we want to coalesce away. */
1301             if (to_mrf) {
1302                /* SEND instructions can't have MRF as a destination. */
1303                if (scan_inst->mlen)
1304                   break;
1305 
1306                if (devinfo->gen == 6) {
1307                   /* gen6 math instructions must have the destination be
1308                    * VGRF, so no compute-to-MRF for them.
1309                    */
1310                   if (scan_inst->is_math()) {
1311                      break;
1312                   }
1313                }
1314             }
1315 
1316             /* VS_OPCODE_UNPACK_FLAGS_SIMD4X2 generates a bunch of mov(1)
1317              * instructions, and this optimization pass is not capable of
1318              * handling that.  Bail on these instructions and hope that some
1319              * later optimization pass can do the right thing after they are
1320              * expanded.
1321              */
1322             if (scan_inst->opcode == VS_OPCODE_UNPACK_FLAGS_SIMD4X2)
1323                break;
1324 
1325             /* This doesn't handle saturation on the instruction we
1326              * want to coalesce away if the register types do not match.
1327              * But if scan_inst is a non type-converting 'mov', we can fix
1328              * the types later.
1329              */
1330             if (inst->saturate &&
1331                 inst->dst.type != scan_inst->dst.type &&
1332                 !(scan_inst->opcode == BRW_OPCODE_MOV &&
1333                   scan_inst->dst.type == scan_inst->src[0].type))
1334                break;
1335 
1336             /* Only allow coalescing between registers of the same type size.
1337              * Otherwise we would need to make the pass aware of the fact that
1338              * channel sizes are different for single and double precision.
1339              */
1340             if (type_sz(inst->src[0].type) != type_sz(scan_inst->src[0].type))
1341                break;
1342 
1343             /* Check that scan_inst writes the same amount of data as the
1344              * instruction, otherwise coalescing would lead to writing a
1345              * different (larger or smaller) region of the destination
1346              */
1347             if (scan_inst->size_written != inst->size_written)
1348                break;
1349 
1350             /* If we can't handle the swizzle, bail. */
1351             if (!scan_inst->can_reswizzle(devinfo, inst->dst.writemask,
1352                                           inst->src[0].swizzle,
1353                                           chans_needed)) {
1354                break;
1355             }
1356 
1357             /* This only handles coalescing writes of 8 channels (1 register
1358              * for single-precision and 2 registers for double-precision)
1359              * starting at the source offset of the copy instruction.
1360              */
1361             if (DIV_ROUND_UP(scan_inst->size_written,
1362                              type_sz(scan_inst->dst.type)) > 8 ||
1363                 scan_inst->dst.offset != inst->src[0].offset)
1364                break;
1365 
1366 	    /* Mark which channels we found unconditional writes for. */
1367 	    if (!scan_inst->predicate)
1368                chans_remaining &= ~scan_inst->dst.writemask;
1369 
1370 	    if (chans_remaining == 0)
1371 	       break;
1372 	 }
1373 
1374          /* You can't read from an MRF, so if someone else reads our MRF's
1375           * source GRF that we wanted to rewrite, that stops us.  If it's a
1376           * GRF we're trying to coalesce to, we don't actually handle
1377           * rewriting sources so bail in that case as well.
1378           */
1379 	 bool interfered = false;
1380 	 for (int i = 0; i < 3; i++) {
1381             if (regions_overlap(inst->src[0], inst->size_read(0),
1382                                 scan_inst->src[i], scan_inst->size_read(i)))
1383 	       interfered = true;
1384 	 }
1385 	 if (interfered)
1386 	    break;
1387 
1388          /* If somebody else writes the same channels of our destination here,
1389           * we can't coalesce before that.
1390           */
1391          if (regions_overlap(inst->dst, inst->size_written,
1392                              scan_inst->dst, scan_inst->size_written) &&
1393              (inst->dst.writemask & scan_inst->dst.writemask) != 0) {
1394             break;
1395          }
1396 
1397          /* Check for reads of the register we're trying to coalesce into.  We
1398           * can't go rewriting instructions above that to put some other value
1399           * in the register instead.
1400           */
1401          if (to_mrf && scan_inst->mlen > 0) {
1402             unsigned start = scan_inst->base_mrf;
1403             unsigned end = scan_inst->base_mrf + scan_inst->mlen;
1404 
1405             if (inst->dst.nr >= start && inst->dst.nr < end) {
1406                break;
1407             }
1408          } else {
1409             for (int i = 0; i < 3; i++) {
1410                if (regions_overlap(inst->dst, inst->size_written,
1411                                    scan_inst->src[i], scan_inst->size_read(i)))
1412                   interfered = true;
1413             }
1414             if (interfered)
1415                break;
1416          }
1417       }
1418 
1419       if (chans_remaining == 0) {
1420 	 /* If we've made it here, we have an MOV we want to coalesce out, and
1421 	  * a scan_inst pointing to the earliest instruction involved in
1422 	  * computing the value.  Now go rewrite the instruction stream
1423 	  * between the two.
1424 	  */
1425          vec4_instruction *scan_inst = _scan_inst;
1426 	 while (scan_inst != inst) {
1427 	    if (scan_inst->dst.file == VGRF &&
1428                 scan_inst->dst.nr == inst->src[0].nr &&
1429 		scan_inst->dst.offset == inst->src[0].offset) {
1430                scan_inst->reswizzle(inst->dst.writemask,
1431                                     inst->src[0].swizzle);
1432 	       scan_inst->dst.file = inst->dst.file;
1433                scan_inst->dst.nr = inst->dst.nr;
1434 	       scan_inst->dst.offset = inst->dst.offset;
1435                if (inst->saturate &&
1436                    inst->dst.type != scan_inst->dst.type) {
1437                   /* If we have reached this point, scan_inst is a non
1438                    * type-converting 'mov' and we can modify its register types
1439                    * to match the ones in inst. Otherwise, we could have an
1440                    * incorrect saturation result.
1441                    */
1442                   scan_inst->dst.type = inst->dst.type;
1443                   scan_inst->src[0].type = inst->src[0].type;
1444                }
1445 	       scan_inst->saturate |= inst->saturate;
1446 	    }
1447 	    scan_inst = (vec4_instruction *)scan_inst->next;
1448 	 }
1449 	 inst->remove(block);
1450 	 progress = true;
1451       }
1452    }
1453 
1454    if (progress)
1455       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1456 
1457    return progress;
1458 }
1459 
1460 /**
1461  * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
1462  * flow.  We could probably do better here with some form of divergence
1463  * analysis.
1464  */
1465 bool
eliminate_find_live_channel()1466 vec4_visitor::eliminate_find_live_channel()
1467 {
1468    bool progress = false;
1469    unsigned depth = 0;
1470 
1471    if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
1472       /* The optimization below assumes that channel zero is live on thread
1473        * dispatch, which may not be the case if the fixed function dispatches
1474        * threads sparsely.
1475        */
1476       return false;
1477    }
1478 
1479    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1480       switch (inst->opcode) {
1481       case BRW_OPCODE_IF:
1482       case BRW_OPCODE_DO:
1483          depth++;
1484          break;
1485 
1486       case BRW_OPCODE_ENDIF:
1487       case BRW_OPCODE_WHILE:
1488          depth--;
1489          break;
1490 
1491       case SHADER_OPCODE_FIND_LIVE_CHANNEL:
1492          if (depth == 0) {
1493             inst->opcode = BRW_OPCODE_MOV;
1494             inst->src[0] = brw_imm_d(0);
1495             inst->force_writemask_all = true;
1496             progress = true;
1497          }
1498          break;
1499 
1500       default:
1501          break;
1502       }
1503    }
1504 
1505    if (progress)
1506       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
1507 
1508    return progress;
1509 }
1510 
1511 /**
1512  * Splits virtual GRFs requesting more than one contiguous physical register.
1513  *
1514  * We initially create large virtual GRFs for temporary structures, arrays,
1515  * and matrices, so that the visitor functions can add offsets to work their
1516  * way down to the actual member being accessed.  But when it comes to
1517  * optimization, we'd like to treat each register as individual storage if
1518  * possible.
1519  *
1520  * So far, the only thing that might prevent splitting is a send message from
1521  * a GRF on IVB.
1522  */
1523 void
split_virtual_grfs()1524 vec4_visitor::split_virtual_grfs()
1525 {
1526    int num_vars = this->alloc.count;
1527    int new_virtual_grf[num_vars];
1528    bool split_grf[num_vars];
1529 
1530    memset(new_virtual_grf, 0, sizeof(new_virtual_grf));
1531 
1532    /* Try to split anything > 0 sized. */
1533    for (int i = 0; i < num_vars; i++) {
1534       split_grf[i] = this->alloc.sizes[i] != 1;
1535    }
1536 
1537    /* Check that the instructions are compatible with the registers we're trying
1538     * to split.
1539     */
1540    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1541       if (inst->dst.file == VGRF && regs_written(inst) > 1)
1542          split_grf[inst->dst.nr] = false;
1543 
1544       for (int i = 0; i < 3; i++) {
1545          if (inst->src[i].file == VGRF && regs_read(inst, i) > 1)
1546             split_grf[inst->src[i].nr] = false;
1547       }
1548    }
1549 
1550    /* Allocate new space for split regs.  Note that the virtual
1551     * numbers will be contiguous.
1552     */
1553    for (int i = 0; i < num_vars; i++) {
1554       if (!split_grf[i])
1555          continue;
1556 
1557       new_virtual_grf[i] = alloc.allocate(1);
1558       for (unsigned j = 2; j < this->alloc.sizes[i]; j++) {
1559          unsigned reg = alloc.allocate(1);
1560          assert(reg == new_virtual_grf[i] + j - 1);
1561          (void) reg;
1562       }
1563       this->alloc.sizes[i] = 1;
1564    }
1565 
1566    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1567       if (inst->dst.file == VGRF && split_grf[inst->dst.nr] &&
1568           inst->dst.offset / REG_SIZE != 0) {
1569          inst->dst.nr = (new_virtual_grf[inst->dst.nr] +
1570                          inst->dst.offset / REG_SIZE - 1);
1571          inst->dst.offset %= REG_SIZE;
1572       }
1573       for (int i = 0; i < 3; i++) {
1574          if (inst->src[i].file == VGRF && split_grf[inst->src[i].nr] &&
1575              inst->src[i].offset / REG_SIZE != 0) {
1576             inst->src[i].nr = (new_virtual_grf[inst->src[i].nr] +
1577                                 inst->src[i].offset / REG_SIZE - 1);
1578             inst->src[i].offset %= REG_SIZE;
1579          }
1580       }
1581    }
1582    invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL | DEPENDENCY_VARIABLES);
1583 }
1584 
1585 void
dump_instruction(const backend_instruction * be_inst) const1586 vec4_visitor::dump_instruction(const backend_instruction *be_inst) const
1587 {
1588    dump_instruction(be_inst, stderr);
1589 }
1590 
1591 void
dump_instruction(const backend_instruction * be_inst,FILE * file) const1592 vec4_visitor::dump_instruction(const backend_instruction *be_inst, FILE *file) const
1593 {
1594    const vec4_instruction *inst = (const vec4_instruction *)be_inst;
1595 
1596    if (inst->predicate) {
1597       fprintf(file, "(%cf%d.%d%s) ",
1598               inst->predicate_inverse ? '-' : '+',
1599               inst->flag_subreg / 2,
1600               inst->flag_subreg % 2,
1601               pred_ctrl_align16[inst->predicate]);
1602    }
1603 
1604    fprintf(file, "%s(%d)", brw_instruction_name(devinfo, inst->opcode),
1605            inst->exec_size);
1606    if (inst->saturate)
1607       fprintf(file, ".sat");
1608    if (inst->conditional_mod) {
1609       fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
1610       if (!inst->predicate &&
1611           (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
1612                                 inst->opcode != BRW_OPCODE_CSEL &&
1613                                 inst->opcode != BRW_OPCODE_IF &&
1614                                 inst->opcode != BRW_OPCODE_WHILE))) {
1615          fprintf(file, ".f%d.%d", inst->flag_subreg / 2, inst->flag_subreg % 2);
1616       }
1617    }
1618    fprintf(file, " ");
1619 
1620    switch (inst->dst.file) {
1621    case VGRF:
1622       fprintf(file, "vgrf%d", inst->dst.nr);
1623       break;
1624    case FIXED_GRF:
1625       fprintf(file, "g%d", inst->dst.nr);
1626       break;
1627    case MRF:
1628       fprintf(file, "m%d", inst->dst.nr);
1629       break;
1630    case ARF:
1631       switch (inst->dst.nr) {
1632       case BRW_ARF_NULL:
1633          fprintf(file, "null");
1634          break;
1635       case BRW_ARF_ADDRESS:
1636          fprintf(file, "a0.%d", inst->dst.subnr);
1637          break;
1638       case BRW_ARF_ACCUMULATOR:
1639          fprintf(file, "acc%d", inst->dst.subnr);
1640          break;
1641       case BRW_ARF_FLAG:
1642          fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1643          break;
1644       default:
1645          fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1646          break;
1647       }
1648       break;
1649    case BAD_FILE:
1650       fprintf(file, "(null)");
1651       break;
1652    case IMM:
1653    case ATTR:
1654    case UNIFORM:
1655       unreachable("not reached");
1656    }
1657    if (inst->dst.offset ||
1658        (inst->dst.file == VGRF &&
1659         alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
1660       const unsigned reg_size = (inst->dst.file == UNIFORM ? 16 : REG_SIZE);
1661       fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
1662               inst->dst.offset % reg_size);
1663    }
1664    if (inst->dst.writemask != WRITEMASK_XYZW) {
1665       fprintf(file, ".");
1666       if (inst->dst.writemask & 1)
1667          fprintf(file, "x");
1668       if (inst->dst.writemask & 2)
1669          fprintf(file, "y");
1670       if (inst->dst.writemask & 4)
1671          fprintf(file, "z");
1672       if (inst->dst.writemask & 8)
1673          fprintf(file, "w");
1674    }
1675    fprintf(file, ":%s", brw_reg_type_to_letters(inst->dst.type));
1676 
1677    if (inst->src[0].file != BAD_FILE)
1678       fprintf(file, ", ");
1679 
1680    for (int i = 0; i < 3 && inst->src[i].file != BAD_FILE; i++) {
1681       if (inst->src[i].negate)
1682          fprintf(file, "-");
1683       if (inst->src[i].abs)
1684          fprintf(file, "|");
1685       switch (inst->src[i].file) {
1686       case VGRF:
1687          fprintf(file, "vgrf%d", inst->src[i].nr);
1688          break;
1689       case FIXED_GRF:
1690          fprintf(file, "g%d.%d", inst->src[i].nr, inst->src[i].subnr);
1691          break;
1692       case ATTR:
1693          fprintf(file, "attr%d", inst->src[i].nr);
1694          break;
1695       case UNIFORM:
1696          fprintf(file, "u%d", inst->src[i].nr);
1697          break;
1698       case IMM:
1699          switch (inst->src[i].type) {
1700          case BRW_REGISTER_TYPE_F:
1701             fprintf(file, "%fF", inst->src[i].f);
1702             break;
1703          case BRW_REGISTER_TYPE_DF:
1704             fprintf(file, "%fDF", inst->src[i].df);
1705             break;
1706          case BRW_REGISTER_TYPE_D:
1707             fprintf(file, "%dD", inst->src[i].d);
1708             break;
1709          case BRW_REGISTER_TYPE_UD:
1710             fprintf(file, "%uU", inst->src[i].ud);
1711             break;
1712          case BRW_REGISTER_TYPE_VF:
1713             fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
1714                     brw_vf_to_float((inst->src[i].ud >>  0) & 0xff),
1715                     brw_vf_to_float((inst->src[i].ud >>  8) & 0xff),
1716                     brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
1717                     brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
1718             break;
1719          default:
1720             fprintf(file, "???");
1721             break;
1722          }
1723          break;
1724       case ARF:
1725          switch (inst->src[i].nr) {
1726          case BRW_ARF_NULL:
1727             fprintf(file, "null");
1728             break;
1729          case BRW_ARF_ADDRESS:
1730             fprintf(file, "a0.%d", inst->src[i].subnr);
1731             break;
1732          case BRW_ARF_ACCUMULATOR:
1733             fprintf(file, "acc%d", inst->src[i].subnr);
1734             break;
1735          case BRW_ARF_FLAG:
1736             fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1737             break;
1738          default:
1739             fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1740             break;
1741          }
1742          break;
1743       case BAD_FILE:
1744          fprintf(file, "(null)");
1745          break;
1746       case MRF:
1747          unreachable("not reached");
1748       }
1749 
1750       if (inst->src[i].offset ||
1751           (inst->src[i].file == VGRF &&
1752            alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
1753          const unsigned reg_size = (inst->src[i].file == UNIFORM ? 16 : REG_SIZE);
1754          fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
1755                  inst->src[i].offset % reg_size);
1756       }
1757 
1758       if (inst->src[i].file != IMM) {
1759          static const char *chans[4] = {"x", "y", "z", "w"};
1760          fprintf(file, ".");
1761          for (int c = 0; c < 4; c++) {
1762             fprintf(file, "%s", chans[BRW_GET_SWZ(inst->src[i].swizzle, c)]);
1763          }
1764       }
1765 
1766       if (inst->src[i].abs)
1767          fprintf(file, "|");
1768 
1769       if (inst->src[i].file != IMM) {
1770          fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
1771       }
1772 
1773       if (i < 2 && inst->src[i + 1].file != BAD_FILE)
1774          fprintf(file, ", ");
1775    }
1776 
1777    if (inst->force_writemask_all)
1778       fprintf(file, " NoMask");
1779 
1780    if (inst->exec_size != 8)
1781       fprintf(file, " group%d", inst->group);
1782 
1783    fprintf(file, "\n");
1784 }
1785 
1786 
1787 int
setup_attributes(int payload_reg)1788 vec4_vs_visitor::setup_attributes(int payload_reg)
1789 {
1790    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1791       for (int i = 0; i < 3; i++) {
1792          if (inst->src[i].file == ATTR) {
1793             assert(inst->src[i].offset % REG_SIZE == 0);
1794             int grf = payload_reg + inst->src[i].nr +
1795                       inst->src[i].offset / REG_SIZE;
1796 
1797             struct brw_reg reg = brw_vec8_grf(grf, 0);
1798             reg.swizzle = inst->src[i].swizzle;
1799             reg.type = inst->src[i].type;
1800             reg.abs = inst->src[i].abs;
1801             reg.negate = inst->src[i].negate;
1802             inst->src[i] = reg;
1803          }
1804       }
1805    }
1806 
1807    return payload_reg + vs_prog_data->nr_attribute_slots;
1808 }
1809 
1810 int
setup_uniforms(int reg)1811 vec4_visitor::setup_uniforms(int reg)
1812 {
1813    prog_data->base.dispatch_grf_start_reg = reg;
1814 
1815    /* The pre-gen6 VS requires that some push constants get loaded no
1816     * matter what, or the GPU would hang.
1817     */
1818    if (devinfo->gen < 6 && this->uniforms == 0) {
1819       brw_stage_prog_data_add_params(stage_prog_data, 4);
1820       for (unsigned int i = 0; i < 4; i++) {
1821 	 unsigned int slot = this->uniforms * 4 + i;
1822 	 stage_prog_data->param[slot] = BRW_PARAM_BUILTIN_ZERO;
1823       }
1824 
1825       this->uniforms++;
1826       reg++;
1827    } else {
1828       reg += ALIGN(uniforms, 2) / 2;
1829    }
1830 
1831    for (int i = 0; i < 4; i++)
1832       reg += stage_prog_data->ubo_ranges[i].length;
1833 
1834    stage_prog_data->nr_params = this->uniforms * 4;
1835 
1836    prog_data->base.curb_read_length =
1837       reg - prog_data->base.dispatch_grf_start_reg;
1838 
1839    return reg;
1840 }
1841 
1842 void
setup_payload(void)1843 vec4_vs_visitor::setup_payload(void)
1844 {
1845    int reg = 0;
1846 
1847    /* The payload always contains important data in g0, which contains
1848     * the URB handles that are passed on to the URB write at the end
1849     * of the thread.  So, we always start push constants at g1.
1850     */
1851    reg++;
1852 
1853    reg = setup_uniforms(reg);
1854 
1855    reg = setup_attributes(reg);
1856 
1857    this->first_non_payload_grf = reg;
1858 }
1859 
1860 bool
lower_minmax()1861 vec4_visitor::lower_minmax()
1862 {
1863    assert(devinfo->gen < 6);
1864 
1865    bool progress = false;
1866 
1867    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1868       const vec4_builder ibld(this, block, inst);
1869 
1870       if (inst->opcode == BRW_OPCODE_SEL &&
1871           inst->predicate == BRW_PREDICATE_NONE) {
1872          /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
1873           *        the original SEL.L/GE instruction
1874           */
1875          ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
1876                   inst->conditional_mod);
1877          inst->predicate = BRW_PREDICATE_NORMAL;
1878          inst->conditional_mod = BRW_CONDITIONAL_NONE;
1879 
1880          progress = true;
1881       }
1882    }
1883 
1884    if (progress)
1885       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1886 
1887    return progress;
1888 }
1889 
1890 src_reg
get_timestamp()1891 vec4_visitor::get_timestamp()
1892 {
1893    assert(devinfo->gen == 7);
1894 
1895    src_reg ts = src_reg(brw_reg(BRW_ARCHITECTURE_REGISTER_FILE,
1896                                 BRW_ARF_TIMESTAMP,
1897                                 0,
1898                                 0,
1899                                 0,
1900                                 BRW_REGISTER_TYPE_UD,
1901                                 BRW_VERTICAL_STRIDE_0,
1902                                 BRW_WIDTH_4,
1903                                 BRW_HORIZONTAL_STRIDE_4,
1904                                 BRW_SWIZZLE_XYZW,
1905                                 WRITEMASK_XYZW));
1906 
1907    dst_reg dst = dst_reg(this, glsl_type::uvec4_type);
1908 
1909    vec4_instruction *mov = emit(MOV(dst, ts));
1910    /* We want to read the 3 fields we care about (mostly field 0, but also 2)
1911     * even if it's not enabled in the dispatch.
1912     */
1913    mov->force_writemask_all = true;
1914 
1915    return src_reg(dst);
1916 }
1917 
1918 void
emit_shader_time_begin()1919 vec4_visitor::emit_shader_time_begin()
1920 {
1921    current_annotation = "shader time start";
1922    shader_start_time = get_timestamp();
1923 }
1924 
1925 void
emit_shader_time_end()1926 vec4_visitor::emit_shader_time_end()
1927 {
1928    current_annotation = "shader time end";
1929    src_reg shader_end_time = get_timestamp();
1930 
1931 
1932    /* Check that there weren't any timestamp reset events (assuming these
1933     * were the only two timestamp reads that happened).
1934     */
1935    src_reg reset_end = shader_end_time;
1936    reset_end.swizzle = BRW_SWIZZLE_ZZZZ;
1937    vec4_instruction *test = emit(AND(dst_null_ud(), reset_end, brw_imm_ud(1u)));
1938    test->conditional_mod = BRW_CONDITIONAL_Z;
1939 
1940    emit(IF(BRW_PREDICATE_NORMAL));
1941 
1942    /* Take the current timestamp and get the delta. */
1943    shader_start_time.negate = true;
1944    dst_reg diff = dst_reg(this, glsl_type::uint_type);
1945    emit(ADD(diff, shader_start_time, shader_end_time));
1946 
1947    /* If there were no instructions between the two timestamp gets, the diff
1948     * is 2 cycles.  Remove that overhead, so I can forget about that when
1949     * trying to determine the time taken for single instructions.
1950     */
1951    emit(ADD(diff, src_reg(diff), brw_imm_ud(-2u)));
1952 
1953    emit_shader_time_write(0, src_reg(diff));
1954    emit_shader_time_write(1, brw_imm_ud(1u));
1955    emit(BRW_OPCODE_ELSE);
1956    emit_shader_time_write(2, brw_imm_ud(1u));
1957    emit(BRW_OPCODE_ENDIF);
1958 }
1959 
1960 void
emit_shader_time_write(int shader_time_subindex,src_reg value)1961 vec4_visitor::emit_shader_time_write(int shader_time_subindex, src_reg value)
1962 {
1963    dst_reg dst =
1964       dst_reg(this, glsl_type::get_array_instance(glsl_type::vec4_type, 2));
1965 
1966    dst_reg offset = dst;
1967    dst_reg time = dst;
1968    time.offset += REG_SIZE;
1969 
1970    offset.type = BRW_REGISTER_TYPE_UD;
1971    int index = shader_time_index * 3 + shader_time_subindex;
1972    emit(MOV(offset, brw_imm_d(index * BRW_SHADER_TIME_STRIDE)));
1973 
1974    time.type = BRW_REGISTER_TYPE_UD;
1975    emit(MOV(time, value));
1976 
1977    vec4_instruction *inst =
1978       emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
1979    inst->mlen = 2;
1980 }
1981 
1982 static bool
is_align1_df(vec4_instruction * inst)1983 is_align1_df(vec4_instruction *inst)
1984 {
1985    switch (inst->opcode) {
1986    case VEC4_OPCODE_DOUBLE_TO_F32:
1987    case VEC4_OPCODE_DOUBLE_TO_D32:
1988    case VEC4_OPCODE_DOUBLE_TO_U32:
1989    case VEC4_OPCODE_TO_DOUBLE:
1990    case VEC4_OPCODE_PICK_LOW_32BIT:
1991    case VEC4_OPCODE_PICK_HIGH_32BIT:
1992    case VEC4_OPCODE_SET_LOW_32BIT:
1993    case VEC4_OPCODE_SET_HIGH_32BIT:
1994       return true;
1995    default:
1996       return false;
1997    }
1998 }
1999 
2000 /**
2001  * Three source instruction must have a GRF/MRF destination register.
2002  * ARF NULL is not allowed.  Fix that up by allocating a temporary GRF.
2003  */
2004 void
fixup_3src_null_dest()2005 vec4_visitor::fixup_3src_null_dest()
2006 {
2007    bool progress = false;
2008 
2009    foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
2010       if (inst->is_3src(devinfo) && inst->dst.is_null()) {
2011          const unsigned size_written = type_sz(inst->dst.type);
2012          const unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
2013 
2014          inst->dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2015                             inst->dst.type);
2016          progress = true;
2017       }
2018    }
2019 
2020    if (progress)
2021       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL |
2022                           DEPENDENCY_VARIABLES);
2023 }
2024 
2025 void
convert_to_hw_regs()2026 vec4_visitor::convert_to_hw_regs()
2027 {
2028    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
2029       for (int i = 0; i < 3; i++) {
2030          class src_reg &src = inst->src[i];
2031          struct brw_reg reg;
2032          switch (src.file) {
2033          case VGRF: {
2034             reg = byte_offset(brw_vecn_grf(4, src.nr, 0), src.offset);
2035             reg.type = src.type;
2036             reg.abs = src.abs;
2037             reg.negate = src.negate;
2038             break;
2039          }
2040 
2041          case UNIFORM: {
2042             reg = stride(byte_offset(brw_vec4_grf(
2043                                         prog_data->base.dispatch_grf_start_reg +
2044                                         src.nr / 2, src.nr % 2 * 4),
2045                                      src.offset),
2046                          0, 4, 1);
2047             reg.type = src.type;
2048             reg.abs = src.abs;
2049             reg.negate = src.negate;
2050 
2051             /* This should have been moved to pull constants. */
2052             assert(!src.reladdr);
2053             break;
2054          }
2055 
2056          case FIXED_GRF:
2057             if (type_sz(src.type) == 8) {
2058                reg = src.as_brw_reg();
2059                break;
2060             }
2061             /* fallthrough */
2062          case ARF:
2063          case IMM:
2064             continue;
2065 
2066          case BAD_FILE:
2067             /* Probably unused. */
2068             reg = brw_null_reg();
2069             reg = retype(reg, src.type);
2070             break;
2071 
2072          case MRF:
2073          case ATTR:
2074             unreachable("not reached");
2075          }
2076 
2077          apply_logical_swizzle(&reg, inst, i);
2078          src = reg;
2079 
2080          /* From IVB PRM, vol4, part3, "General Restrictions on Regioning
2081           * Parameters":
2082           *
2083           *   "If ExecSize = Width and HorzStride ≠ 0, VertStride must be set
2084           *    to Width * HorzStride."
2085           *
2086           * We can break this rule with DF sources on DF align1
2087           * instructions, because the exec_size would be 4 and width is 4.
2088           * As we know we are not accessing to next GRF, it is safe to
2089           * set vstride to the formula given by the rule itself.
2090           */
2091          if (is_align1_df(inst) && (cvt(inst->exec_size) - 1) == src.width)
2092             src.vstride = src.width + src.hstride;
2093       }
2094 
2095       if (inst->is_3src(devinfo)) {
2096          /* 3-src instructions with scalar sources support arbitrary subnr,
2097           * but don't actually use swizzles.  Convert swizzle into subnr.
2098           * Skip this for double-precision instructions: RepCtrl=1 is not
2099           * allowed for them and needs special handling.
2100           */
2101          for (int i = 0; i < 3; i++) {
2102             if (inst->src[i].vstride == BRW_VERTICAL_STRIDE_0 &&
2103                 type_sz(inst->src[i].type) < 8) {
2104                assert(brw_is_single_value_swizzle(inst->src[i].swizzle));
2105                inst->src[i].subnr += 4 * BRW_GET_SWZ(inst->src[i].swizzle, 0);
2106             }
2107          }
2108       }
2109 
2110       dst_reg &dst = inst->dst;
2111       struct brw_reg reg;
2112 
2113       switch (inst->dst.file) {
2114       case VGRF:
2115          reg = byte_offset(brw_vec8_grf(dst.nr, 0), dst.offset);
2116          reg.type = dst.type;
2117          reg.writemask = dst.writemask;
2118          break;
2119 
2120       case MRF:
2121          reg = byte_offset(brw_message_reg(dst.nr), dst.offset);
2122          assert((reg.nr & ~BRW_MRF_COMPR4) < BRW_MAX_MRF(devinfo->gen));
2123          reg.type = dst.type;
2124          reg.writemask = dst.writemask;
2125          break;
2126 
2127       case ARF:
2128       case FIXED_GRF:
2129          reg = dst.as_brw_reg();
2130          break;
2131 
2132       case BAD_FILE:
2133          reg = brw_null_reg();
2134          reg = retype(reg, dst.type);
2135          break;
2136 
2137       case IMM:
2138       case ATTR:
2139       case UNIFORM:
2140          unreachable("not reached");
2141       }
2142 
2143       dst = reg;
2144    }
2145 }
2146 
2147 static bool
stage_uses_interleaved_attributes(unsigned stage,enum shader_dispatch_mode dispatch_mode)2148 stage_uses_interleaved_attributes(unsigned stage,
2149                                   enum shader_dispatch_mode dispatch_mode)
2150 {
2151    switch (stage) {
2152    case MESA_SHADER_TESS_EVAL:
2153       return true;
2154    case MESA_SHADER_GEOMETRY:
2155       return dispatch_mode != DISPATCH_MODE_4X2_DUAL_OBJECT;
2156    default:
2157       return false;
2158    }
2159 }
2160 
2161 /**
2162  * Get the closest native SIMD width supported by the hardware for instruction
2163  * \p inst.  The instruction will be left untouched by
2164  * vec4_visitor::lower_simd_width() if the returned value matches the
2165  * instruction's original execution size.
2166  */
2167 static unsigned
get_lowered_simd_width(const struct gen_device_info * devinfo,enum shader_dispatch_mode dispatch_mode,unsigned stage,const vec4_instruction * inst)2168 get_lowered_simd_width(const struct gen_device_info *devinfo,
2169                        enum shader_dispatch_mode dispatch_mode,
2170                        unsigned stage, const vec4_instruction *inst)
2171 {
2172    /* Do not split some instructions that require special handling */
2173    switch (inst->opcode) {
2174    case SHADER_OPCODE_GEN4_SCRATCH_READ:
2175    case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
2176       return inst->exec_size;
2177    default:
2178       break;
2179    }
2180 
2181    unsigned lowered_width = MIN2(16, inst->exec_size);
2182 
2183    /* We need to split some cases of double-precision instructions that write
2184     * 2 registers. We only need to care about this in gen7 because that is the
2185     * only hardware that implements fp64 in Align16.
2186     */
2187    if (devinfo->gen == 7 && inst->size_written > REG_SIZE) {
2188       /* Align16 8-wide double-precision SEL does not work well. Verified
2189        * empirically.
2190        */
2191       if (inst->opcode == BRW_OPCODE_SEL && type_sz(inst->dst.type) == 8)
2192          lowered_width = MIN2(lowered_width, 4);
2193 
2194       /* HSW PRM, 3D Media GPGPU Engine, Region Alignment Rules for Direct
2195        * Register Addressing:
2196        *
2197        *    "When destination spans two registers, the source MUST span two
2198        *     registers."
2199        */
2200       for (unsigned i = 0; i < 3; i++) {
2201          if (inst->src[i].file == BAD_FILE)
2202             continue;
2203          if (inst->size_read(i) <= REG_SIZE)
2204             lowered_width = MIN2(lowered_width, 4);
2205 
2206          /* Interleaved attribute setups use a vertical stride of 0, which
2207           * makes them hit the associated instruction decompression bug in gen7.
2208           * Split them to prevent this.
2209           */
2210          if (inst->src[i].file == ATTR &&
2211              stage_uses_interleaved_attributes(stage, dispatch_mode))
2212             lowered_width = MIN2(lowered_width, 4);
2213       }
2214    }
2215 
2216    /* IvyBridge can manage a maximum of 4 DFs per SIMD4x2 instruction, since
2217     * it doesn't support compression in Align16 mode, no matter if it has
2218     * force_writemask_all enabled or disabled (the latter is affected by the
2219     * compressed instruction bug in gen7, which is another reason to enforce
2220     * this limit).
2221     */
2222    if (devinfo->gen == 7 && !devinfo->is_haswell &&
2223        (get_exec_type_size(inst) == 8 || type_sz(inst->dst.type) == 8))
2224       lowered_width = MIN2(lowered_width, 4);
2225 
2226    return lowered_width;
2227 }
2228 
2229 static bool
dst_src_regions_overlap(vec4_instruction * inst)2230 dst_src_regions_overlap(vec4_instruction *inst)
2231 {
2232    if (inst->size_written == 0)
2233       return false;
2234 
2235    unsigned dst_start = inst->dst.offset;
2236    unsigned dst_end = dst_start + inst->size_written - 1;
2237    for (int i = 0; i < 3; i++) {
2238       if (inst->src[i].file == BAD_FILE)
2239          continue;
2240 
2241       if (inst->dst.file != inst->src[i].file ||
2242           inst->dst.nr != inst->src[i].nr)
2243          continue;
2244 
2245       unsigned src_start = inst->src[i].offset;
2246       unsigned src_end = src_start + inst->size_read(i) - 1;
2247 
2248       if ((dst_start >= src_start && dst_start <= src_end) ||
2249           (dst_end >= src_start && dst_end <= src_end) ||
2250           (dst_start <= src_start && dst_end >= src_end)) {
2251          return true;
2252       }
2253    }
2254 
2255    return false;
2256 }
2257 
2258 bool
lower_simd_width()2259 vec4_visitor::lower_simd_width()
2260 {
2261    bool progress = false;
2262 
2263    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2264       const unsigned lowered_width =
2265          get_lowered_simd_width(devinfo, prog_data->dispatch_mode, stage, inst);
2266       assert(lowered_width <= inst->exec_size);
2267       if (lowered_width == inst->exec_size)
2268          continue;
2269 
2270       /* We need to deal with source / destination overlaps when splitting.
2271        * The hardware supports reading from and writing to the same register
2272        * in the same instruction, but we need to be careful that each split
2273        * instruction we produce does not corrupt the source of the next.
2274        *
2275        * The easiest way to handle this is to make the split instructions write
2276        * to temporaries if there is an src/dst overlap and then move from the
2277        * temporaries to the original destination. We also need to consider
2278        * instructions that do partial writes via align1 opcodes, in which case
2279        * we need to make sure that the we initialize the temporary with the
2280        * value of the instruction's dst.
2281        */
2282       bool needs_temp = dst_src_regions_overlap(inst);
2283       for (unsigned n = 0; n < inst->exec_size / lowered_width; n++)  {
2284          unsigned channel_offset = lowered_width * n;
2285 
2286          unsigned size_written = lowered_width * type_sz(inst->dst.type);
2287 
2288          /* Create the split instruction from the original so that we copy all
2289           * relevant instruction fields, then set the width and calculate the
2290           * new dst/src regions.
2291           */
2292          vec4_instruction *linst = new(mem_ctx) vec4_instruction(*inst);
2293          linst->exec_size = lowered_width;
2294          linst->group = channel_offset;
2295          linst->size_written = size_written;
2296 
2297          /* Compute split dst region */
2298          dst_reg dst;
2299          if (needs_temp) {
2300             unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
2301             dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2302                          inst->dst.type);
2303             if (inst->is_align1_partial_write()) {
2304                vec4_instruction *copy = MOV(dst, src_reg(inst->dst));
2305                copy->exec_size = lowered_width;
2306                copy->group = channel_offset;
2307                copy->size_written = size_written;
2308                inst->insert_before(block, copy);
2309             }
2310          } else {
2311             dst = horiz_offset(inst->dst, channel_offset);
2312          }
2313          linst->dst = dst;
2314 
2315          /* Compute split source regions */
2316          for (int i = 0; i < 3; i++) {
2317             if (linst->src[i].file == BAD_FILE)
2318                continue;
2319 
2320             bool is_interleaved_attr =
2321                linst->src[i].file == ATTR &&
2322                stage_uses_interleaved_attributes(stage,
2323                                                  prog_data->dispatch_mode);
2324 
2325             if (!is_uniform(linst->src[i]) && !is_interleaved_attr)
2326                linst->src[i] = horiz_offset(linst->src[i], channel_offset);
2327          }
2328 
2329          inst->insert_before(block, linst);
2330 
2331          /* If we used a temporary to store the result of the split
2332           * instruction, copy the result to the original destination
2333           */
2334          if (needs_temp) {
2335             vec4_instruction *mov =
2336                MOV(offset(inst->dst, lowered_width, n), src_reg(dst));
2337             mov->exec_size = lowered_width;
2338             mov->group = channel_offset;
2339             mov->size_written = size_written;
2340             mov->predicate = inst->predicate;
2341             inst->insert_before(block, mov);
2342          }
2343       }
2344 
2345       inst->remove(block);
2346       progress = true;
2347    }
2348 
2349    if (progress)
2350       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
2351 
2352    return progress;
2353 }
2354 
2355 static brw_predicate
scalarize_predicate(brw_predicate predicate,unsigned writemask)2356 scalarize_predicate(brw_predicate predicate, unsigned writemask)
2357 {
2358    if (predicate != BRW_PREDICATE_NORMAL)
2359       return predicate;
2360 
2361    switch (writemask) {
2362    case WRITEMASK_X:
2363       return BRW_PREDICATE_ALIGN16_REPLICATE_X;
2364    case WRITEMASK_Y:
2365       return BRW_PREDICATE_ALIGN16_REPLICATE_Y;
2366    case WRITEMASK_Z:
2367       return BRW_PREDICATE_ALIGN16_REPLICATE_Z;
2368    case WRITEMASK_W:
2369       return BRW_PREDICATE_ALIGN16_REPLICATE_W;
2370    default:
2371       unreachable("invalid writemask");
2372    }
2373 }
2374 
2375 /* Gen7 has a hardware decompression bug that we can exploit to represent
2376  * handful of additional swizzles natively.
2377  */
2378 static bool
is_gen7_supported_64bit_swizzle(vec4_instruction * inst,unsigned arg)2379 is_gen7_supported_64bit_swizzle(vec4_instruction *inst, unsigned arg)
2380 {
2381    switch (inst->src[arg].swizzle) {
2382    case BRW_SWIZZLE_XXXX:
2383    case BRW_SWIZZLE_YYYY:
2384    case BRW_SWIZZLE_ZZZZ:
2385    case BRW_SWIZZLE_WWWW:
2386    case BRW_SWIZZLE_XYXY:
2387    case BRW_SWIZZLE_YXYX:
2388    case BRW_SWIZZLE_ZWZW:
2389    case BRW_SWIZZLE_WZWZ:
2390       return true;
2391    default:
2392       return false;
2393    }
2394 }
2395 
2396 /* 64-bit sources use regions with a width of 2. These 2 elements in each row
2397  * can be addressed using 32-bit swizzles (which is what the hardware supports)
2398  * but it also means that the swizzle we apply on the first two components of a
2399  * dvec4 is coupled with the swizzle we use for the last 2. In other words,
2400  * only some specific swizzle combinations can be natively supported.
2401  *
2402  * FIXME: we can go an step further and implement even more swizzle
2403  *        variations using only partial scalarization.
2404  *
2405  * For more details see:
2406  * https://bugs.freedesktop.org/show_bug.cgi?id=92760#c82
2407  */
2408 bool
is_supported_64bit_region(vec4_instruction * inst,unsigned arg)2409 vec4_visitor::is_supported_64bit_region(vec4_instruction *inst, unsigned arg)
2410 {
2411    const src_reg &src = inst->src[arg];
2412    assert(type_sz(src.type) == 8);
2413 
2414    /* Uniform regions have a vstride=0. Because we use 2-wide rows with
2415     * 64-bit regions it means that we cannot access components Z/W, so
2416     * return false for any such case. Interleaved attributes will also be
2417     * mapped to GRF registers with a vstride of 0, so apply the same
2418     * treatment.
2419     */
2420    if ((is_uniform(src) ||
2421         (stage_uses_interleaved_attributes(stage, prog_data->dispatch_mode) &&
2422          src.file == ATTR)) &&
2423        (brw_mask_for_swizzle(src.swizzle) & 12))
2424       return false;
2425 
2426    switch (src.swizzle) {
2427    case BRW_SWIZZLE_XYZW:
2428    case BRW_SWIZZLE_XXZZ:
2429    case BRW_SWIZZLE_YYWW:
2430    case BRW_SWIZZLE_YXWZ:
2431       return true;
2432    default:
2433       return devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg);
2434    }
2435 }
2436 
2437 bool
scalarize_df()2438 vec4_visitor::scalarize_df()
2439 {
2440    bool progress = false;
2441 
2442    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2443       /* Skip DF instructions that operate in Align1 mode */
2444       if (is_align1_df(inst))
2445          continue;
2446 
2447       /* Check if this is a double-precision instruction */
2448       bool is_double = type_sz(inst->dst.type) == 8;
2449       for (int arg = 0; !is_double && arg < 3; arg++) {
2450          is_double = inst->src[arg].file != BAD_FILE &&
2451                      type_sz(inst->src[arg].type) == 8;
2452       }
2453 
2454       if (!is_double)
2455          continue;
2456 
2457       /* Skip the lowering for specific regioning scenarios that we can
2458        * support natively.
2459        */
2460       bool skip_lowering = true;
2461 
2462       /* XY and ZW writemasks operate in 32-bit, which means that they don't
2463        * have a native 64-bit representation and they should always be split.
2464        */
2465       if (inst->dst.writemask == WRITEMASK_XY ||
2466           inst->dst.writemask == WRITEMASK_ZW) {
2467          skip_lowering = false;
2468       } else {
2469          for (unsigned i = 0; i < 3; i++) {
2470             if (inst->src[i].file == BAD_FILE || type_sz(inst->src[i].type) < 8)
2471                continue;
2472             skip_lowering = skip_lowering && is_supported_64bit_region(inst, i);
2473          }
2474       }
2475 
2476       if (skip_lowering)
2477          continue;
2478 
2479       /* Generate scalar instructions for each enabled channel */
2480       for (unsigned chan = 0; chan < 4; chan++) {
2481          unsigned chan_mask = 1 << chan;
2482          if (!(inst->dst.writemask & chan_mask))
2483             continue;
2484 
2485          vec4_instruction *scalar_inst = new(mem_ctx) vec4_instruction(*inst);
2486 
2487          for (unsigned i = 0; i < 3; i++) {
2488             unsigned swz = BRW_GET_SWZ(inst->src[i].swizzle, chan);
2489             scalar_inst->src[i].swizzle = BRW_SWIZZLE4(swz, swz, swz, swz);
2490          }
2491 
2492          scalar_inst->dst.writemask = chan_mask;
2493 
2494          if (inst->predicate != BRW_PREDICATE_NONE) {
2495             scalar_inst->predicate =
2496                scalarize_predicate(inst->predicate, chan_mask);
2497          }
2498 
2499          inst->insert_before(block, scalar_inst);
2500       }
2501 
2502       inst->remove(block);
2503       progress = true;
2504    }
2505 
2506    if (progress)
2507       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
2508 
2509    return progress;
2510 }
2511 
2512 bool
lower_64bit_mad_to_mul_add()2513 vec4_visitor::lower_64bit_mad_to_mul_add()
2514 {
2515    bool progress = false;
2516 
2517    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2518       if (inst->opcode != BRW_OPCODE_MAD)
2519          continue;
2520 
2521       if (type_sz(inst->dst.type) != 8)
2522          continue;
2523 
2524       dst_reg mul_dst = dst_reg(this, glsl_type::dvec4_type);
2525 
2526       /* Use the copy constructor so we copy all relevant instruction fields
2527        * from the original mad into the add and mul instructions
2528        */
2529       vec4_instruction *mul = new(mem_ctx) vec4_instruction(*inst);
2530       mul->opcode = BRW_OPCODE_MUL;
2531       mul->dst = mul_dst;
2532       mul->src[0] = inst->src[1];
2533       mul->src[1] = inst->src[2];
2534       mul->src[2].file = BAD_FILE;
2535 
2536       vec4_instruction *add = new(mem_ctx) vec4_instruction(*inst);
2537       add->opcode = BRW_OPCODE_ADD;
2538       add->src[0] = src_reg(mul_dst);
2539       add->src[1] = inst->src[0];
2540       add->src[2].file = BAD_FILE;
2541 
2542       inst->insert_before(block, mul);
2543       inst->insert_before(block, add);
2544       inst->remove(block);
2545 
2546       progress = true;
2547    }
2548 
2549    if (progress)
2550       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
2551 
2552    return progress;
2553 }
2554 
2555 /* The align16 hardware can only do 32-bit swizzle channels, so we need to
2556  * translate the logical 64-bit swizzle channels that we use in the Vec4 IR
2557  * to 32-bit swizzle channels in hardware registers.
2558  *
2559  * @inst and @arg identify the original vec4 IR source operand we need to
2560  * translate the swizzle for and @hw_reg is the hardware register where we
2561  * will write the hardware swizzle to use.
2562  *
2563  * This pass assumes that Align16/DF instructions have been fully scalarized
2564  * previously so there is just one 64-bit swizzle channel to deal with for any
2565  * given Vec4 IR source.
2566  */
2567 void
apply_logical_swizzle(struct brw_reg * hw_reg,vec4_instruction * inst,int arg)2568 vec4_visitor::apply_logical_swizzle(struct brw_reg *hw_reg,
2569                                     vec4_instruction *inst, int arg)
2570 {
2571    src_reg reg = inst->src[arg];
2572 
2573    if (reg.file == BAD_FILE || reg.file == BRW_IMMEDIATE_VALUE)
2574       return;
2575 
2576    /* If this is not a 64-bit operand or this is a scalar instruction we don't
2577     * need to do anything about the swizzles.
2578     */
2579    if(type_sz(reg.type) < 8 || is_align1_df(inst)) {
2580       hw_reg->swizzle = reg.swizzle;
2581       return;
2582    }
2583 
2584    /* Take the 64-bit logical swizzle channel and translate it to 32-bit */
2585    assert(brw_is_single_value_swizzle(reg.swizzle) ||
2586           is_supported_64bit_region(inst, arg));
2587 
2588    /* Apply the region <2, 2, 1> for GRF or <0, 2, 1> for uniforms, as align16
2589     * HW can only do 32-bit swizzle channels.
2590     */
2591    hw_reg->width = BRW_WIDTH_2;
2592 
2593    if (is_supported_64bit_region(inst, arg) &&
2594        !is_gen7_supported_64bit_swizzle(inst, arg)) {
2595       /* Supported 64-bit swizzles are those such that their first two
2596        * components, when expanded to 32-bit swizzles, match the semantics
2597        * of the original 64-bit swizzle with 2-wide row regioning.
2598        */
2599       unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2600       unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2601       hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2602                                      swizzle1 * 2, swizzle1 * 2 + 1);
2603    } else {
2604       /* If we got here then we have one of the following:
2605        *
2606        * 1. An unsupported swizzle, which should be single-value thanks to the
2607        *    scalarization pass.
2608        *
2609        * 2. A gen7 supported swizzle. These can be single-value or double-value
2610        *    swizzles. If the latter, they are never cross-dvec2 channels. For
2611        *    these we always need to activate the gen7 vstride=0 exploit.
2612        */
2613       unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2614       unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2615       assert((swizzle0 < 2) == (swizzle1 < 2));
2616 
2617       /* To gain access to Z/W components we need to select the second half
2618        * of the register and then use a X/Y swizzle to select Z/W respectively.
2619        */
2620       if (swizzle0 >= 2) {
2621          *hw_reg = suboffset(*hw_reg, 2);
2622          swizzle0 -= 2;
2623          swizzle1 -= 2;
2624       }
2625 
2626       /* All gen7-specific supported swizzles require the vstride=0 exploit */
2627       if (devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg))
2628          hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2629 
2630       /* Any 64-bit source with an offset at 16B is intended to address the
2631        * second half of a register and needs a vertical stride of 0 so we:
2632        *
2633        * 1. Don't violate register region restrictions.
2634        * 2. Activate the gen7 instruction decompresion bug exploit when
2635        *    execsize > 4
2636        */
2637       if (hw_reg->subnr % REG_SIZE == 16) {
2638          assert(devinfo->gen == 7);
2639          hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2640       }
2641 
2642       hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2643                                      swizzle1 * 2, swizzle1 * 2 + 1);
2644    }
2645 }
2646 
2647 void
invalidate_analysis(brw::analysis_dependency_class c)2648 vec4_visitor::invalidate_analysis(brw::analysis_dependency_class c)
2649 {
2650    backend_shader::invalidate_analysis(c);
2651    live_analysis.invalidate(c);
2652 }
2653 
2654 bool
run()2655 vec4_visitor::run()
2656 {
2657    if (shader_time_index >= 0)
2658       emit_shader_time_begin();
2659 
2660    emit_prolog();
2661 
2662    emit_nir_code();
2663    if (failed)
2664       return false;
2665    base_ir = NULL;
2666 
2667    emit_thread_end();
2668 
2669    calculate_cfg();
2670 
2671    /* Before any optimization, push array accesses out to scratch
2672     * space where we need them to be.  This pass may allocate new
2673     * virtual GRFs, so we want to do it early.  It also makes sure
2674     * that we have reladdr computations available for CSE, since we'll
2675     * often do repeated subexpressions for those.
2676     */
2677    move_grf_array_access_to_scratch();
2678    move_uniform_array_access_to_pull_constants();
2679 
2680    pack_uniform_registers();
2681    move_push_constants_to_pull_constants();
2682    split_virtual_grfs();
2683 
2684 #define OPT(pass, args...) ({                                          \
2685       pass_num++;                                                      \
2686       bool this_progress = pass(args);                                 \
2687                                                                        \
2688       if ((INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) {  \
2689          char filename[64];                                            \
2690          snprintf(filename, 64, "%s-%s-%02d-%02d-" #pass,              \
2691                   stage_abbrev, nir->info.name, iteration, pass_num); \
2692                                                                        \
2693          backend_shader::dump_instructions(filename);                  \
2694       }                                                                \
2695                                                                        \
2696       progress = progress || this_progress;                            \
2697       this_progress;                                                   \
2698    })
2699 
2700 
2701    if (INTEL_DEBUG & DEBUG_OPTIMIZER) {
2702       char filename[64];
2703       snprintf(filename, 64, "%s-%s-00-00-start",
2704                stage_abbrev, nir->info.name);
2705 
2706       backend_shader::dump_instructions(filename);
2707    }
2708 
2709    bool progress;
2710    int iteration = 0;
2711    int pass_num = 0;
2712    do {
2713       progress = false;
2714       pass_num = 0;
2715       iteration++;
2716 
2717       OPT(opt_predicated_break, this);
2718       OPT(opt_reduce_swizzle);
2719       OPT(dead_code_eliminate);
2720       OPT(dead_control_flow_eliminate, this);
2721       OPT(opt_copy_propagation);
2722       OPT(opt_cmod_propagation);
2723       OPT(opt_cse);
2724       OPT(opt_algebraic);
2725       OPT(opt_register_coalesce);
2726       OPT(eliminate_find_live_channel);
2727    } while (progress);
2728 
2729    pass_num = 0;
2730 
2731    if (OPT(opt_vector_float)) {
2732       OPT(opt_cse);
2733       OPT(opt_copy_propagation, false);
2734       OPT(opt_copy_propagation, true);
2735       OPT(dead_code_eliminate);
2736    }
2737 
2738    if (devinfo->gen <= 5 && OPT(lower_minmax)) {
2739       OPT(opt_cmod_propagation);
2740       OPT(opt_cse);
2741       OPT(opt_copy_propagation);
2742       OPT(dead_code_eliminate);
2743    }
2744 
2745    if (OPT(lower_simd_width)) {
2746       OPT(opt_copy_propagation);
2747       OPT(dead_code_eliminate);
2748    }
2749 
2750    if (failed)
2751       return false;
2752 
2753    OPT(lower_64bit_mad_to_mul_add);
2754 
2755    /* Run this before payload setup because tesselation shaders
2756     * rely on it to prevent cross dvec2 regioning on DF attributes
2757     * that are setup so that XY are on the second half of register and
2758     * ZW are in the first half of the next.
2759     */
2760    OPT(scalarize_df);
2761 
2762    setup_payload();
2763 
2764    if (INTEL_DEBUG & DEBUG_SPILL_VEC4) {
2765       /* Debug of register spilling: Go spill everything. */
2766       const int grf_count = alloc.count;
2767       float spill_costs[alloc.count];
2768       bool no_spill[alloc.count];
2769       evaluate_spill_costs(spill_costs, no_spill);
2770       for (int i = 0; i < grf_count; i++) {
2771          if (no_spill[i])
2772             continue;
2773          spill_reg(i);
2774       }
2775 
2776       /* We want to run this after spilling because 64-bit (un)spills need to
2777        * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2778        * messages that can produce unsupported 64-bit swizzle regions.
2779        */
2780       OPT(scalarize_df);
2781    }
2782 
2783    fixup_3src_null_dest();
2784 
2785    bool allocated_without_spills = reg_allocate();
2786 
2787    if (!allocated_without_spills) {
2788       compiler->shader_perf_log(log_data,
2789                                 "%s shader triggered register spilling.  "
2790                                 "Try reducing the number of live vec4 values "
2791                                 "to improve performance.\n",
2792                                 stage_name);
2793 
2794       while (!reg_allocate()) {
2795          if (failed)
2796             return false;
2797       }
2798 
2799       /* We want to run this after spilling because 64-bit (un)spills need to
2800        * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2801        * messages that can produce unsupported 64-bit swizzle regions.
2802        */
2803       OPT(scalarize_df);
2804    }
2805 
2806    opt_schedule_instructions();
2807 
2808    opt_set_dependency_control();
2809 
2810    convert_to_hw_regs();
2811 
2812    if (last_scratch > 0) {
2813       prog_data->base.total_scratch =
2814          brw_get_scratch_size(last_scratch * REG_SIZE);
2815    }
2816 
2817    return !failed;
2818 }
2819 
2820 } /* namespace brw */
2821 
2822 extern "C" {
2823 
2824 /**
2825  * Compile a vertex shader.
2826  *
2827  * Returns the final assembly and the program's size.
2828  */
2829 const unsigned *
brw_compile_vs(const struct brw_compiler * compiler,void * log_data,void * mem_ctx,const struct brw_vs_prog_key * key,struct brw_vs_prog_data * prog_data,nir_shader * nir,int shader_time_index,struct brw_compile_stats * stats,char ** error_str)2830 brw_compile_vs(const struct brw_compiler *compiler, void *log_data,
2831                void *mem_ctx,
2832                const struct brw_vs_prog_key *key,
2833                struct brw_vs_prog_data *prog_data,
2834                nir_shader *nir,
2835                int shader_time_index,
2836                struct brw_compile_stats *stats,
2837                char **error_str)
2838 {
2839    const bool is_scalar = compiler->scalar_stage[MESA_SHADER_VERTEX];
2840    brw_nir_apply_key(nir, compiler, &key->base, 8, is_scalar);
2841 
2842    const unsigned *assembly = NULL;
2843 
2844    if (prog_data->base.vue_map.varying_to_slot[VARYING_SLOT_EDGE] != -1) {
2845       /* If the output VUE map contains VARYING_SLOT_EDGE then we need to copy
2846        * the edge flag from VERT_ATTRIB_EDGEFLAG.  This will be done
2847        * automatically by brw_vec4_visitor::emit_urb_slot but we need to
2848        * ensure that prog_data->inputs_read is accurate.
2849        *
2850        * In order to make late NIR passes aware of the change, we actually
2851        * whack shader->info.inputs_read instead.  This is safe because we just
2852        * made a copy of the shader.
2853        */
2854       assert(!is_scalar);
2855       assert(key->copy_edgeflag);
2856       nir->info.inputs_read |= VERT_BIT_EDGEFLAG;
2857    }
2858 
2859    prog_data->inputs_read = nir->info.inputs_read;
2860    prog_data->double_inputs_read = nir->info.vs.double_inputs;
2861 
2862    brw_nir_lower_vs_inputs(nir, key->gl_attrib_wa_flags);
2863    brw_nir_lower_vue_outputs(nir);
2864    brw_postprocess_nir(nir, compiler, is_scalar);
2865 
2866    prog_data->base.clip_distance_mask =
2867       ((1 << nir->info.clip_distance_array_size) - 1);
2868    prog_data->base.cull_distance_mask =
2869       ((1 << nir->info.cull_distance_array_size) - 1) <<
2870       nir->info.clip_distance_array_size;
2871 
2872    unsigned nr_attribute_slots = util_bitcount64(prog_data->inputs_read);
2873 
2874    /* gl_VertexID and gl_InstanceID are system values, but arrive via an
2875     * incoming vertex attribute.  So, add an extra slot.
2876     */
2877    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_FIRST_VERTEX) ||
2878        BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_BASE_INSTANCE) ||
2879        BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) ||
2880        BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID)) {
2881       nr_attribute_slots++;
2882    }
2883 
2884    /* gl_DrawID and IsIndexedDraw share its very own vec4 */
2885    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_DRAW_ID) ||
2886        BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_IS_INDEXED_DRAW)) {
2887       nr_attribute_slots++;
2888    }
2889 
2890    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_IS_INDEXED_DRAW))
2891       prog_data->uses_is_indexed_draw = true;
2892 
2893    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_FIRST_VERTEX))
2894       prog_data->uses_firstvertex = true;
2895 
2896    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_BASE_INSTANCE))
2897       prog_data->uses_baseinstance = true;
2898 
2899    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_VERTEX_ID_ZERO_BASE))
2900       prog_data->uses_vertexid = true;
2901 
2902    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID))
2903       prog_data->uses_instanceid = true;
2904 
2905    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_DRAW_ID))
2906           prog_data->uses_drawid = true;
2907 
2908    /* The 3DSTATE_VS documentation lists the lower bound on "Vertex URB Entry
2909     * Read Length" as 1 in vec4 mode, and 0 in SIMD8 mode.  Empirically, in
2910     * vec4 mode, the hardware appears to wedge unless we read something.
2911     */
2912    if (is_scalar)
2913       prog_data->base.urb_read_length =
2914          DIV_ROUND_UP(nr_attribute_slots, 2);
2915    else
2916       prog_data->base.urb_read_length =
2917          DIV_ROUND_UP(MAX2(nr_attribute_slots, 1), 2);
2918 
2919    prog_data->nr_attribute_slots = nr_attribute_slots;
2920 
2921    /* Since vertex shaders reuse the same VUE entry for inputs and outputs
2922     * (overwriting the original contents), we need to make sure the size is
2923     * the larger of the two.
2924     */
2925    const unsigned vue_entries =
2926       MAX2(nr_attribute_slots, (unsigned)prog_data->base.vue_map.num_slots);
2927 
2928    if (compiler->devinfo->gen == 6) {
2929       prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 8);
2930    } else {
2931       prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 4);
2932    }
2933 
2934    if (INTEL_DEBUG & DEBUG_VS) {
2935       fprintf(stderr, "VS Output ");
2936       brw_print_vue_map(stderr, &prog_data->base.vue_map);
2937    }
2938 
2939    if (is_scalar) {
2940       prog_data->base.dispatch_mode = DISPATCH_MODE_SIMD8;
2941 
2942       fs_visitor v(compiler, log_data, mem_ctx, &key->base,
2943                    &prog_data->base.base,
2944                    nir, 8, shader_time_index);
2945       if (!v.run_vs()) {
2946          if (error_str)
2947             *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2948 
2949          return NULL;
2950       }
2951 
2952       prog_data->base.base.dispatch_grf_start_reg = v.payload.num_regs;
2953 
2954       fs_generator g(compiler, log_data, mem_ctx,
2955                      &prog_data->base.base, v.runtime_check_aads_emit,
2956                      MESA_SHADER_VERTEX);
2957       if (INTEL_DEBUG & DEBUG_VS) {
2958          const char *debug_name =
2959             ralloc_asprintf(mem_ctx, "%s vertex shader %s",
2960                             nir->info.label ? nir->info.label :
2961                                "unnamed",
2962                             nir->info.name);
2963 
2964          g.enable_debug(debug_name);
2965       }
2966       g.generate_code(v.cfg, 8, v.shader_stats,
2967                       v.performance_analysis.require(), stats);
2968       g.add_const_data(nir->constant_data, nir->constant_data_size);
2969       assembly = g.get_assembly();
2970    }
2971 
2972    if (!assembly) {
2973       prog_data->base.dispatch_mode = DISPATCH_MODE_4X2_DUAL_OBJECT;
2974 
2975       vec4_vs_visitor v(compiler, log_data, key, prog_data,
2976                         nir, mem_ctx, shader_time_index);
2977       if (!v.run()) {
2978          if (error_str)
2979             *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2980 
2981          return NULL;
2982       }
2983 
2984       assembly = brw_vec4_generate_assembly(compiler, log_data, mem_ctx,
2985                                             nir, &prog_data->base,
2986                                             v.cfg,
2987                                             v.performance_analysis.require(),
2988                                             stats);
2989    }
2990 
2991    return assembly;
2992 }
2993 
2994 } /* extern "C" */
2995