OSDN Git Service

i965/vec4: Do separate copy followed by constant propagation after opt_vector_float().
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / brw_vec4.cpp
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_vs.h"
28 #include "brw_dead_control_flow.h"
29
30 extern "C" {
31 #include "main/macros.h"
32 #include "main/shaderobj.h"
33 #include "program/prog_print.h"
34 #include "program/prog_parameter.h"
35 }
36
37 #define MAX_INSTRUCTION (1 << 30)
38
39 using namespace brw;
40
41 namespace brw {
42
43 /**
44  * Common helper for constructing swizzles.  When only a subset of
45  * channels of a vec4 are used, we don't want to reference the other
46  * channels, as that will tell optimization passes that those other
47  * channels are used.
48  */
49 unsigned
50 swizzle_for_size(int size)
51 {
52    static const unsigned size_swizzles[4] = {
53       BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
54       BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
55       BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
56       BRW_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
57    };
58
59    assert((size >= 1) && (size <= 4));
60    return size_swizzles[size - 1];
61 }
62
63 void
64 src_reg::init()
65 {
66    memset(this, 0, sizeof(*this));
67
68    this->file = BAD_FILE;
69 }
70
71 src_reg::src_reg(register_file file, int reg, const glsl_type *type)
72 {
73    init();
74
75    this->file = file;
76    this->reg = reg;
77    if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
78       this->swizzle = swizzle_for_size(type->vector_elements);
79    else
80       this->swizzle = BRW_SWIZZLE_XYZW;
81 }
82
83 /** Generic unset register constructor. */
84 src_reg::src_reg()
85 {
86    init();
87 }
88
89 src_reg::src_reg(float f)
90 {
91    init();
92
93    this->file = IMM;
94    this->type = BRW_REGISTER_TYPE_F;
95    this->fixed_hw_reg.dw1.f = f;
96 }
97
98 src_reg::src_reg(uint32_t u)
99 {
100    init();
101
102    this->file = IMM;
103    this->type = BRW_REGISTER_TYPE_UD;
104    this->fixed_hw_reg.dw1.ud = u;
105 }
106
107 src_reg::src_reg(int32_t i)
108 {
109    init();
110
111    this->file = IMM;
112    this->type = BRW_REGISTER_TYPE_D;
113    this->fixed_hw_reg.dw1.d = i;
114 }
115
116 src_reg::src_reg(uint8_t vf[4])
117 {
118    init();
119
120    this->file = IMM;
121    this->type = BRW_REGISTER_TYPE_VF;
122    memcpy(&this->fixed_hw_reg.dw1.ud, vf, sizeof(unsigned));
123 }
124
125 src_reg::src_reg(uint8_t vf0, uint8_t vf1, uint8_t vf2, uint8_t vf3)
126 {
127    init();
128
129    this->file = IMM;
130    this->type = BRW_REGISTER_TYPE_VF;
131    this->fixed_hw_reg.dw1.ud = (vf0 <<  0) |
132                                (vf1 <<  8) |
133                                (vf2 << 16) |
134                                (vf3 << 24);
135 }
136
137 src_reg::src_reg(struct brw_reg reg)
138 {
139    init();
140
141    this->file = HW_REG;
142    this->fixed_hw_reg = reg;
143    this->type = reg.type;
144 }
145
146 src_reg::src_reg(dst_reg reg)
147 {
148    init();
149
150    this->file = reg.file;
151    this->reg = reg.reg;
152    this->reg_offset = reg.reg_offset;
153    this->type = reg.type;
154    this->reladdr = reg.reladdr;
155    this->fixed_hw_reg = reg.fixed_hw_reg;
156
157    int swizzles[4];
158    int next_chan = 0;
159    int last = 0;
160
161    for (int i = 0; i < 4; i++) {
162       if (!(reg.writemask & (1 << i)))
163          continue;
164
165       swizzles[next_chan++] = last = i;
166    }
167
168    for (; next_chan < 4; next_chan++) {
169       swizzles[next_chan] = last;
170    }
171
172    this->swizzle = BRW_SWIZZLE4(swizzles[0], swizzles[1],
173                                 swizzles[2], swizzles[3]);
174 }
175
176 void
177 dst_reg::init()
178 {
179    memset(this, 0, sizeof(*this));
180    this->file = BAD_FILE;
181    this->writemask = WRITEMASK_XYZW;
182 }
183
184 dst_reg::dst_reg()
185 {
186    init();
187 }
188
189 dst_reg::dst_reg(register_file file, int reg)
190 {
191    init();
192
193    this->file = file;
194    this->reg = reg;
195 }
196
197 dst_reg::dst_reg(register_file file, int reg, const glsl_type *type,
198                  int writemask)
199 {
200    init();
201
202    this->file = file;
203    this->reg = reg;
204    this->type = brw_type_for_base_type(type);
205    this->writemask = writemask;
206 }
207
208 dst_reg::dst_reg(struct brw_reg reg)
209 {
210    init();
211
212    this->file = HW_REG;
213    this->fixed_hw_reg = reg;
214    this->type = reg.type;
215 }
216
217 dst_reg::dst_reg(src_reg reg)
218 {
219    init();
220
221    this->file = reg.file;
222    this->reg = reg.reg;
223    this->reg_offset = reg.reg_offset;
224    this->type = reg.type;
225    /* How should we do writemasking when converting from a src_reg?  It seems
226     * pretty obvious that for src.xxxx the caller wants to write to src.x, but
227     * what about for src.wx?  Just special-case src.xxxx for now.
228     */
229    if (reg.swizzle == BRW_SWIZZLE_XXXX)
230       this->writemask = WRITEMASK_X;
231    else
232       this->writemask = WRITEMASK_XYZW;
233    this->reladdr = reg.reladdr;
234    this->fixed_hw_reg = reg.fixed_hw_reg;
235 }
236
237 bool
238 vec4_instruction::is_send_from_grf()
239 {
240    switch (opcode) {
241    case SHADER_OPCODE_SHADER_TIME_ADD:
242    case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
243       return true;
244    default:
245       return false;
246    }
247 }
248
249 bool
250 vec4_instruction::can_do_source_mods(struct brw_context *brw)
251 {
252    if (brw->gen == 6 && is_math())
253       return false;
254
255    if (is_send_from_grf())
256       return false;
257
258    if (!backend_instruction::can_do_source_mods())
259       return false;
260
261    return true;
262 }
263
264 /**
265  * Returns how many MRFs an opcode will write over.
266  *
267  * Note that this is not the 0 or 1 implied writes in an actual gen
268  * instruction -- the generate_* functions generate additional MOVs
269  * for setup.
270  */
271 int
272 vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
273 {
274    if (inst->mlen == 0)
275       return 0;
276
277    switch (inst->opcode) {
278    case SHADER_OPCODE_RCP:
279    case SHADER_OPCODE_RSQ:
280    case SHADER_OPCODE_SQRT:
281    case SHADER_OPCODE_EXP2:
282    case SHADER_OPCODE_LOG2:
283    case SHADER_OPCODE_SIN:
284    case SHADER_OPCODE_COS:
285       return 1;
286    case SHADER_OPCODE_INT_QUOTIENT:
287    case SHADER_OPCODE_INT_REMAINDER:
288    case SHADER_OPCODE_POW:
289       return 2;
290    case VS_OPCODE_URB_WRITE:
291       return 1;
292    case VS_OPCODE_PULL_CONSTANT_LOAD:
293       return 2;
294    case SHADER_OPCODE_GEN4_SCRATCH_READ:
295       return 2;
296    case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
297       return 3;
298    case GS_OPCODE_URB_WRITE:
299    case GS_OPCODE_URB_WRITE_ALLOCATE:
300    case GS_OPCODE_THREAD_END:
301       return 0;
302    case GS_OPCODE_FF_SYNC:
303       return 1;
304    case SHADER_OPCODE_SHADER_TIME_ADD:
305       return 0;
306    case SHADER_OPCODE_TEX:
307    case SHADER_OPCODE_TXL:
308    case SHADER_OPCODE_TXD:
309    case SHADER_OPCODE_TXF:
310    case SHADER_OPCODE_TXF_CMS:
311    case SHADER_OPCODE_TXF_MCS:
312    case SHADER_OPCODE_TXS:
313    case SHADER_OPCODE_TG4:
314    case SHADER_OPCODE_TG4_OFFSET:
315       return inst->header_present ? 1 : 0;
316    case SHADER_OPCODE_UNTYPED_ATOMIC:
317    case SHADER_OPCODE_UNTYPED_SURFACE_READ:
318       return 0;
319    default:
320       unreachable("not reached");
321    }
322 }
323
324 bool
325 src_reg::equals(const src_reg &r) const
326 {
327    return (file == r.file &&
328            reg == r.reg &&
329            reg_offset == r.reg_offset &&
330            type == r.type &&
331            negate == r.negate &&
332            abs == r.abs &&
333            swizzle == r.swizzle &&
334            !reladdr && !r.reladdr &&
335            memcmp(&fixed_hw_reg, &r.fixed_hw_reg,
336                   sizeof(fixed_hw_reg)) == 0);
337 }
338
339 bool
340 vec4_visitor::opt_vector_float()
341 {
342    bool progress = false;
343
344    int last_reg = -1;
345    int remaining_channels;
346    uint8_t imm[4];
347    int inst_count;
348    vec4_instruction *imm_inst[4];
349
350    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
351       if (last_reg != inst->dst.reg) {
352          last_reg = inst->dst.reg;
353          remaining_channels = WRITEMASK_XYZW;
354
355          inst_count = 0;
356       }
357
358       if (inst->opcode != BRW_OPCODE_MOV ||
359           inst->dst.writemask == WRITEMASK_XYZW ||
360           inst->src[0].file != IMM)
361          continue;
362
363       int vf = brw_float_to_vf(inst->src[0].fixed_hw_reg.dw1.f);
364       if (vf == -1)
365          continue;
366
367       if ((inst->dst.writemask & WRITEMASK_X) != 0)
368          imm[0] = vf;
369       if ((inst->dst.writemask & WRITEMASK_Y) != 0)
370          imm[1] = vf;
371       if ((inst->dst.writemask & WRITEMASK_Z) != 0)
372          imm[2] = vf;
373       if ((inst->dst.writemask & WRITEMASK_W) != 0)
374          imm[3] = vf;
375
376       imm_inst[inst_count++] = inst;
377
378       remaining_channels &= ~inst->dst.writemask;
379       if (remaining_channels == 0) {
380          vec4_instruction *mov = MOV(inst->dst, imm);
381          mov->dst.type = BRW_REGISTER_TYPE_F;
382          mov->dst.writemask = WRITEMASK_XYZW;
383          inst->insert_after(block, mov);
384          last_reg = -1;
385
386          for (int i = 0; i < inst_count; i++) {
387             imm_inst[i]->remove(block);
388          }
389          progress = true;
390       }
391    }
392
393    if (progress)
394       invalidate_live_intervals();
395
396    return progress;
397 }
398
399 /* Replaces unused channels of a swizzle with channels that are used.
400  *
401  * For instance, this pass transforms
402  *
403  *    mov vgrf4.yz, vgrf5.wxzy
404  *
405  * into
406  *
407  *    mov vgrf4.yz, vgrf5.xxzx
408  *
409  * This eliminates false uses of some channels, letting dead code elimination
410  * remove the instructions that wrote them.
411  */
412 bool
413 vec4_visitor::opt_reduce_swizzle()
414 {
415    bool progress = false;
416
417    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
418       if (inst->dst.file == BAD_FILE || inst->dst.file == HW_REG)
419          continue;
420
421       int swizzle[4];
422
423       /* Determine which channels of the sources are read. */
424       switch (inst->opcode) {
425       case VEC4_OPCODE_PACK_BYTES:
426          swizzle[0] = 0;
427          swizzle[1] = 1;
428          swizzle[2] = 2;
429          swizzle[3] = 3;
430          break;
431       case BRW_OPCODE_DP4:
432       case BRW_OPCODE_DPH: /* FINISHME: DPH reads only three channels of src0,
433                             *           but all four of src1.
434                             */
435          swizzle[0] = 0;
436          swizzle[1] = 1;
437          swizzle[2] = 2;
438          swizzle[3] = 3;
439          break;
440       case BRW_OPCODE_DP3:
441          swizzle[0] = 0;
442          swizzle[1] = 1;
443          swizzle[2] = 2;
444          swizzle[3] = -1;
445          break;
446       case BRW_OPCODE_DP2:
447          swizzle[0] = 0;
448          swizzle[1] = 1;
449          swizzle[2] = -1;
450          swizzle[3] = -1;
451          break;
452       default:
453          swizzle[0] = inst->dst.writemask & WRITEMASK_X ? 0 : -1;
454          swizzle[1] = inst->dst.writemask & WRITEMASK_Y ? 1 : -1;
455          swizzle[2] = inst->dst.writemask & WRITEMASK_Z ? 2 : -1;
456          swizzle[3] = inst->dst.writemask & WRITEMASK_W ? 3 : -1;
457          break;
458       }
459
460       /* Resolve unread channels (-1) by assigning them the swizzle of the
461        * first channel that is used.
462        */
463       int first_used_channel = 0;
464       for (int i = 0; i < 4; i++) {
465          if (swizzle[i] != -1) {
466             first_used_channel = swizzle[i];
467             break;
468          }
469       }
470       for (int i = 0; i < 4; i++) {
471          if (swizzle[i] == -1) {
472             swizzle[i] = first_used_channel;
473          }
474       }
475
476       /* Update sources' swizzles. */
477       for (int i = 0; i < 3; i++) {
478          if (inst->src[i].file != GRF &&
479              inst->src[i].file != ATTR &&
480              inst->src[i].file != UNIFORM)
481             continue;
482
483          int swiz[4];
484          for (int j = 0; j < 4; j++) {
485             swiz[j] = BRW_GET_SWZ(inst->src[i].swizzle, swizzle[j]);
486          }
487
488          unsigned new_swizzle = BRW_SWIZZLE4(swiz[0], swiz[1], swiz[2], swiz[3]);
489          if (inst->src[i].swizzle != new_swizzle) {
490             inst->src[i].swizzle = new_swizzle;
491             progress = true;
492          }
493       }
494    }
495
496    if (progress)
497       invalidate_live_intervals();
498
499    return progress;
500 }
501
502 void
503 vec4_visitor::split_uniform_registers()
504 {
505    /* Prior to this, uniforms have been in an array sized according to
506     * the number of vector uniforms present, sparsely filled (so an
507     * aggregate results in reg indices being skipped over).  Now we're
508     * going to cut those aggregates up so each .reg index is one
509     * vector.  The goal is to make elimination of unused uniform
510     * components easier later.
511     */
512    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
513       for (int i = 0 ; i < 3; i++) {
514          if (inst->src[i].file != UNIFORM)
515             continue;
516
517          assert(!inst->src[i].reladdr);
518
519          inst->src[i].reg += inst->src[i].reg_offset;
520          inst->src[i].reg_offset = 0;
521       }
522    }
523
524    /* Update that everything is now vector-sized. */
525    for (int i = 0; i < this->uniforms; i++) {
526       this->uniform_size[i] = 1;
527    }
528 }
529
530 void
531 vec4_visitor::pack_uniform_registers()
532 {
533    bool uniform_used[this->uniforms];
534    int new_loc[this->uniforms];
535    int new_chan[this->uniforms];
536
537    memset(uniform_used, 0, sizeof(uniform_used));
538    memset(new_loc, 0, sizeof(new_loc));
539    memset(new_chan, 0, sizeof(new_chan));
540
541    /* Find which uniform vectors are actually used by the program.  We
542     * expect unused vector elements when we've moved array access out
543     * to pull constants, and from some GLSL code generators like wine.
544     */
545    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
546       for (int i = 0 ; i < 3; i++) {
547          if (inst->src[i].file != UNIFORM)
548             continue;
549
550          uniform_used[inst->src[i].reg] = true;
551       }
552    }
553
554    int new_uniform_count = 0;
555
556    /* Now, figure out a packing of the live uniform vectors into our
557     * push constants.
558     */
559    for (int src = 0; src < uniforms; src++) {
560       assert(src < uniform_array_size);
561       int size = this->uniform_vector_size[src];
562
563       if (!uniform_used[src]) {
564          this->uniform_vector_size[src] = 0;
565          continue;
566       }
567
568       int dst;
569       /* Find the lowest place we can slot this uniform in. */
570       for (dst = 0; dst < src; dst++) {
571          if (this->uniform_vector_size[dst] + size <= 4)
572             break;
573       }
574
575       if (src == dst) {
576          new_loc[src] = dst;
577          new_chan[src] = 0;
578       } else {
579          new_loc[src] = dst;
580          new_chan[src] = this->uniform_vector_size[dst];
581
582          /* Move the references to the data */
583          for (int j = 0; j < size; j++) {
584             stage_prog_data->param[dst * 4 + new_chan[src] + j] =
585                stage_prog_data->param[src * 4 + j];
586          }
587
588          this->uniform_vector_size[dst] += size;
589          this->uniform_vector_size[src] = 0;
590       }
591
592       new_uniform_count = MAX2(new_uniform_count, dst + 1);
593    }
594
595    this->uniforms = new_uniform_count;
596
597    /* Now, update the instructions for our repacked uniforms. */
598    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
599       for (int i = 0 ; i < 3; i++) {
600          int src = inst->src[i].reg;
601
602          if (inst->src[i].file != UNIFORM)
603             continue;
604
605          inst->src[i].reg = new_loc[src];
606
607          int sx = BRW_GET_SWZ(inst->src[i].swizzle, 0) + new_chan[src];
608          int sy = BRW_GET_SWZ(inst->src[i].swizzle, 1) + new_chan[src];
609          int sz = BRW_GET_SWZ(inst->src[i].swizzle, 2) + new_chan[src];
610          int sw = BRW_GET_SWZ(inst->src[i].swizzle, 3) + new_chan[src];
611          inst->src[i].swizzle = BRW_SWIZZLE4(sx, sy, sz, sw);
612       }
613    }
614 }
615
616 /**
617  * Does algebraic optimizations (0 * a = 0, 1 * a = a, a + 0 = a).
618  *
619  * While GLSL IR also performs this optimization, we end up with it in
620  * our instruction stream for a couple of reasons.  One is that we
621  * sometimes generate silly instructions, for example in array access
622  * where we'll generate "ADD offset, index, base" even if base is 0.
623  * The other is that GLSL IR's constant propagation doesn't track the
624  * components of aggregates, so some VS patterns (initialize matrix to
625  * 0, accumulate in vertex blending factors) end up breaking down to
626  * instructions involving 0.
627  */
628 bool
629 vec4_visitor::opt_algebraic()
630 {
631    bool progress = false;
632
633    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
634       switch (inst->opcode) {
635       case BRW_OPCODE_MOV:
636          if (inst->src[0].file != IMM)
637             break;
638
639          if (inst->saturate) {
640             if (inst->dst.type != inst->src[0].type)
641                assert(!"unimplemented: saturate mixed types");
642
643             if (brw_saturate_immediate(inst->dst.type,
644                                        &inst->src[0].fixed_hw_reg)) {
645                inst->saturate = false;
646                progress = true;
647             }
648          }
649          break;
650
651       case VEC4_OPCODE_UNPACK_UNIFORM:
652          if (inst->src[0].file != UNIFORM) {
653             inst->opcode = BRW_OPCODE_MOV;
654             progress = true;
655          }
656          break;
657
658       case BRW_OPCODE_ADD:
659          if (inst->src[1].is_zero()) {
660             inst->opcode = BRW_OPCODE_MOV;
661             inst->src[1] = src_reg();
662             progress = true;
663          }
664          break;
665
666       case BRW_OPCODE_MUL:
667          if (inst->src[1].is_zero()) {
668             inst->opcode = BRW_OPCODE_MOV;
669             switch (inst->src[0].type) {
670             case BRW_REGISTER_TYPE_F:
671                inst->src[0] = src_reg(0.0f);
672                break;
673             case BRW_REGISTER_TYPE_D:
674                inst->src[0] = src_reg(0);
675                break;
676             case BRW_REGISTER_TYPE_UD:
677                inst->src[0] = src_reg(0u);
678                break;
679             default:
680                unreachable("not reached");
681             }
682             inst->src[1] = src_reg();
683             progress = true;
684          } else if (inst->src[1].is_one()) {
685             inst->opcode = BRW_OPCODE_MOV;
686             inst->src[1] = src_reg();
687             progress = true;
688          }
689          break;
690       case SHADER_OPCODE_RCP: {
691          vec4_instruction *prev = (vec4_instruction *)inst->prev;
692          if (prev->opcode == SHADER_OPCODE_SQRT) {
693             if (inst->src[0].equals(src_reg(prev->dst))) {
694                inst->opcode = SHADER_OPCODE_RSQ;
695                inst->src[0] = prev->src[0];
696                progress = true;
697             }
698          }
699          break;
700       }
701       default:
702          break;
703       }
704    }
705
706    if (progress)
707       invalidate_live_intervals();
708
709    return progress;
710 }
711
712 /**
713  * Only a limited number of hardware registers may be used for push
714  * constants, so this turns access to the overflowed constants into
715  * pull constants.
716  */
717 void
718 vec4_visitor::move_push_constants_to_pull_constants()
719 {
720    int pull_constant_loc[this->uniforms];
721
722    /* Only allow 32 registers (256 uniform components) as push constants,
723     * which is the limit on gen6.
724     *
725     * If changing this value, note the limitation about total_regs in
726     * brw_curbe.c.
727     */
728    int max_uniform_components = 32 * 8;
729    if (this->uniforms * 4 <= max_uniform_components)
730       return;
731
732    /* Make some sort of choice as to which uniforms get sent to pull
733     * constants.  We could potentially do something clever here like
734     * look for the most infrequently used uniform vec4s, but leave
735     * that for later.
736     */
737    for (int i = 0; i < this->uniforms * 4; i += 4) {
738       pull_constant_loc[i / 4] = -1;
739
740       if (i >= max_uniform_components) {
741          const gl_constant_value **values = &stage_prog_data->param[i];
742
743          /* Try to find an existing copy of this uniform in the pull
744           * constants if it was part of an array access already.
745           */
746          for (unsigned int j = 0; j < stage_prog_data->nr_pull_params; j += 4) {
747             int matches;
748
749             for (matches = 0; matches < 4; matches++) {
750                if (stage_prog_data->pull_param[j + matches] != values[matches])
751                   break;
752             }
753
754             if (matches == 4) {
755                pull_constant_loc[i / 4] = j / 4;
756                break;
757             }
758          }
759
760          if (pull_constant_loc[i / 4] == -1) {
761             assert(stage_prog_data->nr_pull_params % 4 == 0);
762             pull_constant_loc[i / 4] = stage_prog_data->nr_pull_params / 4;
763
764             for (int j = 0; j < 4; j++) {
765                stage_prog_data->pull_param[stage_prog_data->nr_pull_params++] =
766                   values[j];
767             }
768          }
769       }
770    }
771
772    /* Now actually rewrite usage of the things we've moved to pull
773     * constants.
774     */
775    foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
776       for (int i = 0 ; i < 3; i++) {
777          if (inst->src[i].file != UNIFORM ||
778              pull_constant_loc[inst->src[i].reg] == -1)
779             continue;
780
781          int uniform = inst->src[i].reg;
782
783          dst_reg temp = dst_reg(this, glsl_type::vec4_type);
784
785          emit_pull_constant_load(block, inst, temp, inst->src[i],
786                                  pull_constant_loc[uniform]);
787
788          inst->src[i].file = temp.file;
789          inst->src[i].reg = temp.reg;
790          inst->src[i].reg_offset = temp.reg_offset;
791          inst->src[i].reladdr = NULL;
792       }
793    }
794
795    /* Repack push constants to remove the now-unused ones. */
796    pack_uniform_registers();
797 }
798
799 /* Conditions for which we want to avoid setting the dependency control bits */
800 bool
801 vec4_visitor::is_dep_ctrl_unsafe(const vec4_instruction *inst)
802 {
803 #define IS_DWORD(reg) \
804    (reg.type == BRW_REGISTER_TYPE_UD || \
805     reg.type == BRW_REGISTER_TYPE_D)
806
807    /* From the destination hazard section of the spec:
808     * > Instructions other than send, may use this control as long as operations
809     * > that have different pipeline latencies are not mixed.
810     */
811    if (brw->gen >= 8) {
812       if (inst->opcode == BRW_OPCODE_MUL &&
813          IS_DWORD(inst->src[0]) &&
814          IS_DWORD(inst->src[1]))
815          return true;
816    }
817 #undef IS_DWORD
818
819    /*
820     * mlen:
821     * In the presence of send messages, totally interrupt dependency
822     * control. They're long enough that the chance of dependency
823     * control around them just doesn't matter.
824     *
825     * predicate:
826     * From the Ivy Bridge PRM, volume 4 part 3.7, page 80:
827     * When a sequence of NoDDChk and NoDDClr are used, the last instruction that
828     * completes the scoreboard clear must have a non-zero execution mask. This
829     * means, if any kind of predication can change the execution mask or channel
830     * enable of the last instruction, the optimization must be avoided. This is
831     * to avoid instructions being shot down the pipeline when no writes are
832     * required.
833     *
834     * math:
835     * Dependency control does not work well over math instructions.
836     * NB: Discovered empirically
837     */
838    return (inst->mlen || inst->predicate || inst->is_math());
839 }
840
841 /**
842  * Sets the dependency control fields on instructions after register
843  * allocation and before the generator is run.
844  *
845  * When you have a sequence of instructions like:
846  *
847  * DP4 temp.x vertex uniform[0]
848  * DP4 temp.y vertex uniform[0]
849  * DP4 temp.z vertex uniform[0]
850  * DP4 temp.w vertex uniform[0]
851  *
852  * The hardware doesn't know that it can actually run the later instructions
853  * while the previous ones are in flight, producing stalls.  However, we have
854  * manual fields we can set in the instructions that let it do so.
855  */
856 void
857 vec4_visitor::opt_set_dependency_control()
858 {
859    vec4_instruction *last_grf_write[BRW_MAX_GRF];
860    uint8_t grf_channels_written[BRW_MAX_GRF];
861    vec4_instruction *last_mrf_write[BRW_MAX_GRF];
862    uint8_t mrf_channels_written[BRW_MAX_GRF];
863
864    assert(prog_data->total_grf ||
865           !"Must be called after register allocation");
866
867    foreach_block (block, cfg) {
868       memset(last_grf_write, 0, sizeof(last_grf_write));
869       memset(last_mrf_write, 0, sizeof(last_mrf_write));
870
871       foreach_inst_in_block (vec4_instruction, inst, block) {
872          /* If we read from a register that we were doing dependency control
873           * on, don't do dependency control across the read.
874           */
875          for (int i = 0; i < 3; i++) {
876             int reg = inst->src[i].reg + inst->src[i].reg_offset;
877             if (inst->src[i].file == GRF) {
878                last_grf_write[reg] = NULL;
879             } else if (inst->src[i].file == HW_REG) {
880                memset(last_grf_write, 0, sizeof(last_grf_write));
881                break;
882             }
883             assert(inst->src[i].file != MRF);
884          }
885
886          if (is_dep_ctrl_unsafe(inst)) {
887             memset(last_grf_write, 0, sizeof(last_grf_write));
888             memset(last_mrf_write, 0, sizeof(last_mrf_write));
889             continue;
890          }
891
892          /* Now, see if we can do dependency control for this instruction
893           * against a previous one writing to its destination.
894           */
895          int reg = inst->dst.reg + inst->dst.reg_offset;
896          if (inst->dst.file == GRF) {
897             if (last_grf_write[reg] &&
898                 !(inst->dst.writemask & grf_channels_written[reg])) {
899                last_grf_write[reg]->no_dd_clear = true;
900                inst->no_dd_check = true;
901             } else {
902                grf_channels_written[reg] = 0;
903             }
904
905             last_grf_write[reg] = inst;
906             grf_channels_written[reg] |= inst->dst.writemask;
907          } else if (inst->dst.file == MRF) {
908             if (last_mrf_write[reg] &&
909                 !(inst->dst.writemask & mrf_channels_written[reg])) {
910                last_mrf_write[reg]->no_dd_clear = true;
911                inst->no_dd_check = true;
912             } else {
913                mrf_channels_written[reg] = 0;
914             }
915
916             last_mrf_write[reg] = inst;
917             mrf_channels_written[reg] |= inst->dst.writemask;
918          } else if (inst->dst.reg == HW_REG) {
919             if (inst->dst.fixed_hw_reg.file == BRW_GENERAL_REGISTER_FILE)
920                memset(last_grf_write, 0, sizeof(last_grf_write));
921             if (inst->dst.fixed_hw_reg.file == BRW_MESSAGE_REGISTER_FILE)
922                memset(last_mrf_write, 0, sizeof(last_mrf_write));
923          }
924       }
925    }
926 }
927
928 bool
929 vec4_instruction::can_reswizzle(int dst_writemask,
930                                 int swizzle,
931                                 int swizzle_mask)
932 {
933    /* If this instruction sets anything not referenced by swizzle, then we'd
934     * totally break it when we reswizzle.
935     */
936    if (dst.writemask & ~swizzle_mask)
937       return false;
938
939    if (mlen > 0)
940       return false;
941
942    return true;
943 }
944
945 /**
946  * For any channels in the swizzle's source that were populated by this
947  * instruction, rewrite the instruction to put the appropriate result directly
948  * in those channels.
949  *
950  * e.g. for swizzle=yywx, MUL a.xy b c -> MUL a.yy_x b.yy z.yy_x
951  */
952 void
953 vec4_instruction::reswizzle(int dst_writemask, int swizzle)
954 {
955    int new_writemask = 0;
956    int new_swizzle[4] = { 0 };
957
958    /* Dot product instructions write a single result into all channels. */
959    if (opcode != BRW_OPCODE_DP4 && opcode != BRW_OPCODE_DPH &&
960        opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2) {
961       for (int i = 0; i < 3; i++) {
962          if (src[i].file == BAD_FILE || src[i].file == IMM)
963             continue;
964
965          /* Destination write mask doesn't correspond to source swizzle for the
966           * pack_bytes instruction.
967           */
968          if (opcode == VEC4_OPCODE_PACK_BYTES)
969             continue;
970
971          for (int c = 0; c < 4; c++) {
972             new_swizzle[c] = BRW_GET_SWZ(src[i].swizzle, BRW_GET_SWZ(swizzle, c));
973          }
974
975          src[i].swizzle = BRW_SWIZZLE4(new_swizzle[0], new_swizzle[1],
976                                        new_swizzle[2], new_swizzle[3]);
977       }
978    }
979
980    for (int c = 0; c < 4; c++) {
981       int bit = 1 << BRW_GET_SWZ(swizzle, c);
982       /* Skip components of the swizzle not used by the dst. */
983       if (!(dst_writemask & (1 << c)))
984          continue;
985       /* If we were populating this component, then populate the
986        * corresponding channel of the new dst.
987        */
988       if (dst.writemask & bit)
989          new_writemask |= (1 << c);
990    }
991    dst.writemask = new_writemask;
992 }
993
994 /*
995  * Tries to reduce extra MOV instructions by taking temporary GRFs that get
996  * just written and then MOVed into another reg and making the original write
997  * of the GRF write directly to the final destination instead.
998  */
999 bool
1000 vec4_visitor::opt_register_coalesce()
1001 {
1002    bool progress = false;
1003    int next_ip = 0;
1004
1005    calculate_live_intervals();
1006
1007    foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
1008       int ip = next_ip;
1009       next_ip++;
1010
1011       if (inst->opcode != BRW_OPCODE_MOV ||
1012           (inst->dst.file != GRF && inst->dst.file != MRF) ||
1013           inst->predicate ||
1014           inst->src[0].file != GRF ||
1015           inst->dst.type != inst->src[0].type ||
1016           inst->src[0].abs || inst->src[0].negate || inst->src[0].reladdr)
1017          continue;
1018
1019       bool to_mrf = (inst->dst.file == MRF);
1020
1021       /* Can't coalesce this GRF if someone else was going to
1022        * read it later.
1023        */
1024       if (this->virtual_grf_end[inst->src[0].reg * 4 + 0] > ip ||
1025           this->virtual_grf_end[inst->src[0].reg * 4 + 1] > ip ||
1026           this->virtual_grf_end[inst->src[0].reg * 4 + 2] > ip ||
1027           this->virtual_grf_end[inst->src[0].reg * 4 + 3] > ip)
1028          continue;
1029
1030       /* We need to check interference with the final destination between this
1031        * instruction and the earliest instruction involved in writing the GRF
1032        * we're eliminating.  To do that, keep track of which of our source
1033        * channels we've seen initialized.
1034        */
1035       bool chans_needed[4] = {false, false, false, false};
1036       int chans_remaining = 0;
1037       int swizzle_mask = 0;
1038       for (int i = 0; i < 4; i++) {
1039          int chan = BRW_GET_SWZ(inst->src[0].swizzle, i);
1040
1041          if (!(inst->dst.writemask & (1 << i)))
1042             continue;
1043
1044          swizzle_mask |= (1 << chan);
1045
1046          if (!chans_needed[chan]) {
1047             chans_needed[chan] = true;
1048             chans_remaining++;
1049          }
1050       }
1051
1052       /* Now walk up the instruction stream trying to see if we can rewrite
1053        * everything writing to the temporary to write into the destination
1054        * instead.
1055        */
1056       vec4_instruction *_scan_inst = (vec4_instruction *)inst->prev;
1057       foreach_inst_in_block_reverse_starting_from(vec4_instruction, scan_inst,
1058                                                   inst, block) {
1059          _scan_inst = scan_inst;
1060
1061          if (scan_inst->dst.file == GRF &&
1062              scan_inst->dst.reg == inst->src[0].reg &&
1063              scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
1064             /* Found something writing to the reg we want to coalesce away. */
1065             if (to_mrf) {
1066                /* SEND instructions can't have MRF as a destination. */
1067                if (scan_inst->mlen)
1068                   break;
1069
1070                if (brw->gen == 6) {
1071                   /* gen6 math instructions must have the destination be
1072                    * GRF, so no compute-to-MRF for them.
1073                    */
1074                   if (scan_inst->is_math()) {
1075                      break;
1076                   }
1077                }
1078             }
1079
1080             /* If we can't handle the swizzle, bail. */
1081             if (!scan_inst->can_reswizzle(inst->dst.writemask,
1082                                           inst->src[0].swizzle,
1083                                           swizzle_mask)) {
1084                break;
1085             }
1086
1087             /* Mark which channels we found unconditional writes for. */
1088             if (!scan_inst->predicate) {
1089                for (int i = 0; i < 4; i++) {
1090                   if (scan_inst->dst.writemask & (1 << i) &&
1091                       chans_needed[i]) {
1092                      chans_needed[i] = false;
1093                      chans_remaining--;
1094                   }
1095                }
1096             }
1097
1098             if (chans_remaining == 0)
1099                break;
1100          }
1101
1102          /* You can't read from an MRF, so if someone else reads our MRF's
1103           * source GRF that we wanted to rewrite, that stops us.  If it's a
1104           * GRF we're trying to coalesce to, we don't actually handle
1105           * rewriting sources so bail in that case as well.
1106           */
1107          bool interfered = false;
1108          for (int i = 0; i < 3; i++) {
1109             if (scan_inst->src[i].file == GRF &&
1110                 scan_inst->src[i].reg == inst->src[0].reg &&
1111                 scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
1112                interfered = true;
1113             }
1114          }
1115          if (interfered)
1116             break;
1117
1118          /* If somebody else writes our destination here, we can't coalesce
1119           * before that.
1120           */
1121          if (scan_inst->dst.file == inst->dst.file &&
1122              scan_inst->dst.reg == inst->dst.reg) {
1123             break;
1124          }
1125
1126          /* Check for reads of the register we're trying to coalesce into.  We
1127           * can't go rewriting instructions above that to put some other value
1128           * in the register instead.
1129           */
1130          if (to_mrf && scan_inst->mlen > 0) {
1131             if (inst->dst.reg >= scan_inst->base_mrf &&
1132                 inst->dst.reg < scan_inst->base_mrf + scan_inst->mlen) {
1133                break;
1134             }
1135          } else {
1136             for (int i = 0; i < 3; i++) {
1137                if (scan_inst->src[i].file == inst->dst.file &&
1138                    scan_inst->src[i].reg == inst->dst.reg &&
1139                    scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
1140                   interfered = true;
1141                }
1142             }
1143             if (interfered)
1144                break;
1145          }
1146       }
1147
1148       if (chans_remaining == 0) {
1149          /* If we've made it here, we have an MOV we want to coalesce out, and
1150           * a scan_inst pointing to the earliest instruction involved in
1151           * computing the value.  Now go rewrite the instruction stream
1152           * between the two.
1153           */
1154          vec4_instruction *scan_inst = _scan_inst;
1155          while (scan_inst != inst) {
1156             if (scan_inst->dst.file == GRF &&
1157                 scan_inst->dst.reg == inst->src[0].reg &&
1158                 scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
1159                scan_inst->reswizzle(inst->dst.writemask,
1160                                     inst->src[0].swizzle);
1161                scan_inst->dst.file = inst->dst.file;
1162                scan_inst->dst.reg = inst->dst.reg;
1163                scan_inst->dst.reg_offset = inst->dst.reg_offset;
1164                scan_inst->saturate |= inst->saturate;
1165             }
1166             scan_inst = (vec4_instruction *)scan_inst->next;
1167          }
1168          inst->remove(block);
1169          progress = true;
1170       }
1171    }
1172
1173    if (progress)
1174       invalidate_live_intervals();
1175
1176    return progress;
1177 }
1178
1179 /**
1180  * Splits virtual GRFs requesting more than one contiguous physical register.
1181  *
1182  * We initially create large virtual GRFs for temporary structures, arrays,
1183  * and matrices, so that the dereference visitor functions can add reg_offsets
1184  * to work their way down to the actual member being accessed.  But when it
1185  * comes to optimization, we'd like to treat each register as individual
1186  * storage if possible.
1187  *
1188  * So far, the only thing that might prevent splitting is a send message from
1189  * a GRF on IVB.
1190  */
1191 void
1192 vec4_visitor::split_virtual_grfs()
1193 {
1194    int num_vars = this->virtual_grf_count;
1195    int new_virtual_grf[num_vars];
1196    bool split_grf[num_vars];
1197
1198    memset(new_virtual_grf, 0, sizeof(new_virtual_grf));
1199
1200    /* Try to split anything > 0 sized. */
1201    for (int i = 0; i < num_vars; i++) {
1202       split_grf[i] = this->virtual_grf_sizes[i] != 1;
1203    }
1204
1205    /* Check that the instructions are compatible with the registers we're trying
1206     * to split.
1207     */
1208    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1209       /* If there's a SEND message loading from a GRF on gen7+, it needs to be
1210        * contiguous.
1211        */
1212       if (inst->is_send_from_grf()) {
1213          for (int i = 0; i < 3; i++) {
1214             if (inst->src[i].file == GRF) {
1215                split_grf[inst->src[i].reg] = false;
1216             }
1217          }
1218       }
1219    }
1220
1221    /* Allocate new space for split regs.  Note that the virtual
1222     * numbers will be contiguous.
1223     */
1224    for (int i = 0; i < num_vars; i++) {
1225       if (!split_grf[i])
1226          continue;
1227
1228       new_virtual_grf[i] = virtual_grf_alloc(1);
1229       for (int j = 2; j < this->virtual_grf_sizes[i]; j++) {
1230          int reg = virtual_grf_alloc(1);
1231          assert(reg == new_virtual_grf[i] + j - 1);
1232          (void) reg;
1233       }
1234       this->virtual_grf_sizes[i] = 1;
1235    }
1236
1237    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1238       if (inst->dst.file == GRF && split_grf[inst->dst.reg] &&
1239           inst->dst.reg_offset != 0) {
1240          inst->dst.reg = (new_virtual_grf[inst->dst.reg] +
1241                           inst->dst.reg_offset - 1);
1242          inst->dst.reg_offset = 0;
1243       }
1244       for (int i = 0; i < 3; i++) {
1245          if (inst->src[i].file == GRF && split_grf[inst->src[i].reg] &&
1246              inst->src[i].reg_offset != 0) {
1247             inst->src[i].reg = (new_virtual_grf[inst->src[i].reg] +
1248                                 inst->src[i].reg_offset - 1);
1249             inst->src[i].reg_offset = 0;
1250          }
1251       }
1252    }
1253    invalidate_live_intervals();
1254 }
1255
1256 void
1257 vec4_visitor::dump_instruction(backend_instruction *be_inst)
1258 {
1259    dump_instruction(be_inst, stderr);
1260 }
1261
1262 void
1263 vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
1264 {
1265    vec4_instruction *inst = (vec4_instruction *)be_inst;
1266
1267    if (inst->predicate) {
1268       fprintf(file, "(%cf0) ",
1269              inst->predicate_inverse ? '-' : '+');
1270    }
1271
1272    fprintf(file, "%s", brw_instruction_name(inst->opcode));
1273    if (inst->conditional_mod) {
1274       fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
1275    }
1276    fprintf(file, " ");
1277
1278    switch (inst->dst.file) {
1279    case GRF:
1280       fprintf(file, "vgrf%d.%d", inst->dst.reg, inst->dst.reg_offset);
1281       break;
1282    case MRF:
1283       fprintf(file, "m%d", inst->dst.reg);
1284       break;
1285    case HW_REG:
1286       if (inst->dst.fixed_hw_reg.file == BRW_ARCHITECTURE_REGISTER_FILE) {
1287          switch (inst->dst.fixed_hw_reg.nr) {
1288          case BRW_ARF_NULL:
1289             fprintf(file, "null");
1290             break;
1291          case BRW_ARF_ADDRESS:
1292             fprintf(file, "a0.%d", inst->dst.fixed_hw_reg.subnr);
1293             break;
1294          case BRW_ARF_ACCUMULATOR:
1295             fprintf(file, "acc%d", inst->dst.fixed_hw_reg.subnr);
1296             break;
1297          case BRW_ARF_FLAG:
1298             fprintf(file, "f%d.%d", inst->dst.fixed_hw_reg.nr & 0xf,
1299                              inst->dst.fixed_hw_reg.subnr);
1300             break;
1301          default:
1302             fprintf(file, "arf%d.%d", inst->dst.fixed_hw_reg.nr & 0xf,
1303                                inst->dst.fixed_hw_reg.subnr);
1304             break;
1305          }
1306       } else {
1307          fprintf(file, "hw_reg%d", inst->dst.fixed_hw_reg.nr);
1308       }
1309       if (inst->dst.fixed_hw_reg.subnr)
1310          fprintf(file, "+%d", inst->dst.fixed_hw_reg.subnr);
1311       break;
1312    case BAD_FILE:
1313       fprintf(file, "(null)");
1314       break;
1315    default:
1316       fprintf(file, "???");
1317       break;
1318    }
1319    if (inst->dst.writemask != WRITEMASK_XYZW) {
1320       fprintf(file, ".");
1321       if (inst->dst.writemask & 1)
1322          fprintf(file, "x");
1323       if (inst->dst.writemask & 2)
1324          fprintf(file, "y");
1325       if (inst->dst.writemask & 4)
1326          fprintf(file, "z");
1327       if (inst->dst.writemask & 8)
1328          fprintf(file, "w");
1329    }
1330    fprintf(file, ":%s", brw_reg_type_letters(inst->dst.type));
1331
1332    if (inst->src[0].file != BAD_FILE)
1333       fprintf(file, ", ");
1334
1335    for (int i = 0; i < 3 && inst->src[i].file != BAD_FILE; i++) {
1336       if (inst->src[i].negate)
1337          fprintf(file, "-");
1338       if (inst->src[i].abs)
1339          fprintf(file, "|");
1340       switch (inst->src[i].file) {
1341       case GRF:
1342          fprintf(file, "vgrf%d", inst->src[i].reg);
1343          break;
1344       case ATTR:
1345          fprintf(file, "attr%d", inst->src[i].reg);
1346          break;
1347       case UNIFORM:
1348          fprintf(file, "u%d", inst->src[i].reg);
1349          break;
1350       case IMM:
1351          switch (inst->src[i].type) {
1352          case BRW_REGISTER_TYPE_F:
1353             fprintf(file, "%fF", inst->src[i].fixed_hw_reg.dw1.f);
1354             break;
1355          case BRW_REGISTER_TYPE_D:
1356             fprintf(file, "%dD", inst->src[i].fixed_hw_reg.dw1.d);
1357             break;
1358          case BRW_REGISTER_TYPE_UD:
1359             fprintf(file, "%uU", inst->src[i].fixed_hw_reg.dw1.ud);
1360             break;
1361          case BRW_REGISTER_TYPE_VF:
1362             fprintf(stderr, "[%-gF, %-gF, %-gF, %-gF]",
1363                     brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >>  0) & 0xff),
1364                     brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >>  8) & 0xff),
1365                     brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 16) & 0xff),
1366                     brw_vf_to_float((inst->src[i].fixed_hw_reg.dw1.ud >> 24) & 0xff));
1367             break;
1368          default:
1369             fprintf(file, "???");
1370             break;
1371          }
1372          break;
1373       case HW_REG:
1374          if (inst->src[i].fixed_hw_reg.negate)
1375             fprintf(file, "-");
1376          if (inst->src[i].fixed_hw_reg.abs)
1377             fprintf(file, "|");
1378          if (inst->src[i].fixed_hw_reg.file == BRW_ARCHITECTURE_REGISTER_FILE) {
1379             switch (inst->src[i].fixed_hw_reg.nr) {
1380             case BRW_ARF_NULL:
1381                fprintf(file, "null");
1382                break;
1383             case BRW_ARF_ADDRESS:
1384                fprintf(file, "a0.%d", inst->src[i].fixed_hw_reg.subnr);
1385                break;
1386             case BRW_ARF_ACCUMULATOR:
1387                fprintf(file, "acc%d", inst->src[i].fixed_hw_reg.subnr);
1388                break;
1389             case BRW_ARF_FLAG:
1390                fprintf(file, "f%d.%d", inst->src[i].fixed_hw_reg.nr & 0xf,
1391                                 inst->src[i].fixed_hw_reg.subnr);
1392                break;
1393             default:
1394                fprintf(file, "arf%d.%d", inst->src[i].fixed_hw_reg.nr & 0xf,
1395                                   inst->src[i].fixed_hw_reg.subnr);
1396                break;
1397             }
1398          } else {
1399             fprintf(file, "hw_reg%d", inst->src[i].fixed_hw_reg.nr);
1400          }
1401          if (inst->src[i].fixed_hw_reg.subnr)
1402             fprintf(file, "+%d", inst->src[i].fixed_hw_reg.subnr);
1403          if (inst->src[i].fixed_hw_reg.abs)
1404             fprintf(file, "|");
1405          break;
1406       case BAD_FILE:
1407          fprintf(file, "(null)");
1408          break;
1409       default:
1410          fprintf(file, "???");
1411          break;
1412       }
1413
1414       /* Don't print .0; and only VGRFs have reg_offsets and sizes */
1415       if (inst->src[i].reg_offset != 0 &&
1416           inst->src[i].file == GRF &&
1417           virtual_grf_sizes[inst->src[i].reg] != 1)
1418          fprintf(file, ".%d", inst->src[i].reg_offset);
1419
1420       if (inst->src[i].file != IMM) {
1421          static const char *chans[4] = {"x", "y", "z", "w"};
1422          fprintf(file, ".");
1423          for (int c = 0; c < 4; c++) {
1424             fprintf(file, "%s", chans[BRW_GET_SWZ(inst->src[i].swizzle, c)]);
1425          }
1426       }
1427
1428       if (inst->src[i].abs)
1429          fprintf(file, "|");
1430
1431       if (inst->src[i].file != IMM) {
1432          fprintf(file, ":%s", brw_reg_type_letters(inst->src[i].type));
1433       }
1434
1435       if (i < 2 && inst->src[i + 1].file != BAD_FILE)
1436          fprintf(file, ", ");
1437    }
1438
1439    fprintf(file, "\n");
1440 }
1441
1442
1443 static inline struct brw_reg
1444 attribute_to_hw_reg(int attr, bool interleaved)
1445 {
1446    if (interleaved)
1447       return stride(brw_vec4_grf(attr / 2, (attr % 2) * 4), 0, 4, 1);
1448    else
1449       return brw_vec8_grf(attr, 0);
1450 }
1451
1452
1453 /**
1454  * Replace each register of type ATTR in this->instructions with a reference
1455  * to a fixed HW register.
1456  *
1457  * If interleaved is true, then each attribute takes up half a register, with
1458  * register N containing attribute 2*N in its first half and attribute 2*N+1
1459  * in its second half (this corresponds to the payload setup used by geometry
1460  * shaders in "single" or "dual instanced" dispatch mode).  If interleaved is
1461  * false, then each attribute takes up a whole register, with register N
1462  * containing attribute N (this corresponds to the payload setup used by
1463  * vertex shaders, and by geometry shaders in "dual object" dispatch mode).
1464  */
1465 void
1466 vec4_visitor::lower_attributes_to_hw_regs(const int *attribute_map,
1467                                           bool interleaved)
1468 {
1469    foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1470       /* We have to support ATTR as a destination for GL_FIXED fixup. */
1471       if (inst->dst.file == ATTR) {
1472          int grf = attribute_map[inst->dst.reg + inst->dst.reg_offset];
1473
1474          /* All attributes used in the shader need to have been assigned a
1475           * hardware register by the caller
1476           */
1477          assert(grf != 0);
1478
1479          struct brw_reg reg = attribute_to_hw_reg(grf, interleaved);
1480          reg.type = inst->dst.type;
1481          reg.dw1.bits.writemask = inst->dst.writemask;
1482
1483          inst->dst.file = HW_REG;
1484          inst->dst.fixed_hw_reg = reg;
1485       }
1486
1487       for (int i = 0; i < 3; i++) {
1488          if (inst->src[i].file != ATTR)
1489             continue;
1490
1491          int grf = attribute_map[inst->src[i].reg + inst->src[i].reg_offset];
1492
1493          /* All attributes used in the shader need to have been assigned a
1494           * hardware register by the caller
1495           */
1496          assert(grf != 0);
1497
1498          struct brw_reg reg = attribute_to_hw_reg(grf, interleaved);
1499          reg.dw1.bits.swizzle = inst->src[i].swizzle;
1500          reg.type = inst->src[i].type;
1501          if (inst->src[i].abs)
1502             reg = brw_abs(reg);
1503          if (inst->src[i].negate)
1504             reg = negate(reg);
1505
1506          inst->src[i].file = HW_REG;
1507          inst->src[i].fixed_hw_reg = reg;
1508       }
1509    }
1510 }
1511
1512 int
1513 vec4_vs_visitor::setup_attributes(int payload_reg)
1514 {
1515    int nr_attributes;
1516    int attribute_map[VERT_ATTRIB_MAX + 1];
1517    memset(attribute_map, 0, sizeof(attribute_map));
1518
1519    nr_attributes = 0;
1520    for (int i = 0; i < VERT_ATTRIB_MAX; i++) {
1521       if (vs_prog_data->inputs_read & BITFIELD64_BIT(i)) {
1522          attribute_map[i] = payload_reg + nr_attributes;
1523          nr_attributes++;
1524       }
1525    }
1526
1527    /* VertexID is stored by the VF as the last vertex element, but we
1528     * don't represent it with a flag in inputs_read, so we call it
1529     * VERT_ATTRIB_MAX.
1530     */
1531    if (vs_prog_data->uses_vertexid || vs_prog_data->uses_instanceid) {
1532       attribute_map[VERT_ATTRIB_MAX] = payload_reg + nr_attributes;
1533       nr_attributes++;
1534    }
1535
1536    lower_attributes_to_hw_regs(attribute_map, false /* interleaved */);
1537
1538    /* The BSpec says we always have to read at least one thing from
1539     * the VF, and it appears that the hardware wedges otherwise.
1540     */
1541    if (nr_attributes == 0)
1542       nr_attributes = 1;
1543
1544    prog_data->urb_read_length = (nr_attributes + 1) / 2;
1545
1546    unsigned vue_entries =
1547       MAX2(nr_attributes, prog_data->vue_map.num_slots);
1548
1549    if (brw->gen == 6)
1550       prog_data->urb_entry_size = ALIGN(vue_entries, 8) / 8;
1551    else
1552       prog_data->urb_entry_size = ALIGN(vue_entries, 4) / 4;
1553
1554    return payload_reg + nr_attributes;
1555 }
1556
1557 int
1558 vec4_visitor::setup_uniforms(int reg)
1559 {
1560    prog_data->base.dispatch_grf_start_reg = reg;
1561
1562    /* The pre-gen6 VS requires that some push constants get loaded no
1563     * matter what, or the GPU would hang.
1564     */
1565    if (brw->gen < 6 && this->uniforms == 0) {
1566       assert(this->uniforms < this->uniform_array_size);
1567       this->uniform_vector_size[this->uniforms] = 1;
1568
1569       stage_prog_data->param =
1570          reralloc(NULL, stage_prog_data->param, const gl_constant_value *, 4);
1571       for (unsigned int i = 0; i < 4; i++) {
1572          unsigned int slot = this->uniforms * 4 + i;
1573          static gl_constant_value zero = { 0.0 };
1574          stage_prog_data->param[slot] = &zero;
1575       }
1576
1577       this->uniforms++;
1578       reg++;
1579    } else {
1580       reg += ALIGN(uniforms, 2) / 2;
1581    }
1582
1583    stage_prog_data->nr_params = this->uniforms * 4;
1584
1585    prog_data->base.curb_read_length =
1586       reg - prog_data->base.dispatch_grf_start_reg;
1587
1588    return reg;
1589 }
1590
1591 void
1592 vec4_vs_visitor::setup_payload(void)
1593 {
1594    int reg = 0;
1595
1596    /* The payload always contains important data in g0, which contains
1597     * the URB handles that are passed on to the URB write at the end
1598     * of the thread.  So, we always start push constants at g1.
1599     */
1600    reg++;
1601
1602    reg = setup_uniforms(reg);
1603
1604    reg = setup_attributes(reg);
1605
1606    this->first_non_payload_grf = reg;
1607 }
1608
1609 void
1610 vec4_visitor::assign_binding_table_offsets()
1611 {
1612    assign_common_binding_table_offsets(0);
1613 }
1614
1615 src_reg
1616 vec4_visitor::get_timestamp()
1617 {
1618    assert(brw->gen >= 7);
1619
1620    src_reg ts = src_reg(brw_reg(BRW_ARCHITECTURE_REGISTER_FILE,
1621                                 BRW_ARF_TIMESTAMP,
1622                                 0,
1623                                 0,
1624                                 0,
1625                                 BRW_REGISTER_TYPE_UD,
1626                                 BRW_VERTICAL_STRIDE_0,
1627                                 BRW_WIDTH_4,
1628                                 BRW_HORIZONTAL_STRIDE_4,
1629                                 BRW_SWIZZLE_XYZW,
1630                                 WRITEMASK_XYZW));
1631
1632    dst_reg dst = dst_reg(this, glsl_type::uvec4_type);
1633
1634    vec4_instruction *mov = emit(MOV(dst, ts));
1635    /* We want to read the 3 fields we care about (mostly field 0, but also 2)
1636     * even if it's not enabled in the dispatch.
1637     */
1638    mov->force_writemask_all = true;
1639
1640    return src_reg(dst);
1641 }
1642
1643 void
1644 vec4_visitor::emit_shader_time_begin()
1645 {
1646    current_annotation = "shader time start";
1647    shader_start_time = get_timestamp();
1648 }
1649
1650 void
1651 vec4_visitor::emit_shader_time_end()
1652 {
1653    current_annotation = "shader time end";
1654    src_reg shader_end_time = get_timestamp();
1655
1656
1657    /* Check that there weren't any timestamp reset events (assuming these
1658     * were the only two timestamp reads that happened).
1659     */
1660    src_reg reset_end = shader_end_time;
1661    reset_end.swizzle = BRW_SWIZZLE_ZZZZ;
1662    vec4_instruction *test = emit(AND(dst_null_d(), reset_end, src_reg(1u)));
1663    test->conditional_mod = BRW_CONDITIONAL_Z;
1664
1665    emit(IF(BRW_PREDICATE_NORMAL));
1666
1667    /* Take the current timestamp and get the delta. */
1668    shader_start_time.negate = true;
1669    dst_reg diff = dst_reg(this, glsl_type::uint_type);
1670    emit(ADD(diff, shader_start_time, shader_end_time));
1671
1672    /* If there were no instructions between the two timestamp gets, the diff
1673     * is 2 cycles.  Remove that overhead, so I can forget about that when
1674     * trying to determine the time taken for single instructions.
1675     */
1676    emit(ADD(diff, src_reg(diff), src_reg(-2u)));
1677
1678    emit_shader_time_write(st_base, src_reg(diff));
1679    emit_shader_time_write(st_written, src_reg(1u));
1680    emit(BRW_OPCODE_ELSE);
1681    emit_shader_time_write(st_reset, src_reg(1u));
1682    emit(BRW_OPCODE_ENDIF);
1683 }
1684
1685 void
1686 vec4_visitor::emit_shader_time_write(enum shader_time_shader_type type,
1687                                      src_reg value)
1688 {
1689    int shader_time_index =
1690       brw_get_shader_time_index(brw, shader_prog, prog, type);
1691
1692    dst_reg dst =
1693       dst_reg(this, glsl_type::get_array_instance(glsl_type::vec4_type, 2));
1694
1695    dst_reg offset = dst;
1696    dst_reg time = dst;
1697    time.reg_offset++;
1698
1699    offset.type = BRW_REGISTER_TYPE_UD;
1700    emit(MOV(offset, src_reg(shader_time_index * SHADER_TIME_STRIDE)));
1701
1702    time.type = BRW_REGISTER_TYPE_UD;
1703    emit(MOV(time, src_reg(value)));
1704
1705    emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
1706 }
1707
1708 bool
1709 vec4_visitor::run()
1710 {
1711    sanity_param_count = prog->Parameters->NumParameters;
1712
1713    if (INTEL_DEBUG & DEBUG_SHADER_TIME)
1714       emit_shader_time_begin();
1715
1716    assign_binding_table_offsets();
1717
1718    emit_prolog();
1719
1720    /* Generate VS IR for main().  (the visitor only descends into
1721     * functions called "main").
1722     */
1723    if (shader) {
1724       visit_instructions(shader->base.ir);
1725    } else {
1726       emit_program_code();
1727    }
1728    base_ir = NULL;
1729
1730    if (key->userclip_active && !prog->UsesClipDistanceOut)
1731       setup_uniform_clipplane_values();
1732
1733    emit_thread_end();
1734
1735    calculate_cfg();
1736
1737    /* Before any optimization, push array accesses out to scratch
1738     * space where we need them to be.  This pass may allocate new
1739     * virtual GRFs, so we want to do it early.  It also makes sure
1740     * that we have reladdr computations available for CSE, since we'll
1741     * often do repeated subexpressions for those.
1742     */
1743    if (shader) {
1744       move_grf_array_access_to_scratch();
1745       move_uniform_array_access_to_pull_constants();
1746    } else {
1747       /* The ARB_vertex_program frontend emits pull constant loads directly
1748        * rather than using reladdr, so we don't need to walk through all the
1749        * instructions looking for things to move.  There isn't anything.
1750        *
1751        * We do still need to split things to vec4 size.
1752        */
1753       split_uniform_registers();
1754    }
1755    pack_uniform_registers();
1756    move_push_constants_to_pull_constants();
1757    split_virtual_grfs();
1758
1759    const char *stage_name = stage == MESA_SHADER_GEOMETRY ? "gs" : "vs";
1760
1761 #define OPT(pass, args...) do {                                        \
1762       pass_num++;                                                      \
1763       bool this_progress = pass(args);                                 \
1764                                                                        \
1765       if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) {  \
1766          char filename[64];                                            \
1767          snprintf(filename, 64, "%s-%04d-%02d-%02d-" #pass,            \
1768                   stage_name, shader_prog ? shader_prog->Name : 0, iteration, pass_num); \
1769                                                                        \
1770          backend_visitor::dump_instructions(filename);                 \
1771       }                                                                \
1772                                                                        \
1773       progress = progress || this_progress;                            \
1774    } while (false)
1775
1776
1777    if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
1778       char filename[64];
1779       snprintf(filename, 64, "%s-%04d-00-start",
1780                stage_name, shader_prog ? shader_prog->Name : 0);
1781
1782       backend_visitor::dump_instructions(filename);
1783    }
1784
1785    bool progress;
1786    int iteration = 0;
1787    do {
1788       progress = false;
1789       iteration++;
1790       int pass_num = 0;
1791
1792       OPT(opt_reduce_swizzle);
1793       OPT(dead_code_eliminate);
1794       OPT(dead_control_flow_eliminate, this);
1795       OPT(opt_copy_propagation);
1796       OPT(opt_cse);
1797       OPT(opt_algebraic);
1798       OPT(opt_register_coalesce);
1799    } while (progress);
1800
1801    if (opt_vector_float()) {
1802       opt_cse();
1803       opt_copy_propagation(false);
1804       opt_copy_propagation(true);
1805       dead_code_eliminate();
1806    }
1807
1808    if (failed)
1809       return false;
1810
1811    setup_payload();
1812
1813    if (false) {
1814       /* Debug of register spilling: Go spill everything. */
1815       const int grf_count = virtual_grf_count;
1816       float spill_costs[virtual_grf_count];
1817       bool no_spill[virtual_grf_count];
1818       evaluate_spill_costs(spill_costs, no_spill);
1819       for (int i = 0; i < grf_count; i++) {
1820          if (no_spill[i])
1821             continue;
1822          spill_reg(i);
1823       }
1824    }
1825
1826    while (!reg_allocate()) {
1827       if (failed)
1828          return false;
1829    }
1830
1831    opt_schedule_instructions();
1832
1833    opt_set_dependency_control();
1834
1835    /* If any state parameters were appended, then ParameterValues could have
1836     * been realloced, in which case the driver uniform storage set up by
1837     * _mesa_associate_uniform_storage() would point to freed memory.  Make
1838     * sure that didn't happen.
1839     */
1840    assert(sanity_param_count == prog->Parameters->NumParameters);
1841
1842    return !failed;
1843 }
1844
1845 } /* namespace brw */
1846
1847 extern "C" {
1848
1849 /**
1850  * Compile a vertex shader.
1851  *
1852  * Returns the final assembly and the program's size.
1853  */
1854 const unsigned *
1855 brw_vs_emit(struct brw_context *brw,
1856             struct gl_shader_program *prog,
1857             struct brw_vs_compile *c,
1858             struct brw_vs_prog_data *prog_data,
1859             void *mem_ctx,
1860             unsigned *final_assembly_size)
1861 {
1862    bool start_busy = false;
1863    double start_time = 0;
1864    const unsigned *assembly = NULL;
1865
1866    if (unlikely(brw->perf_debug)) {
1867       start_busy = (brw->batch.last_bo &&
1868                     drm_intel_bo_busy(brw->batch.last_bo));
1869       start_time = get_time();
1870    }
1871
1872    struct brw_shader *shader = NULL;
1873    if (prog)
1874       shader = (brw_shader *) prog->_LinkedShaders[MESA_SHADER_VERTEX];
1875
1876    if (unlikely(INTEL_DEBUG & DEBUG_VS))
1877       brw_dump_ir("vertex", prog, &shader->base, &c->vp->program.Base);
1878
1879    if (prog && brw->gen >= 8 && brw->scalar_vs) {
1880       fs_visitor v(brw, mem_ctx, &c->key, prog_data, prog, &c->vp->program, 8);
1881       if (!v.run_vs()) {
1882          if (prog) {
1883             prog->LinkStatus = false;
1884             ralloc_strcat(&prog->InfoLog, v.fail_msg);
1885          }
1886
1887          _mesa_problem(NULL, "Failed to compile vertex shader: %s\n",
1888                        v.fail_msg);
1889
1890          return NULL;
1891       }
1892
1893       fs_generator g(brw, mem_ctx, (void *) &c->key, &prog_data->base.base,
1894                      &c->vp->program.Base, v.runtime_check_aads_emit);
1895       if (INTEL_DEBUG & DEBUG_VS) {
1896          char *name = ralloc_asprintf(mem_ctx, "%s vertex shader %d",
1897                                       prog->Label ? prog->Label : "unnamed",
1898                                       prog->Name);
1899          g.enable_debug(name);
1900       }
1901       g.generate_code(v.cfg, 8);
1902       assembly = g.get_assembly(final_assembly_size);
1903
1904       if (assembly)
1905          prog_data->base.simd8 = true;
1906       c->base.last_scratch = v.last_scratch;
1907    }
1908
1909    if (!assembly) {
1910       vec4_vs_visitor v(brw, c, prog_data, prog, mem_ctx);
1911       if (!v.run()) {
1912          if (prog) {
1913             prog->LinkStatus = false;
1914             ralloc_strcat(&prog->InfoLog, v.fail_msg);
1915          }
1916
1917          _mesa_problem(NULL, "Failed to compile vertex shader: %s\n",
1918                        v.fail_msg);
1919
1920          return NULL;
1921       }
1922
1923       vec4_generator g(brw, prog, &c->vp->program.Base, &prog_data->base,
1924                        mem_ctx, INTEL_DEBUG & DEBUG_VS);
1925       assembly = g.generate_assembly(v.cfg, final_assembly_size);
1926    }
1927
1928    if (unlikely(brw->perf_debug) && shader) {
1929       if (shader->compiled_once) {
1930          brw_vs_debug_recompile(brw, prog, &c->key);
1931       }
1932       if (start_busy && !drm_intel_bo_busy(brw->batch.last_bo)) {
1933          perf_debug("VS compile took %.03f ms and stalled the GPU\n",
1934                     (get_time() - start_time) * 1000);
1935       }
1936       shader->compiled_once = true;
1937    }
1938
1939    return assembly;
1940 }
1941
1942
1943 void
1944 brw_vue_setup_prog_key_for_precompile(struct gl_context *ctx,
1945                                       struct brw_vue_prog_key *key,
1946                                       GLuint id, struct gl_program *prog)
1947 {
1948    key->program_string_id = id;
1949
1950    unsigned sampler_count = _mesa_fls(prog->SamplersUsed);
1951    for (unsigned i = 0; i < sampler_count; i++) {
1952       if (prog->ShadowSamplers & (1 << i)) {
1953          /* Assume DEPTH_TEXTURE_MODE is the default: X, X, X, 1 */
1954          key->tex.swizzles[i] =
1955             MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_ONE);
1956       } else {
1957          /* Color sampler: assume no swizzling. */
1958          key->tex.swizzles[i] = SWIZZLE_XYZW;
1959       }
1960    }
1961 }
1962
1963 } /* extern "C" */