OSDN Git Service

i965/msaa: Add backend support for centroid interpolation.
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / brw_fs.cpp
1 /*
2  * Copyright © 2010 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 /** @file brw_fs.cpp
25  *
26  * This file drives the GLSL IR -> LIR translation, contains the
27  * optimizations on the LIR, and drives the generation of native code
28  * from the LIR.
29  */
30
31 extern "C" {
32
33 #include <sys/types.h>
34
35 #include "main/macros.h"
36 #include "main/shaderobj.h"
37 #include "main/uniforms.h"
38 #include "main/fbobject.h"
39 #include "program/prog_parameter.h"
40 #include "program/prog_print.h"
41 #include "program/register_allocate.h"
42 #include "program/sampler.h"
43 #include "program/hash_table.h"
44 #include "brw_context.h"
45 #include "brw_eu.h"
46 #include "brw_wm.h"
47 }
48 #include "brw_shader.h"
49 #include "brw_fs.h"
50 #include "glsl/glsl_types.h"
51 #include "glsl/ir_print_visitor.h"
52
53 int
54 fs_visitor::type_size(const struct glsl_type *type)
55 {
56    unsigned int size, i;
57
58    switch (type->base_type) {
59    case GLSL_TYPE_UINT:
60    case GLSL_TYPE_INT:
61    case GLSL_TYPE_FLOAT:
62    case GLSL_TYPE_BOOL:
63       return type->components();
64    case GLSL_TYPE_ARRAY:
65       return type_size(type->fields.array) * type->length;
66    case GLSL_TYPE_STRUCT:
67       size = 0;
68       for (i = 0; i < type->length; i++) {
69          size += type_size(type->fields.structure[i].type);
70       }
71       return size;
72    case GLSL_TYPE_SAMPLER:
73       /* Samplers take up no register space, since they're baked in at
74        * link time.
75        */
76       return 0;
77    default:
78       assert(!"not reached");
79       return 0;
80    }
81 }
82
83 void
84 fs_visitor::fail(const char *format, ...)
85 {
86    va_list va;
87    char *msg;
88
89    if (failed)
90       return;
91
92    failed = true;
93
94    va_start(va, format);
95    msg = ralloc_vasprintf(mem_ctx, format, va);
96    va_end(va);
97    msg = ralloc_asprintf(mem_ctx, "FS compile failed: %s\n", msg);
98
99    this->fail_msg = msg;
100
101    if (INTEL_DEBUG & DEBUG_WM) {
102       fprintf(stderr, "%s",  msg);
103    }
104 }
105
106 void
107 fs_visitor::push_force_uncompressed()
108 {
109    force_uncompressed_stack++;
110 }
111
112 void
113 fs_visitor::pop_force_uncompressed()
114 {
115    force_uncompressed_stack--;
116    assert(force_uncompressed_stack >= 0);
117 }
118
119 void
120 fs_visitor::push_force_sechalf()
121 {
122    force_sechalf_stack++;
123 }
124
125 void
126 fs_visitor::pop_force_sechalf()
127 {
128    force_sechalf_stack--;
129    assert(force_sechalf_stack >= 0);
130 }
131
132 /**
133  * Returns how many MRFs an FS opcode will write over.
134  *
135  * Note that this is not the 0 or 1 implied writes in an actual gen
136  * instruction -- the FS opcodes often generate MOVs in addition.
137  */
138 int
139 fs_visitor::implied_mrf_writes(fs_inst *inst)
140 {
141    if (inst->mlen == 0)
142       return 0;
143
144    switch (inst->opcode) {
145    case SHADER_OPCODE_RCP:
146    case SHADER_OPCODE_RSQ:
147    case SHADER_OPCODE_SQRT:
148    case SHADER_OPCODE_EXP2:
149    case SHADER_OPCODE_LOG2:
150    case SHADER_OPCODE_SIN:
151    case SHADER_OPCODE_COS:
152       return 1 * c->dispatch_width / 8;
153    case SHADER_OPCODE_POW:
154    case SHADER_OPCODE_INT_QUOTIENT:
155    case SHADER_OPCODE_INT_REMAINDER:
156       return 2 * c->dispatch_width / 8;
157    case SHADER_OPCODE_TEX:
158    case FS_OPCODE_TXB:
159    case SHADER_OPCODE_TXD:
160    case SHADER_OPCODE_TXF:
161    case SHADER_OPCODE_TXL:
162    case SHADER_OPCODE_TXS:
163       return 1;
164    case FS_OPCODE_FB_WRITE:
165       return 2;
166    case FS_OPCODE_PULL_CONSTANT_LOAD:
167    case FS_OPCODE_UNSPILL:
168       return 1;
169    case FS_OPCODE_SPILL:
170       return 2;
171    default:
172       assert(!"not reached");
173       return inst->mlen;
174    }
175 }
176
177 int
178 fs_visitor::virtual_grf_alloc(int size)
179 {
180    if (virtual_grf_array_size <= virtual_grf_next) {
181       if (virtual_grf_array_size == 0)
182          virtual_grf_array_size = 16;
183       else
184          virtual_grf_array_size *= 2;
185       virtual_grf_sizes = reralloc(mem_ctx, virtual_grf_sizes, int,
186                                    virtual_grf_array_size);
187    }
188    virtual_grf_sizes[virtual_grf_next] = size;
189    return virtual_grf_next++;
190 }
191
192 /** Fixed HW reg constructor. */
193 fs_reg::fs_reg(enum register_file file, int reg)
194 {
195    init();
196    this->file = file;
197    this->reg = reg;
198    this->type = BRW_REGISTER_TYPE_F;
199 }
200
201 /** Fixed HW reg constructor. */
202 fs_reg::fs_reg(enum register_file file, int reg, uint32_t type)
203 {
204    init();
205    this->file = file;
206    this->reg = reg;
207    this->type = type;
208 }
209
210 /** Automatic reg constructor. */
211 fs_reg::fs_reg(class fs_visitor *v, const struct glsl_type *type)
212 {
213    init();
214
215    this->file = GRF;
216    this->reg = v->virtual_grf_alloc(v->type_size(type));
217    this->reg_offset = 0;
218    this->type = brw_type_for_base_type(type);
219 }
220
221 fs_reg *
222 fs_visitor::variable_storage(ir_variable *var)
223 {
224    return (fs_reg *)hash_table_find(this->variable_ht, var);
225 }
226
227 void
228 import_uniforms_callback(const void *key,
229                          void *data,
230                          void *closure)
231 {
232    struct hash_table *dst_ht = (struct hash_table *)closure;
233    const fs_reg *reg = (const fs_reg *)data;
234
235    if (reg->file != UNIFORM)
236       return;
237
238    hash_table_insert(dst_ht, data, key);
239 }
240
241 /* For 16-wide, we need to follow from the uniform setup of 8-wide dispatch.
242  * This brings in those uniform definitions
243  */
244 void
245 fs_visitor::import_uniforms(fs_visitor *v)
246 {
247    hash_table_call_foreach(v->variable_ht,
248                            import_uniforms_callback,
249                            variable_ht);
250    this->params_remap = v->params_remap;
251 }
252
253 /* Our support for uniforms is piggy-backed on the struct
254  * gl_fragment_program, because that's where the values actually
255  * get stored, rather than in some global gl_shader_program uniform
256  * store.
257  */
258 int
259 fs_visitor::setup_uniform_values(int loc, const glsl_type *type)
260 {
261    unsigned int offset = 0;
262
263    if (type->is_matrix()) {
264       const glsl_type *column = glsl_type::get_instance(GLSL_TYPE_FLOAT,
265                                                         type->vector_elements,
266                                                         1);
267
268       for (unsigned int i = 0; i < type->matrix_columns; i++) {
269          offset += setup_uniform_values(loc + offset, column);
270       }
271
272       return offset;
273    }
274
275    switch (type->base_type) {
276    case GLSL_TYPE_FLOAT:
277    case GLSL_TYPE_UINT:
278    case GLSL_TYPE_INT:
279    case GLSL_TYPE_BOOL:
280       for (unsigned int i = 0; i < type->vector_elements; i++) {
281          unsigned int param = c->prog_data.nr_params++;
282
283          assert(param < ARRAY_SIZE(c->prog_data.param));
284
285          if (ctx->Const.NativeIntegers) {
286             c->prog_data.param_convert[param] = PARAM_NO_CONVERT;
287          } else {
288             switch (type->base_type) {
289             case GLSL_TYPE_FLOAT:
290                c->prog_data.param_convert[param] = PARAM_NO_CONVERT;
291                break;
292             case GLSL_TYPE_UINT:
293                c->prog_data.param_convert[param] = PARAM_CONVERT_F2U;
294                break;
295             case GLSL_TYPE_INT:
296                c->prog_data.param_convert[param] = PARAM_CONVERT_F2I;
297                break;
298             case GLSL_TYPE_BOOL:
299                c->prog_data.param_convert[param] = PARAM_CONVERT_F2B;
300                break;
301             default:
302                assert(!"not reached");
303                c->prog_data.param_convert[param] = PARAM_NO_CONVERT;
304                break;
305             }
306          }
307          this->param_index[param] = loc;
308          this->param_offset[param] = i;
309       }
310       return 1;
311
312    case GLSL_TYPE_STRUCT:
313       for (unsigned int i = 0; i < type->length; i++) {
314          offset += setup_uniform_values(loc + offset,
315                                         type->fields.structure[i].type);
316       }
317       return offset;
318
319    case GLSL_TYPE_ARRAY:
320       for (unsigned int i = 0; i < type->length; i++) {
321          offset += setup_uniform_values(loc + offset, type->fields.array);
322       }
323       return offset;
324
325    case GLSL_TYPE_SAMPLER:
326       /* The sampler takes up a slot, but we don't use any values from it. */
327       return 1;
328
329    default:
330       assert(!"not reached");
331       return 0;
332    }
333 }
334
335
336 /* Our support for builtin uniforms is even scarier than non-builtin.
337  * It sits on top of the PROG_STATE_VAR parameters that are
338  * automatically updated from GL context state.
339  */
340 void
341 fs_visitor::setup_builtin_uniform_values(ir_variable *ir)
342 {
343    const ir_state_slot *const slots = ir->state_slots;
344    assert(ir->state_slots != NULL);
345
346    for (unsigned int i = 0; i < ir->num_state_slots; i++) {
347       /* This state reference has already been setup by ir_to_mesa, but we'll
348        * get the same index back here.
349        */
350       int index = _mesa_add_state_reference(this->fp->Base.Parameters,
351                                             (gl_state_index *)slots[i].tokens);
352
353       /* Add each of the unique swizzles of the element as a parameter.
354        * This'll end up matching the expected layout of the
355        * array/matrix/structure we're trying to fill in.
356        */
357       int last_swiz = -1;
358       for (unsigned int j = 0; j < 4; j++) {
359          int swiz = GET_SWZ(slots[i].swizzle, j);
360          if (swiz == last_swiz)
361             break;
362          last_swiz = swiz;
363
364          c->prog_data.param_convert[c->prog_data.nr_params] =
365             PARAM_NO_CONVERT;
366          this->param_index[c->prog_data.nr_params] = index;
367          this->param_offset[c->prog_data.nr_params] = swiz;
368          c->prog_data.nr_params++;
369       }
370    }
371 }
372
373 fs_reg *
374 fs_visitor::emit_fragcoord_interpolation(ir_variable *ir)
375 {
376    fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
377    fs_reg wpos = *reg;
378    bool flip = !ir->origin_upper_left ^ c->key.render_to_fbo;
379
380    /* gl_FragCoord.x */
381    if (ir->pixel_center_integer) {
382       emit(BRW_OPCODE_MOV, wpos, this->pixel_x);
383    } else {
384       emit(BRW_OPCODE_ADD, wpos, this->pixel_x, fs_reg(0.5f));
385    }
386    wpos.reg_offset++;
387
388    /* gl_FragCoord.y */
389    if (!flip && ir->pixel_center_integer) {
390       emit(BRW_OPCODE_MOV, wpos, this->pixel_y);
391    } else {
392       fs_reg pixel_y = this->pixel_y;
393       float offset = (ir->pixel_center_integer ? 0.0 : 0.5);
394
395       if (flip) {
396          pixel_y.negate = true;
397          offset += c->key.drawable_height - 1.0;
398       }
399
400       emit(BRW_OPCODE_ADD, wpos, pixel_y, fs_reg(offset));
401    }
402    wpos.reg_offset++;
403
404    /* gl_FragCoord.z */
405    if (intel->gen >= 6) {
406       emit(BRW_OPCODE_MOV, wpos,
407            fs_reg(brw_vec8_grf(c->source_depth_reg, 0)));
408    } else {
409       emit(FS_OPCODE_LINTERP, wpos,
410            this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
411            this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
412            interp_reg(FRAG_ATTRIB_WPOS, 2));
413    }
414    wpos.reg_offset++;
415
416    /* gl_FragCoord.w: Already set up in emit_interpolation */
417    emit(BRW_OPCODE_MOV, wpos, this->wpos_w);
418
419    return reg;
420 }
421
422 fs_inst *
423 fs_visitor::emit_linterp(const fs_reg &attr, const fs_reg &interp,
424                          glsl_interp_qualifier interpolation_mode,
425                          bool is_centroid)
426 {
427    brw_wm_barycentric_interp_mode barycoord_mode;
428    if (is_centroid) {
429       if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
430          barycoord_mode = BRW_WM_PERSPECTIVE_CENTROID_BARYCENTRIC;
431       else
432          barycoord_mode = BRW_WM_NONPERSPECTIVE_CENTROID_BARYCENTRIC;
433    } else {
434       if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
435          barycoord_mode = BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC;
436       else
437          barycoord_mode = BRW_WM_NONPERSPECTIVE_PIXEL_BARYCENTRIC;
438    }
439    return emit(FS_OPCODE_LINTERP, attr,
440                this->delta_x[barycoord_mode],
441                this->delta_y[barycoord_mode], interp);
442 }
443
444 fs_reg *
445 fs_visitor::emit_general_interpolation(ir_variable *ir)
446 {
447    fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
448    reg->type = brw_type_for_base_type(ir->type->get_scalar_type());
449    fs_reg attr = *reg;
450
451    unsigned int array_elements;
452    const glsl_type *type;
453
454    if (ir->type->is_array()) {
455       array_elements = ir->type->length;
456       if (array_elements == 0) {
457          fail("dereferenced array '%s' has length 0\n", ir->name);
458       }
459       type = ir->type->fields.array;
460    } else {
461       array_elements = 1;
462       type = ir->type;
463    }
464
465    glsl_interp_qualifier interpolation_mode =
466       ir->determine_interpolation_mode(c->key.flat_shade);
467
468    int location = ir->location;
469    for (unsigned int i = 0; i < array_elements; i++) {
470       for (unsigned int j = 0; j < type->matrix_columns; j++) {
471          if (urb_setup[location] == -1) {
472             /* If there's no incoming setup data for this slot, don't
473              * emit interpolation for it.
474              */
475             attr.reg_offset += type->vector_elements;
476             location++;
477             continue;
478          }
479
480          if (interpolation_mode == INTERP_QUALIFIER_FLAT) {
481             /* Constant interpolation (flat shading) case. The SF has
482              * handed us defined values in only the constant offset
483              * field of the setup reg.
484              */
485             for (unsigned int k = 0; k < type->vector_elements; k++) {
486                struct brw_reg interp = interp_reg(location, k);
487                interp = suboffset(interp, 3);
488                interp.type = reg->type;
489                emit(FS_OPCODE_CINTERP, attr, fs_reg(interp));
490                attr.reg_offset++;
491             }
492          } else {
493             /* Smooth/noperspective interpolation case. */
494             for (unsigned int k = 0; k < type->vector_elements; k++) {
495                /* FINISHME: At some point we probably want to push
496                 * this farther by giving similar treatment to the
497                 * other potentially constant components of the
498                 * attribute, as well as making brw_vs_constval.c
499                 * handle varyings other than gl_TexCoord.
500                 */
501                if (location >= FRAG_ATTRIB_TEX0 &&
502                    location <= FRAG_ATTRIB_TEX7 &&
503                    k == 3 && !(c->key.proj_attrib_mask & (1 << location))) {
504                   emit(BRW_OPCODE_MOV, attr, fs_reg(1.0f));
505                } else {
506                   struct brw_reg interp = interp_reg(location, k);
507                   emit_linterp(attr, fs_reg(interp), interpolation_mode,
508                                ir->centroid);
509                   if (intel->gen < 6) {
510                      emit(BRW_OPCODE_MUL, attr, attr, this->pixel_w);
511                   }
512                }
513                attr.reg_offset++;
514             }
515
516          }
517          location++;
518       }
519    }
520
521    return reg;
522 }
523
524 fs_reg *
525 fs_visitor::emit_frontfacing_interpolation(ir_variable *ir)
526 {
527    fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
528
529    /* The frontfacing comes in as a bit in the thread payload. */
530    if (intel->gen >= 6) {
531       emit(BRW_OPCODE_ASR, *reg,
532            fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_D)),
533            fs_reg(15));
534       emit(BRW_OPCODE_NOT, *reg, *reg);
535       emit(BRW_OPCODE_AND, *reg, *reg, fs_reg(1));
536    } else {
537       struct brw_reg r1_6ud = retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_UD);
538       /* bit 31 is "primitive is back face", so checking < (1 << 31) gives
539        * us front face
540        */
541       fs_inst *inst = emit(BRW_OPCODE_CMP, *reg,
542                            fs_reg(r1_6ud),
543                            fs_reg(1u << 31));
544       inst->conditional_mod = BRW_CONDITIONAL_L;
545       emit(BRW_OPCODE_AND, *reg, *reg, fs_reg(1u));
546    }
547
548    return reg;
549 }
550
551 fs_inst *
552 fs_visitor::emit_math(enum opcode opcode, fs_reg dst, fs_reg src)
553 {
554    switch (opcode) {
555    case SHADER_OPCODE_RCP:
556    case SHADER_OPCODE_RSQ:
557    case SHADER_OPCODE_SQRT:
558    case SHADER_OPCODE_EXP2:
559    case SHADER_OPCODE_LOG2:
560    case SHADER_OPCODE_SIN:
561    case SHADER_OPCODE_COS:
562       break;
563    default:
564       assert(!"not reached: bad math opcode");
565       return NULL;
566    }
567
568    /* Can't do hstride == 0 args to gen6 math, so expand it out.  We
569     * might be able to do better by doing execsize = 1 math and then
570     * expanding that result out, but we would need to be careful with
571     * masking.
572     *
573     * Gen 6 hardware ignores source modifiers (negate and abs) on math
574     * instructions, so we also move to a temp to set those up.
575     */
576    if (intel->gen == 6 && (src.file == UNIFORM ||
577                            src.abs ||
578                            src.negate)) {
579       fs_reg expanded = fs_reg(this, glsl_type::float_type);
580       emit(BRW_OPCODE_MOV, expanded, src);
581       src = expanded;
582    }
583
584    fs_inst *inst = emit(opcode, dst, src);
585
586    if (intel->gen < 6) {
587       inst->base_mrf = 2;
588       inst->mlen = c->dispatch_width / 8;
589    }
590
591    return inst;
592 }
593
594 fs_inst *
595 fs_visitor::emit_math(enum opcode opcode, fs_reg dst, fs_reg src0, fs_reg src1)
596 {
597    int base_mrf = 2;
598    fs_inst *inst;
599
600    switch (opcode) {
601    case SHADER_OPCODE_POW:
602    case SHADER_OPCODE_INT_QUOTIENT:
603    case SHADER_OPCODE_INT_REMAINDER:
604       break;
605    default:
606       assert(!"not reached: unsupported binary math opcode.");
607       return NULL;
608    }
609
610    if (intel->gen >= 7) {
611       inst = emit(opcode, dst, src0, src1);
612    } else if (intel->gen == 6) {
613       /* Can't do hstride == 0 args to gen6 math, so expand it out.
614        *
615        * The hardware ignores source modifiers (negate and abs) on math
616        * instructions, so we also move to a temp to set those up.
617        */
618       if (src0.file == UNIFORM || src0.abs || src0.negate) {
619          fs_reg expanded = fs_reg(this, glsl_type::float_type);
620          expanded.type = src0.type;
621          emit(BRW_OPCODE_MOV, expanded, src0);
622          src0 = expanded;
623       }
624
625       if (src1.file == UNIFORM || src1.abs || src1.negate) {
626          fs_reg expanded = fs_reg(this, glsl_type::float_type);
627          expanded.type = src1.type;
628          emit(BRW_OPCODE_MOV, expanded, src1);
629          src1 = expanded;
630       }
631
632       inst = emit(opcode, dst, src0, src1);
633    } else {
634       /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
635        * "Message Payload":
636        *
637        * "Operand0[7].  For the INT DIV functions, this operand is the
638        *  denominator."
639        *  ...
640        * "Operand1[7].  For the INT DIV functions, this operand is the
641        *  numerator."
642        */
643       bool is_int_div = opcode != SHADER_OPCODE_POW;
644       fs_reg &op0 = is_int_div ? src1 : src0;
645       fs_reg &op1 = is_int_div ? src0 : src1;
646
647       emit(BRW_OPCODE_MOV, fs_reg(MRF, base_mrf + 1, op1.type), op1);
648       inst = emit(opcode, dst, op0, reg_null_f);
649
650       inst->base_mrf = base_mrf;
651       inst->mlen = 2 * c->dispatch_width / 8;
652    }
653    return inst;
654 }
655
656 /**
657  * To be called after the last _mesa_add_state_reference() call, to
658  * set up prog_data.param[] for assign_curb_setup() and
659  * setup_pull_constants().
660  */
661 void
662 fs_visitor::setup_paramvalues_refs()
663 {
664    if (c->dispatch_width != 8)
665       return;
666
667    /* Set up the pointers to ParamValues now that that array is finalized. */
668    for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
669       c->prog_data.param[i] =
670          (const float *)fp->Base.Parameters->ParameterValues[this->param_index[i]] +
671          this->param_offset[i];
672    }
673 }
674
675 void
676 fs_visitor::assign_curb_setup()
677 {
678    c->prog_data.curb_read_length = ALIGN(c->prog_data.nr_params, 8) / 8;
679    if (c->dispatch_width == 8) {
680       c->prog_data.first_curbe_grf = c->nr_payload_regs;
681    } else {
682       c->prog_data.first_curbe_grf_16 = c->nr_payload_regs;
683    }
684
685    /* Map the offsets in the UNIFORM file to fixed HW regs. */
686    foreach_list(node, &this->instructions) {
687       fs_inst *inst = (fs_inst *)node;
688
689       for (unsigned int i = 0; i < 3; i++) {
690          if (inst->src[i].file == UNIFORM) {
691             int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
692             struct brw_reg brw_reg = brw_vec1_grf(c->nr_payload_regs +
693                                                   constant_nr / 8,
694                                                   constant_nr % 8);
695
696             inst->src[i].file = FIXED_HW_REG;
697             inst->src[i].fixed_hw_reg = retype(brw_reg, inst->src[i].type);
698          }
699       }
700    }
701 }
702
703 void
704 fs_visitor::calculate_urb_setup()
705 {
706    for (unsigned int i = 0; i < FRAG_ATTRIB_MAX; i++) {
707       urb_setup[i] = -1;
708    }
709
710    int urb_next = 0;
711    /* Figure out where each of the incoming setup attributes lands. */
712    if (intel->gen >= 6) {
713       for (unsigned int i = 0; i < FRAG_ATTRIB_MAX; i++) {
714          if (fp->Base.InputsRead & BITFIELD64_BIT(i)) {
715             urb_setup[i] = urb_next++;
716          }
717       }
718    } else {
719       /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
720       for (unsigned int i = 0; i < VERT_RESULT_MAX; i++) {
721          if (c->key.vp_outputs_written & BITFIELD64_BIT(i)) {
722             int fp_index = _mesa_vert_result_to_frag_attrib((gl_vert_result) i);
723
724             if (fp_index >= 0)
725                urb_setup[fp_index] = urb_next++;
726          }
727       }
728
729       /*
730        * It's a FS only attribute, and we did interpolation for this attribute
731        * in SF thread. So, count it here, too.
732        *
733        * See compile_sf_prog() for more info.
734        */
735       if (brw->fragment_program->Base.InputsRead & BITFIELD64_BIT(FRAG_ATTRIB_PNTC))
736          urb_setup[FRAG_ATTRIB_PNTC] = urb_next++;
737    }
738
739    /* Each attribute is 4 setup channels, each of which is half a reg. */
740    c->prog_data.urb_read_length = urb_next * 2;
741 }
742
743 void
744 fs_visitor::assign_urb_setup()
745 {
746    int urb_start = c->nr_payload_regs + c->prog_data.curb_read_length;
747
748    /* Offset all the urb_setup[] index by the actual position of the
749     * setup regs, now that the location of the constants has been chosen.
750     */
751    foreach_list(node, &this->instructions) {
752       fs_inst *inst = (fs_inst *)node;
753
754       if (inst->opcode == FS_OPCODE_LINTERP) {
755          assert(inst->src[2].file == FIXED_HW_REG);
756          inst->src[2].fixed_hw_reg.nr += urb_start;
757       }
758
759       if (inst->opcode == FS_OPCODE_CINTERP) {
760          assert(inst->src[0].file == FIXED_HW_REG);
761          inst->src[0].fixed_hw_reg.nr += urb_start;
762       }
763    }
764
765    this->first_non_payload_grf = urb_start + c->prog_data.urb_read_length;
766 }
767
768 /**
769  * Split large virtual GRFs into separate components if we can.
770  *
771  * This is mostly duplicated with what brw_fs_vector_splitting does,
772  * but that's really conservative because it's afraid of doing
773  * splitting that doesn't result in real progress after the rest of
774  * the optimization phases, which would cause infinite looping in
775  * optimization.  We can do it once here, safely.  This also has the
776  * opportunity to split interpolated values, or maybe even uniforms,
777  * which we don't have at the IR level.
778  *
779  * We want to split, because virtual GRFs are what we register
780  * allocate and spill (due to contiguousness requirements for some
781  * instructions), and they're what we naturally generate in the
782  * codegen process, but most virtual GRFs don't actually need to be
783  * contiguous sets of GRFs.  If we split, we'll end up with reduced
784  * live intervals and better dead code elimination and coalescing.
785  */
786 void
787 fs_visitor::split_virtual_grfs()
788 {
789    int num_vars = this->virtual_grf_next;
790    bool split_grf[num_vars];
791    int new_virtual_grf[num_vars];
792
793    /* Try to split anything > 0 sized. */
794    for (int i = 0; i < num_vars; i++) {
795       if (this->virtual_grf_sizes[i] != 1)
796          split_grf[i] = true;
797       else
798          split_grf[i] = false;
799    }
800
801    if (brw->has_pln &&
802        this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].file == GRF) {
803       /* PLN opcodes rely on the delta_xy being contiguous.  We only have to
804        * check this for BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC, because prior to
805        * Gen6, that was the only supported interpolation mode, and since Gen6,
806        * delta_x and delta_y are in fixed hardware registers.
807        */
808       split_grf[this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].reg] =
809          false;
810    }
811
812    foreach_list(node, &this->instructions) {
813       fs_inst *inst = (fs_inst *)node;
814
815       /* Texturing produces 4 contiguous registers, so no splitting. */
816       if (inst->is_tex()) {
817          split_grf[inst->dst.reg] = false;
818       }
819    }
820
821    /* Allocate new space for split regs.  Note that the virtual
822     * numbers will be contiguous.
823     */
824    for (int i = 0; i < num_vars; i++) {
825       if (split_grf[i]) {
826          new_virtual_grf[i] = virtual_grf_alloc(1);
827          for (int j = 2; j < this->virtual_grf_sizes[i]; j++) {
828             int reg = virtual_grf_alloc(1);
829             assert(reg == new_virtual_grf[i] + j - 1);
830             (void) reg;
831          }
832          this->virtual_grf_sizes[i] = 1;
833       }
834    }
835
836    foreach_list(node, &this->instructions) {
837       fs_inst *inst = (fs_inst *)node;
838
839       if (inst->dst.file == GRF &&
840           split_grf[inst->dst.reg] &&
841           inst->dst.reg_offset != 0) {
842          inst->dst.reg = (new_virtual_grf[inst->dst.reg] +
843                           inst->dst.reg_offset - 1);
844          inst->dst.reg_offset = 0;
845       }
846       for (int i = 0; i < 3; i++) {
847          if (inst->src[i].file == GRF &&
848              split_grf[inst->src[i].reg] &&
849              inst->src[i].reg_offset != 0) {
850             inst->src[i].reg = (new_virtual_grf[inst->src[i].reg] +
851                                 inst->src[i].reg_offset - 1);
852             inst->src[i].reg_offset = 0;
853          }
854       }
855    }
856    this->live_intervals_valid = false;
857 }
858
859 bool
860 fs_visitor::remove_dead_constants()
861 {
862    if (c->dispatch_width == 8) {
863       this->params_remap = ralloc_array(mem_ctx, int, c->prog_data.nr_params);
864
865       for (unsigned int i = 0; i < c->prog_data.nr_params; i++)
866          this->params_remap[i] = -1;
867
868       /* Find which params are still in use. */
869       foreach_list(node, &this->instructions) {
870          fs_inst *inst = (fs_inst *)node;
871
872          for (int i = 0; i < 3; i++) {
873             int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
874
875             if (inst->src[i].file != UNIFORM)
876                continue;
877
878             assert(constant_nr < (int)c->prog_data.nr_params);
879
880             /* For now, set this to non-negative.  We'll give it the
881              * actual new number in a moment, in order to keep the
882              * register numbers nicely ordered.
883              */
884             this->params_remap[constant_nr] = 0;
885          }
886       }
887
888       /* Figure out what the new numbers for the params will be.  At some
889        * point when we're doing uniform array access, we're going to want
890        * to keep the distinction between .reg and .reg_offset, but for
891        * now we don't care.
892        */
893       unsigned int new_nr_params = 0;
894       for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
895          if (this->params_remap[i] != -1) {
896             this->params_remap[i] = new_nr_params++;
897          }
898       }
899
900       /* Update the list of params to be uploaded to match our new numbering. */
901       for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
902          int remapped = this->params_remap[i];
903
904          if (remapped == -1)
905             continue;
906
907          /* We've already done setup_paramvalues_refs() so no need to worry
908           * about param_index and param_offset.
909           */
910          c->prog_data.param[remapped] = c->prog_data.param[i];
911          c->prog_data.param_convert[remapped] = c->prog_data.param_convert[i];
912       }
913
914       c->prog_data.nr_params = new_nr_params;
915    } else {
916       /* This should have been generated in the 8-wide pass already. */
917       assert(this->params_remap);
918    }
919
920    /* Now do the renumbering of the shader to remove unused params. */
921    foreach_list(node, &this->instructions) {
922       fs_inst *inst = (fs_inst *)node;
923
924       for (int i = 0; i < 3; i++) {
925          int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
926
927          if (inst->src[i].file != UNIFORM)
928             continue;
929
930          assert(this->params_remap[constant_nr] != -1);
931          inst->src[i].reg = this->params_remap[constant_nr];
932          inst->src[i].reg_offset = 0;
933       }
934    }
935
936    return true;
937 }
938
939 /**
940  * Choose accesses from the UNIFORM file to demote to using the pull
941  * constant buffer.
942  *
943  * We allow a fragment shader to have more than the specified minimum
944  * maximum number of fragment shader uniform components (64).  If
945  * there are too many of these, they'd fill up all of register space.
946  * So, this will push some of them out to the pull constant buffer and
947  * update the program to load them.
948  */
949 void
950 fs_visitor::setup_pull_constants()
951 {
952    /* Only allow 16 registers (128 uniform components) as push constants. */
953    unsigned int max_uniform_components = 16 * 8;
954    if (c->prog_data.nr_params <= max_uniform_components)
955       return;
956
957    if (c->dispatch_width == 16) {
958       fail("Pull constants not supported in 16-wide\n");
959       return;
960    }
961
962    /* Just demote the end of the list.  We could probably do better
963     * here, demoting things that are rarely used in the program first.
964     */
965    int pull_uniform_base = max_uniform_components;
966    int pull_uniform_count = c->prog_data.nr_params - pull_uniform_base;
967
968    foreach_list(node, &this->instructions) {
969       fs_inst *inst = (fs_inst *)node;
970
971       for (int i = 0; i < 3; i++) {
972          if (inst->src[i].file != UNIFORM)
973             continue;
974
975          int uniform_nr = inst->src[i].reg + inst->src[i].reg_offset;
976          if (uniform_nr < pull_uniform_base)
977             continue;
978
979          fs_reg dst = fs_reg(this, glsl_type::float_type);
980          fs_inst *pull = new(mem_ctx) fs_inst(FS_OPCODE_PULL_CONSTANT_LOAD,
981                                               dst);
982          pull->offset = ((uniform_nr - pull_uniform_base) * 4) & ~15;
983          pull->ir = inst->ir;
984          pull->annotation = inst->annotation;
985          pull->base_mrf = 14;
986          pull->mlen = 1;
987
988          inst->insert_before(pull);
989
990          inst->src[i].file = GRF;
991          inst->src[i].reg = dst.reg;
992          inst->src[i].reg_offset = 0;
993          inst->src[i].smear = (uniform_nr - pull_uniform_base) & 3;
994       }
995    }
996
997    for (int i = 0; i < pull_uniform_count; i++) {
998       c->prog_data.pull_param[i] = c->prog_data.param[pull_uniform_base + i];
999       c->prog_data.pull_param_convert[i] =
1000          c->prog_data.param_convert[pull_uniform_base + i];
1001    }
1002    c->prog_data.nr_params -= pull_uniform_count;
1003    c->prog_data.nr_pull_params = pull_uniform_count;
1004 }
1005
1006 /**
1007  * Attempts to move immediate constants into the immediate
1008  * constant slot of following instructions.
1009  *
1010  * Immediate constants are a bit tricky -- they have to be in the last
1011  * operand slot, you can't do abs/negate on them,
1012  */
1013
1014 bool
1015 fs_visitor::propagate_constants()
1016 {
1017    bool progress = false;
1018
1019    calculate_live_intervals();
1020
1021    foreach_list(node, &this->instructions) {
1022       fs_inst *inst = (fs_inst *)node;
1023
1024       if (inst->opcode != BRW_OPCODE_MOV ||
1025           inst->predicated ||
1026           inst->dst.file != GRF || inst->src[0].file != IMM ||
1027           inst->dst.type != inst->src[0].type ||
1028           (c->dispatch_width == 16 &&
1029            (inst->force_uncompressed || inst->force_sechalf)))
1030          continue;
1031
1032       /* Don't bother with cases where we should have had the
1033        * operation on the constant folded in GLSL already.
1034        */
1035       if (inst->saturate)
1036          continue;
1037
1038       /* Found a move of a constant to a GRF.  Find anything else using the GRF
1039        * before it's written, and replace it with the constant if we can.
1040        */
1041       for (fs_inst *scan_inst = (fs_inst *)inst->next;
1042            !scan_inst->is_tail_sentinel();
1043            scan_inst = (fs_inst *)scan_inst->next) {
1044          if (scan_inst->opcode == BRW_OPCODE_DO ||
1045              scan_inst->opcode == BRW_OPCODE_WHILE ||
1046              scan_inst->opcode == BRW_OPCODE_ELSE ||
1047              scan_inst->opcode == BRW_OPCODE_ENDIF) {
1048             break;
1049          }
1050
1051          for (int i = 2; i >= 0; i--) {
1052             if (scan_inst->src[i].file != GRF ||
1053                 scan_inst->src[i].reg != inst->dst.reg ||
1054                 scan_inst->src[i].reg_offset != inst->dst.reg_offset)
1055                continue;
1056
1057             /* Don't bother with cases where we should have had the
1058              * operation on the constant folded in GLSL already.
1059              */
1060             if (scan_inst->src[i].negate || scan_inst->src[i].abs)
1061                continue;
1062
1063             switch (scan_inst->opcode) {
1064             case BRW_OPCODE_MOV:
1065                scan_inst->src[i] = inst->src[0];
1066                progress = true;
1067                break;
1068
1069             case BRW_OPCODE_MUL:
1070             case BRW_OPCODE_ADD:
1071                if (i == 1) {
1072                   scan_inst->src[i] = inst->src[0];
1073                   progress = true;
1074                } else if (i == 0 && scan_inst->src[1].file != IMM) {
1075                   /* Fit this constant in by commuting the operands.
1076                    * Exception: we can't do this for 32-bit integer MUL
1077                    * because it's asymmetric.
1078                    */
1079                   if (scan_inst->opcode == BRW_OPCODE_MUL &&
1080                       (scan_inst->src[1].type == BRW_REGISTER_TYPE_D ||
1081                        scan_inst->src[1].type == BRW_REGISTER_TYPE_UD))
1082                      break;
1083                   scan_inst->src[0] = scan_inst->src[1];
1084                   scan_inst->src[1] = inst->src[0];
1085                   progress = true;
1086                }
1087                break;
1088
1089             case BRW_OPCODE_CMP:
1090             case BRW_OPCODE_IF:
1091                if (i == 1) {
1092                   scan_inst->src[i] = inst->src[0];
1093                   progress = true;
1094                } else if (i == 0 && scan_inst->src[1].file != IMM) {
1095                   uint32_t new_cmod;
1096
1097                   new_cmod = brw_swap_cmod(scan_inst->conditional_mod);
1098                   if (new_cmod != ~0u) {
1099                      /* Fit this constant in by swapping the operands and
1100                       * flipping the test
1101                       */
1102                      scan_inst->src[0] = scan_inst->src[1];
1103                      scan_inst->src[1] = inst->src[0];
1104                      scan_inst->conditional_mod = new_cmod;
1105                      progress = true;
1106                   }
1107                }
1108                break;
1109
1110             case BRW_OPCODE_SEL:
1111                if (i == 1) {
1112                   scan_inst->src[i] = inst->src[0];
1113                   progress = true;
1114                } else if (i == 0 && scan_inst->src[1].file != IMM) {
1115                   scan_inst->src[0] = scan_inst->src[1];
1116                   scan_inst->src[1] = inst->src[0];
1117
1118                   /* If this was predicated, flipping operands means
1119                    * we also need to flip the predicate.
1120                    */
1121                   if (scan_inst->conditional_mod == BRW_CONDITIONAL_NONE) {
1122                      scan_inst->predicate_inverse =
1123                         !scan_inst->predicate_inverse;
1124                   }
1125                   progress = true;
1126                }
1127                break;
1128
1129             case SHADER_OPCODE_RCP:
1130                /* The hardware doesn't do math on immediate values
1131                 * (because why are you doing that, seriously?), but
1132                 * the correct answer is to just constant fold it
1133                 * anyway.
1134                 */
1135                assert(i == 0);
1136                if (inst->src[0].imm.f != 0.0f) {
1137                   scan_inst->opcode = BRW_OPCODE_MOV;
1138                   scan_inst->src[0] = inst->src[0];
1139                   scan_inst->src[0].imm.f = 1.0f / scan_inst->src[0].imm.f;
1140                   progress = true;
1141                }
1142                break;
1143
1144             default:
1145                break;
1146             }
1147          }
1148
1149          if (scan_inst->dst.file == GRF &&
1150              scan_inst->dst.reg == inst->dst.reg &&
1151              (scan_inst->dst.reg_offset == inst->dst.reg_offset ||
1152               scan_inst->is_tex())) {
1153             break;
1154          }
1155       }
1156    }
1157
1158    if (progress)
1159        this->live_intervals_valid = false;
1160
1161    return progress;
1162 }
1163
1164
1165 /**
1166  * Attempts to move immediate constants into the immediate
1167  * constant slot of following instructions.
1168  *
1169  * Immediate constants are a bit tricky -- they have to be in the last
1170  * operand slot, you can't do abs/negate on them,
1171  */
1172
1173 bool
1174 fs_visitor::opt_algebraic()
1175 {
1176    bool progress = false;
1177
1178    calculate_live_intervals();
1179
1180    foreach_list(node, &this->instructions) {
1181       fs_inst *inst = (fs_inst *)node;
1182
1183       switch (inst->opcode) {
1184       case BRW_OPCODE_MUL:
1185          if (inst->src[1].file != IMM)
1186             continue;
1187
1188          /* a * 1.0 = a */
1189          if (inst->src[1].type == BRW_REGISTER_TYPE_F &&
1190              inst->src[1].imm.f == 1.0) {
1191             inst->opcode = BRW_OPCODE_MOV;
1192             inst->src[1] = reg_undef;
1193             progress = true;
1194             break;
1195          }
1196
1197          break;
1198       default:
1199          break;
1200       }
1201    }
1202
1203    return progress;
1204 }
1205
1206 /**
1207  * Must be called after calculate_live_intervales() to remove unused
1208  * writes to registers -- register allocation will fail otherwise
1209  * because something deffed but not used won't be considered to
1210  * interfere with other regs.
1211  */
1212 bool
1213 fs_visitor::dead_code_eliminate()
1214 {
1215    bool progress = false;
1216    int pc = 0;
1217
1218    calculate_live_intervals();
1219
1220    foreach_list_safe(node, &this->instructions) {
1221       fs_inst *inst = (fs_inst *)node;
1222
1223       if (inst->dst.file == GRF && this->virtual_grf_use[inst->dst.reg] <= pc) {
1224          inst->remove();
1225          progress = true;
1226       }
1227
1228       pc++;
1229    }
1230
1231    if (progress)
1232       live_intervals_valid = false;
1233
1234    return progress;
1235 }
1236
1237 /**
1238  * Implements a second type of register coalescing: This one checks if
1239  * the two regs involved in a raw move don't interfere, in which case
1240  * they can both by stored in the same place and the MOV removed.
1241  */
1242 bool
1243 fs_visitor::register_coalesce_2()
1244 {
1245    bool progress = false;
1246
1247    calculate_live_intervals();
1248
1249    foreach_list_safe(node, &this->instructions) {
1250       fs_inst *inst = (fs_inst *)node;
1251
1252       if (inst->opcode != BRW_OPCODE_MOV ||
1253           inst->predicated ||
1254           inst->saturate ||
1255           inst->src[0].file != GRF ||
1256           inst->src[0].negate ||
1257           inst->src[0].abs ||
1258           inst->src[0].smear != -1 ||
1259           inst->dst.file != GRF ||
1260           inst->dst.type != inst->src[0].type ||
1261           virtual_grf_sizes[inst->src[0].reg] != 1 ||
1262           virtual_grf_interferes(inst->dst.reg, inst->src[0].reg)) {
1263          continue;
1264       }
1265
1266       int reg_from = inst->src[0].reg;
1267       assert(inst->src[0].reg_offset == 0);
1268       int reg_to = inst->dst.reg;
1269       int reg_to_offset = inst->dst.reg_offset;
1270
1271       foreach_list_safe(node, &this->instructions) {
1272          fs_inst *scan_inst = (fs_inst *)node;
1273
1274          if (scan_inst->dst.file == GRF &&
1275              scan_inst->dst.reg == reg_from) {
1276             scan_inst->dst.reg = reg_to;
1277             scan_inst->dst.reg_offset = reg_to_offset;
1278          }
1279          for (int i = 0; i < 3; i++) {
1280             if (scan_inst->src[i].file == GRF &&
1281                 scan_inst->src[i].reg == reg_from) {
1282                scan_inst->src[i].reg = reg_to;
1283                scan_inst->src[i].reg_offset = reg_to_offset;
1284             }
1285          }
1286       }
1287
1288       inst->remove();
1289       live_intervals_valid = false;
1290       progress = true;
1291       continue;
1292    }
1293
1294    return progress;
1295 }
1296
1297 bool
1298 fs_visitor::register_coalesce()
1299 {
1300    bool progress = false;
1301    int if_depth = 0;
1302    int loop_depth = 0;
1303
1304    foreach_list_safe(node, &this->instructions) {
1305       fs_inst *inst = (fs_inst *)node;
1306
1307       /* Make sure that we dominate the instructions we're going to
1308        * scan for interfering with our coalescing, or we won't have
1309        * scanned enough to see if anything interferes with our
1310        * coalescing.  We don't dominate the following instructions if
1311        * we're in a loop or an if block.
1312        */
1313       switch (inst->opcode) {
1314       case BRW_OPCODE_DO:
1315          loop_depth++;
1316          break;
1317       case BRW_OPCODE_WHILE:
1318          loop_depth--;
1319          break;
1320       case BRW_OPCODE_IF:
1321          if_depth++;
1322          break;
1323       case BRW_OPCODE_ENDIF:
1324          if_depth--;
1325          break;
1326       default:
1327          break;
1328       }
1329       if (loop_depth || if_depth)
1330          continue;
1331
1332       if (inst->opcode != BRW_OPCODE_MOV ||
1333           inst->predicated ||
1334           inst->saturate ||
1335           inst->dst.file != GRF || (inst->src[0].file != GRF &&
1336                                     inst->src[0].file != UNIFORM)||
1337           inst->dst.type != inst->src[0].type)
1338          continue;
1339
1340       bool has_source_modifiers = inst->src[0].abs || inst->src[0].negate;
1341
1342       /* Found a move of a GRF to a GRF.  Let's see if we can coalesce
1343        * them: check for no writes to either one until the exit of the
1344        * program.
1345        */
1346       bool interfered = false;
1347
1348       for (fs_inst *scan_inst = (fs_inst *)inst->next;
1349            !scan_inst->is_tail_sentinel();
1350            scan_inst = (fs_inst *)scan_inst->next) {
1351          if (scan_inst->dst.file == GRF) {
1352             if (scan_inst->dst.reg == inst->dst.reg &&
1353                 (scan_inst->dst.reg_offset == inst->dst.reg_offset ||
1354                  scan_inst->is_tex())) {
1355                interfered = true;
1356                break;
1357             }
1358             if (inst->src[0].file == GRF &&
1359                 scan_inst->dst.reg == inst->src[0].reg &&
1360                 (scan_inst->dst.reg_offset == inst->src[0].reg_offset ||
1361                  scan_inst->is_tex())) {
1362                interfered = true;
1363                break;
1364             }
1365          }
1366
1367          /* The gen6 MATH instruction can't handle source modifiers or
1368           * unusual register regions, so avoid coalescing those for
1369           * now.  We should do something more specific.
1370           */
1371          if (intel->gen >= 6 &&
1372              scan_inst->is_math() &&
1373              (has_source_modifiers || inst->src[0].file == UNIFORM)) {
1374             interfered = true;
1375             break;
1376          }
1377
1378          /* The accumulator result appears to get used for the
1379           * conditional modifier generation.  When negating a UD
1380           * value, there is a 33rd bit generated for the sign in the
1381           * accumulator value, so now you can't check, for example,
1382           * equality with a 32-bit value.  See piglit fs-op-neg-uint.
1383           */
1384          if (scan_inst->conditional_mod &&
1385              inst->src[0].negate &&
1386              inst->src[0].type == BRW_REGISTER_TYPE_UD) {
1387             interfered = true;
1388             break;
1389          }
1390       }
1391       if (interfered) {
1392          continue;
1393       }
1394
1395       /* Rewrite the later usage to point at the source of the move to
1396        * be removed.
1397        */
1398       for (fs_inst *scan_inst = inst;
1399            !scan_inst->is_tail_sentinel();
1400            scan_inst = (fs_inst *)scan_inst->next) {
1401          for (int i = 0; i < 3; i++) {
1402             if (scan_inst->src[i].file == GRF &&
1403                 scan_inst->src[i].reg == inst->dst.reg &&
1404                 scan_inst->src[i].reg_offset == inst->dst.reg_offset) {
1405                fs_reg new_src = inst->src[0];
1406                if (scan_inst->src[i].abs) {
1407                   new_src.negate = 0;
1408                   new_src.abs = 1;
1409                }
1410                new_src.negate ^= scan_inst->src[i].negate;
1411                scan_inst->src[i] = new_src;
1412             }
1413          }
1414       }
1415
1416       inst->remove();
1417       progress = true;
1418    }
1419
1420    if (progress)
1421       live_intervals_valid = false;
1422
1423    return progress;
1424 }
1425
1426
1427 bool
1428 fs_visitor::compute_to_mrf()
1429 {
1430    bool progress = false;
1431    int next_ip = 0;
1432
1433    calculate_live_intervals();
1434
1435    foreach_list_safe(node, &this->instructions) {
1436       fs_inst *inst = (fs_inst *)node;
1437
1438       int ip = next_ip;
1439       next_ip++;
1440
1441       if (inst->opcode != BRW_OPCODE_MOV ||
1442           inst->predicated ||
1443           inst->dst.file != MRF || inst->src[0].file != GRF ||
1444           inst->dst.type != inst->src[0].type ||
1445           inst->src[0].abs || inst->src[0].negate || inst->src[0].smear != -1)
1446          continue;
1447
1448       /* Work out which hardware MRF registers are written by this
1449        * instruction.
1450        */
1451       int mrf_low = inst->dst.reg & ~BRW_MRF_COMPR4;
1452       int mrf_high;
1453       if (inst->dst.reg & BRW_MRF_COMPR4) {
1454          mrf_high = mrf_low + 4;
1455       } else if (c->dispatch_width == 16 &&
1456                  (!inst->force_uncompressed && !inst->force_sechalf)) {
1457          mrf_high = mrf_low + 1;
1458       } else {
1459          mrf_high = mrf_low;
1460       }
1461
1462       /* Can't compute-to-MRF this GRF if someone else was going to
1463        * read it later.
1464        */
1465       if (this->virtual_grf_use[inst->src[0].reg] > ip)
1466          continue;
1467
1468       /* Found a move of a GRF to a MRF.  Let's see if we can go
1469        * rewrite the thing that made this GRF to write into the MRF.
1470        */
1471       fs_inst *scan_inst;
1472       for (scan_inst = (fs_inst *)inst->prev;
1473            scan_inst->prev != NULL;
1474            scan_inst = (fs_inst *)scan_inst->prev) {
1475          if (scan_inst->dst.file == GRF &&
1476              scan_inst->dst.reg == inst->src[0].reg) {
1477             /* Found the last thing to write our reg we want to turn
1478              * into a compute-to-MRF.
1479              */
1480
1481             if (scan_inst->is_tex()) {
1482                /* texturing writes several continuous regs, so we can't
1483                 * compute-to-mrf that.
1484                 */
1485                break;
1486             }
1487
1488             /* If it's predicated, it (probably) didn't populate all
1489              * the channels.  We might be able to rewrite everything
1490              * that writes that reg, but it would require smarter
1491              * tracking to delay the rewriting until complete success.
1492              */
1493             if (scan_inst->predicated)
1494                break;
1495
1496             /* If it's half of register setup and not the same half as
1497              * our MOV we're trying to remove, bail for now.
1498              */
1499             if (scan_inst->force_uncompressed != inst->force_uncompressed ||
1500                 scan_inst->force_sechalf != inst->force_sechalf) {
1501                break;
1502             }
1503
1504             /* SEND instructions can't have MRF as a destination. */
1505             if (scan_inst->mlen)
1506                break;
1507
1508             if (intel->gen >= 6) {
1509                /* gen6 math instructions must have the destination be
1510                 * GRF, so no compute-to-MRF for them.
1511                 */
1512                if (scan_inst->is_math()) {
1513                   break;
1514                }
1515             }
1516
1517             if (scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
1518                /* Found the creator of our MRF's source value. */
1519                scan_inst->dst.file = MRF;
1520                scan_inst->dst.reg = inst->dst.reg;
1521                scan_inst->saturate |= inst->saturate;
1522                inst->remove();
1523                progress = true;
1524             }
1525             break;
1526          }
1527
1528          /* We don't handle flow control here.  Most computation of
1529           * values that end up in MRFs are shortly before the MRF
1530           * write anyway.
1531           */
1532          if (scan_inst->opcode == BRW_OPCODE_DO ||
1533              scan_inst->opcode == BRW_OPCODE_WHILE ||
1534              scan_inst->opcode == BRW_OPCODE_ELSE ||
1535              scan_inst->opcode == BRW_OPCODE_ENDIF) {
1536             break;
1537          }
1538
1539          /* You can't read from an MRF, so if someone else reads our
1540           * MRF's source GRF that we wanted to rewrite, that stops us.
1541           */
1542          bool interfered = false;
1543          for (int i = 0; i < 3; i++) {
1544             if (scan_inst->src[i].file == GRF &&
1545                 scan_inst->src[i].reg == inst->src[0].reg &&
1546                 scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
1547                interfered = true;
1548             }
1549          }
1550          if (interfered)
1551             break;
1552
1553          if (scan_inst->dst.file == MRF) {
1554             /* If somebody else writes our MRF here, we can't
1555              * compute-to-MRF before that.
1556              */
1557             int scan_mrf_low = scan_inst->dst.reg & ~BRW_MRF_COMPR4;
1558             int scan_mrf_high;
1559
1560             if (scan_inst->dst.reg & BRW_MRF_COMPR4) {
1561                scan_mrf_high = scan_mrf_low + 4;
1562             } else if (c->dispatch_width == 16 &&
1563                        (!scan_inst->force_uncompressed &&
1564                         !scan_inst->force_sechalf)) {
1565                scan_mrf_high = scan_mrf_low + 1;
1566             } else {
1567                scan_mrf_high = scan_mrf_low;
1568             }
1569
1570             if (mrf_low == scan_mrf_low ||
1571                 mrf_low == scan_mrf_high ||
1572                 mrf_high == scan_mrf_low ||
1573                 mrf_high == scan_mrf_high) {
1574                break;
1575             }
1576          }
1577
1578          if (scan_inst->mlen > 0) {
1579             /* Found a SEND instruction, which means that there are
1580              * live values in MRFs from base_mrf to base_mrf +
1581              * scan_inst->mlen - 1.  Don't go pushing our MRF write up
1582              * above it.
1583              */
1584             if (mrf_low >= scan_inst->base_mrf &&
1585                 mrf_low < scan_inst->base_mrf + scan_inst->mlen) {
1586                break;
1587             }
1588             if (mrf_high >= scan_inst->base_mrf &&
1589                 mrf_high < scan_inst->base_mrf + scan_inst->mlen) {
1590                break;
1591             }
1592          }
1593       }
1594    }
1595
1596    return progress;
1597 }
1598
1599 /**
1600  * Walks through basic blocks, looking for repeated MRF writes and
1601  * removing the later ones.
1602  */
1603 bool
1604 fs_visitor::remove_duplicate_mrf_writes()
1605 {
1606    fs_inst *last_mrf_move[16];
1607    bool progress = false;
1608
1609    /* Need to update the MRF tracking for compressed instructions. */
1610    if (c->dispatch_width == 16)
1611       return false;
1612
1613    memset(last_mrf_move, 0, sizeof(last_mrf_move));
1614
1615    foreach_list_safe(node, &this->instructions) {
1616       fs_inst *inst = (fs_inst *)node;
1617
1618       switch (inst->opcode) {
1619       case BRW_OPCODE_DO:
1620       case BRW_OPCODE_WHILE:
1621       case BRW_OPCODE_IF:
1622       case BRW_OPCODE_ELSE:
1623       case BRW_OPCODE_ENDIF:
1624          memset(last_mrf_move, 0, sizeof(last_mrf_move));
1625          continue;
1626       default:
1627          break;
1628       }
1629
1630       if (inst->opcode == BRW_OPCODE_MOV &&
1631           inst->dst.file == MRF) {
1632          fs_inst *prev_inst = last_mrf_move[inst->dst.reg];
1633          if (prev_inst && inst->equals(prev_inst)) {
1634             inst->remove();
1635             progress = true;
1636             continue;
1637          }
1638       }
1639
1640       /* Clear out the last-write records for MRFs that were overwritten. */
1641       if (inst->dst.file == MRF) {
1642          last_mrf_move[inst->dst.reg] = NULL;
1643       }
1644
1645       if (inst->mlen > 0) {
1646          /* Found a SEND instruction, which will include two or fewer
1647           * implied MRF writes.  We could do better here.
1648           */
1649          for (int i = 0; i < implied_mrf_writes(inst); i++) {
1650             last_mrf_move[inst->base_mrf + i] = NULL;
1651          }
1652       }
1653
1654       /* Clear out any MRF move records whose sources got overwritten. */
1655       if (inst->dst.file == GRF) {
1656          for (unsigned int i = 0; i < Elements(last_mrf_move); i++) {
1657             if (last_mrf_move[i] &&
1658                 last_mrf_move[i]->src[0].reg == inst->dst.reg) {
1659                last_mrf_move[i] = NULL;
1660             }
1661          }
1662       }
1663
1664       if (inst->opcode == BRW_OPCODE_MOV &&
1665           inst->dst.file == MRF &&
1666           inst->src[0].file == GRF &&
1667           !inst->predicated) {
1668          last_mrf_move[inst->dst.reg] = inst;
1669       }
1670    }
1671
1672    return progress;
1673 }
1674
1675 /**
1676  * Possibly returns an instruction that set up @param reg.
1677  *
1678  * Sometimes we want to take the result of some expression/variable
1679  * dereference tree and rewrite the instruction generating the result
1680  * of the tree.  When processing the tree, we know that the
1681  * instructions generated are all writing temporaries that are dead
1682  * outside of this tree.  So, if we have some instructions that write
1683  * a temporary, we're free to point that temp write somewhere else.
1684  *
1685  * Note that this doesn't guarantee that the instruction generated
1686  * only reg -- it might be the size=4 destination of a texture instruction.
1687  */
1688 fs_inst *
1689 fs_visitor::get_instruction_generating_reg(fs_inst *start,
1690                                            fs_inst *end,
1691                                            fs_reg reg)
1692 {
1693    if (end == start ||
1694        end->predicated ||
1695        end->force_uncompressed ||
1696        end->force_sechalf ||
1697        !reg.equals(end->dst)) {
1698       return NULL;
1699    } else {
1700       return end;
1701    }
1702 }
1703
1704 bool
1705 fs_visitor::run()
1706 {
1707    uint32_t prog_offset_16 = 0;
1708    uint32_t orig_nr_params = c->prog_data.nr_params;
1709
1710    brw_wm_payload_setup(brw, c);
1711
1712    if (c->dispatch_width == 16) {
1713       /* align to 64 byte boundary. */
1714       while ((c->func.nr_insn * sizeof(struct brw_instruction)) % 64) {
1715          brw_NOP(p);
1716       }
1717
1718       /* Save off the start of this 16-wide program in case we succeed. */
1719       prog_offset_16 = c->func.nr_insn * sizeof(struct brw_instruction);
1720
1721       brw_set_compression_control(p, BRW_COMPRESSION_COMPRESSED);
1722    }
1723
1724    if (0) {
1725       emit_dummy_fs();
1726    } else {
1727       calculate_urb_setup();
1728       if (intel->gen < 6)
1729          emit_interpolation_setup_gen4();
1730       else
1731          emit_interpolation_setup_gen6();
1732
1733       /* Generate FS IR for main().  (the visitor only descends into
1734        * functions called "main").
1735        */
1736       foreach_list(node, &*shader->ir) {
1737          ir_instruction *ir = (ir_instruction *)node;
1738          base_ir = ir;
1739          this->result = reg_undef;
1740          ir->accept(this);
1741       }
1742       if (failed)
1743          return false;
1744
1745       emit_fb_writes();
1746
1747       split_virtual_grfs();
1748
1749       setup_paramvalues_refs();
1750       setup_pull_constants();
1751
1752       bool progress;
1753       do {
1754          progress = false;
1755
1756          progress = remove_duplicate_mrf_writes() || progress;
1757
1758          progress = propagate_constants() || progress;
1759          progress = opt_algebraic() || progress;
1760          progress = opt_cse() || progress;
1761          progress = opt_copy_propagate() || progress;
1762          progress = register_coalesce() || progress;
1763          progress = register_coalesce_2() || progress;
1764          progress = compute_to_mrf() || progress;
1765          progress = dead_code_eliminate() || progress;
1766       } while (progress);
1767
1768       remove_dead_constants();
1769
1770       schedule_instructions();
1771
1772       assign_curb_setup();
1773       assign_urb_setup();
1774
1775       if (0) {
1776          /* Debug of register spilling: Go spill everything. */
1777          int virtual_grf_count = virtual_grf_next;
1778          for (int i = 0; i < virtual_grf_count; i++) {
1779             spill_reg(i);
1780          }
1781       }
1782
1783       if (0)
1784          assign_regs_trivial();
1785       else {
1786          while (!assign_regs()) {
1787             if (failed)
1788                break;
1789          }
1790       }
1791    }
1792    assert(force_uncompressed_stack == 0);
1793    assert(force_sechalf_stack == 0);
1794
1795    if (failed)
1796       return false;
1797
1798    generate_code();
1799
1800    if (c->dispatch_width == 8) {
1801       c->prog_data.reg_blocks = brw_register_blocks(grf_used);
1802    } else {
1803       c->prog_data.reg_blocks_16 = brw_register_blocks(grf_used);
1804       c->prog_data.prog_offset_16 = prog_offset_16;
1805
1806       /* Make sure we didn't try to sneak in an extra uniform */
1807       assert(orig_nr_params == c->prog_data.nr_params);
1808       (void) orig_nr_params;
1809    }
1810
1811    return !failed;
1812 }
1813
1814 bool
1815 brw_wm_fs_emit(struct brw_context *brw, struct brw_wm_compile *c,
1816                struct gl_shader_program *prog)
1817 {
1818    struct intel_context *intel = &brw->intel;
1819
1820    if (!prog)
1821       return false;
1822
1823    struct brw_shader *shader =
1824      (brw_shader *) prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1825    if (!shader)
1826       return false;
1827
1828    if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
1829       printf("GLSL IR for native fragment shader %d:\n", prog->Name);
1830       _mesa_print_ir(shader->ir, NULL);
1831       printf("\n\n");
1832    }
1833
1834    /* Now the main event: Visit the shader IR and generate our FS IR for it.
1835     */
1836    c->dispatch_width = 8;
1837
1838    fs_visitor v(c, prog, shader);
1839    if (!v.run()) {
1840       prog->LinkStatus = false;
1841       ralloc_strcat(&prog->InfoLog, v.fail_msg);
1842
1843       _mesa_problem(NULL, "Failed to compile fragment shader: %s\n",
1844                     v.fail_msg);
1845
1846       return false;
1847    }
1848
1849    if (intel->gen >= 5 && c->prog_data.nr_pull_params == 0) {
1850       c->dispatch_width = 16;
1851       fs_visitor v2(c, prog, shader);
1852       v2.import_uniforms(&v);
1853       v2.run();
1854    }
1855
1856    c->prog_data.dispatch_width = 8;
1857
1858    return true;
1859 }
1860
1861 bool
1862 brw_fs_precompile(struct gl_context *ctx, struct gl_shader_program *prog)
1863 {
1864    struct brw_context *brw = brw_context(ctx);
1865    struct brw_wm_prog_key key;
1866
1867    /* As a temporary measure we assume that all programs use dFdy() (and hence
1868     * need to be compiled differently depending on whether we're rendering to
1869     * an FBO).  FIXME: set this bool correctly based on the contents of the
1870     * program.
1871     */
1872    bool program_uses_dfdy = true;
1873
1874    if (!prog->_LinkedShaders[MESA_SHADER_FRAGMENT])
1875       return true;
1876
1877    struct gl_fragment_program *fp = (struct gl_fragment_program *)
1878       prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program;
1879    struct brw_fragment_program *bfp = brw_fragment_program(fp);
1880
1881    memset(&key, 0, sizeof(key));
1882
1883    if (fp->UsesKill)
1884       key.iz_lookup |= IZ_PS_KILL_ALPHATEST_BIT;
1885
1886    if (fp->Base.OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH))
1887       key.iz_lookup |= IZ_PS_COMPUTES_DEPTH_BIT;
1888
1889    /* Just assume depth testing. */
1890    key.iz_lookup |= IZ_DEPTH_TEST_ENABLE_BIT;
1891    key.iz_lookup |= IZ_DEPTH_WRITE_ENABLE_BIT;
1892
1893    key.vp_outputs_written |= BITFIELD64_BIT(FRAG_ATTRIB_WPOS);
1894    for (int i = 0; i < FRAG_ATTRIB_MAX; i++) {
1895       if (!(fp->Base.InputsRead & BITFIELD64_BIT(i)))
1896          continue;
1897
1898       key.proj_attrib_mask |= 1 << i;
1899
1900       int vp_index = _mesa_vert_result_to_frag_attrib((gl_vert_result) i);
1901
1902       if (vp_index >= 0)
1903          key.vp_outputs_written |= BITFIELD64_BIT(vp_index);
1904    }
1905
1906    key.clamp_fragment_color = true;
1907
1908    for (int i = 0; i < BRW_MAX_TEX_UNIT; i++) {
1909       if (fp->Base.ShadowSamplers & (1 << i))
1910          key.tex.compare_funcs[i] = GL_LESS;
1911
1912       /* FINISHME: depth compares might use (0,0,0,W) for example */
1913       key.tex.swizzles[i] = SWIZZLE_XYZW;
1914    }
1915
1916    if (fp->Base.InputsRead & FRAG_BIT_WPOS) {
1917       key.drawable_height = ctx->DrawBuffer->Height;
1918    }
1919
1920    if ((fp->Base.InputsRead & FRAG_BIT_WPOS) || program_uses_dfdy) {
1921       key.render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
1922    }
1923
1924    key.nr_color_regions = 1;
1925
1926    key.program_string_id = bfp->id;
1927
1928    uint32_t old_prog_offset = brw->wm.prog_offset;
1929    struct brw_wm_prog_data *old_prog_data = brw->wm.prog_data;
1930
1931    bool success = do_wm_prog(brw, prog, bfp, &key);
1932
1933    brw->wm.prog_offset = old_prog_offset;
1934    brw->wm.prog_data = old_prog_data;
1935
1936    return success;
1937 }