OSDN Git Service

glsl: Add image type to the GLSL IR.
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / brw_fs_visitor.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_visitor.cpp
25  *
26  * This file supports generating the FS LIR from the GLSL IR.  The LIR
27  * makes it easier to do backend-specific optimizations than doing so
28  * in the GLSL IR or in the native code.
29  */
30 extern "C" {
31
32 #include <sys/types.h>
33
34 #include "main/macros.h"
35 #include "main/shaderobj.h"
36 #include "program/prog_parameter.h"
37 #include "program/prog_print.h"
38 #include "program/prog_optimize.h"
39 #include "program/register_allocate.h"
40 #include "program/sampler.h"
41 #include "program/hash_table.h"
42 #include "brw_context.h"
43 #include "brw_eu.h"
44 #include "brw_wm.h"
45 }
46 #include "brw_fs.h"
47 #include "main/uniforms.h"
48 #include "glsl/glsl_types.h"
49 #include "glsl/ir_optimization.h"
50
51 void
52 fs_visitor::visit(ir_variable *ir)
53 {
54    fs_reg *reg = NULL;
55
56    if (variable_storage(ir))
57       return;
58
59    if (ir->data.mode == ir_var_shader_in) {
60       if (!strcmp(ir->name, "gl_FragCoord")) {
61          reg = emit_fragcoord_interpolation(ir);
62       } else if (!strcmp(ir->name, "gl_FrontFacing")) {
63          reg = emit_frontfacing_interpolation(ir);
64       } else {
65          reg = emit_general_interpolation(ir);
66       }
67       assert(reg);
68       hash_table_insert(this->variable_ht, reg, ir);
69       return;
70    } else if (ir->data.mode == ir_var_shader_out) {
71       reg = new(this->mem_ctx) fs_reg(this, ir->type);
72
73       if (ir->data.index > 0) {
74          assert(ir->data.location == FRAG_RESULT_DATA0);
75          assert(ir->data.index == 1);
76          this->dual_src_output = *reg;
77       } else if (ir->data.location == FRAG_RESULT_COLOR) {
78          /* Writing gl_FragColor outputs to all color regions. */
79          for (unsigned int i = 0; i < MAX2(c->key.nr_color_regions, 1); i++) {
80             this->outputs[i] = *reg;
81             this->output_components[i] = 4;
82          }
83       } else if (ir->data.location == FRAG_RESULT_DEPTH) {
84          this->frag_depth = *reg;
85       } else if (ir->data.location == FRAG_RESULT_SAMPLE_MASK) {
86          this->sample_mask = *reg;
87       } else {
88          /* gl_FragData or a user-defined FS output */
89          assert(ir->data.location >= FRAG_RESULT_DATA0 &&
90                 ir->data.location < FRAG_RESULT_DATA0 + BRW_MAX_DRAW_BUFFERS);
91
92          int vector_elements =
93             ir->type->is_array() ? ir->type->fields.array->vector_elements
94                                  : ir->type->vector_elements;
95
96          /* General color output. */
97          for (unsigned int i = 0; i < MAX2(1, ir->type->length); i++) {
98             int output = ir->data.location - FRAG_RESULT_DATA0 + i;
99             this->outputs[output] = *reg;
100             this->outputs[output].reg_offset += vector_elements * i;
101             this->output_components[output] = vector_elements;
102          }
103       }
104    } else if (ir->data.mode == ir_var_uniform) {
105       int param_index = c->prog_data.nr_params;
106
107       /* Thanks to the lower_ubo_reference pass, we will see only
108        * ir_binop_ubo_load expressions and not ir_dereference_variable for UBO
109        * variables, so no need for them to be in variable_ht.
110        *
111        * Atomic counters take no uniform storage, no need to do
112        * anything here.
113        */
114       if (ir->is_in_uniform_block() || ir->type->contains_atomic())
115          return;
116
117       if (dispatch_width == 16) {
118          if (!variable_storage(ir)) {
119             fail("Failed to find uniform '%s' in SIMD16\n", ir->name);
120          }
121          return;
122       }
123
124       param_size[param_index] = type_size(ir->type);
125       if (!strncmp(ir->name, "gl_", 3)) {
126          setup_builtin_uniform_values(ir);
127       } else {
128          setup_uniform_values(ir);
129       }
130
131       reg = new(this->mem_ctx) fs_reg(UNIFORM, param_index);
132       reg->type = brw_type_for_base_type(ir->type);
133
134    } else if (ir->data.mode == ir_var_system_value) {
135       if (ir->data.location == SYSTEM_VALUE_SAMPLE_POS) {
136          reg = emit_samplepos_setup(ir);
137       } else if (ir->data.location == SYSTEM_VALUE_SAMPLE_ID) {
138          reg = emit_sampleid_setup(ir);
139       } else if (ir->data.location == SYSTEM_VALUE_SAMPLE_MASK_IN) {
140          reg = emit_samplemaskin_setup(ir);
141       }
142    }
143
144    if (!reg)
145       reg = new(this->mem_ctx) fs_reg(this, ir->type);
146
147    hash_table_insert(this->variable_ht, reg, ir);
148 }
149
150 void
151 fs_visitor::visit(ir_dereference_variable *ir)
152 {
153    fs_reg *reg = variable_storage(ir->var);
154    this->result = *reg;
155 }
156
157 void
158 fs_visitor::visit(ir_dereference_record *ir)
159 {
160    const glsl_type *struct_type = ir->record->type;
161
162    ir->record->accept(this);
163
164    unsigned int offset = 0;
165    for (unsigned int i = 0; i < struct_type->length; i++) {
166       if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
167          break;
168       offset += type_size(struct_type->fields.structure[i].type);
169    }
170    this->result.reg_offset += offset;
171    this->result.type = brw_type_for_base_type(ir->type);
172 }
173
174 void
175 fs_visitor::visit(ir_dereference_array *ir)
176 {
177    ir_constant *constant_index;
178    fs_reg src;
179    int element_size = type_size(ir->type);
180
181    constant_index = ir->array_index->as_constant();
182
183    ir->array->accept(this);
184    src = this->result;
185    src.type = brw_type_for_base_type(ir->type);
186
187    if (constant_index) {
188       assert(src.file == UNIFORM || src.file == GRF);
189       src.reg_offset += constant_index->value.i[0] * element_size;
190    } else {
191       /* Variable index array dereference.  We attach the variable index
192        * component to the reg as a pointer to a register containing the
193        * offset.  Currently only uniform arrays are supported in this patch,
194        * and that reladdr pointer is resolved by
195        * move_uniform_array_access_to_pull_constants().  All other array types
196        * are lowered by lower_variable_index_to_cond_assign().
197        */
198       ir->array_index->accept(this);
199
200       fs_reg index_reg;
201       index_reg = fs_reg(this, glsl_type::int_type);
202       emit(BRW_OPCODE_MUL, index_reg, this->result, fs_reg(element_size));
203
204       if (src.reladdr) {
205          emit(BRW_OPCODE_ADD, index_reg, *src.reladdr, index_reg);
206       }
207
208       src.reladdr = ralloc(mem_ctx, fs_reg);
209       memcpy(src.reladdr, &index_reg, sizeof(index_reg));
210    }
211    this->result = src;
212 }
213
214 void
215 fs_visitor::emit_lrp(fs_reg dst, fs_reg x, fs_reg y, fs_reg a)
216 {
217    if (brw->gen < 6 ||
218        !x.is_valid_3src() ||
219        !y.is_valid_3src() ||
220        !a.is_valid_3src()) {
221       /* We can't use the LRP instruction.  Emit x*(1-a) + y*a. */
222       fs_reg y_times_a           = fs_reg(this, glsl_type::float_type);
223       fs_reg one_minus_a         = fs_reg(this, glsl_type::float_type);
224       fs_reg x_times_one_minus_a = fs_reg(this, glsl_type::float_type);
225
226       emit(MUL(y_times_a, y, a));
227
228       a.negate = !a.negate;
229       emit(ADD(one_minus_a, a, fs_reg(1.0f)));
230       emit(MUL(x_times_one_minus_a, x, one_minus_a));
231
232       emit(ADD(dst, x_times_one_minus_a, y_times_a));
233    } else {
234       /* The LRP instruction actually does op1 * op0 + op2 * (1 - op0), so
235        * we need to reorder the operands.
236        */
237       emit(LRP(dst, a, y, x));
238    }
239 }
240
241 void
242 fs_visitor::emit_minmax(uint32_t conditionalmod, fs_reg dst,
243                         fs_reg src0, fs_reg src1)
244 {
245    fs_inst *inst;
246
247    if (brw->gen >= 6) {
248       inst = emit(BRW_OPCODE_SEL, dst, src0, src1);
249       inst->conditional_mod = conditionalmod;
250    } else {
251       emit(CMP(reg_null_d, src0, src1, conditionalmod));
252
253       inst = emit(BRW_OPCODE_SEL, dst, src0, src1);
254       inst->predicate = BRW_PREDICATE_NORMAL;
255    }
256 }
257
258 /* Instruction selection: Produce a MOV.sat instead of
259  * MIN(MAX(val, 0), 1) when possible.
260  */
261 bool
262 fs_visitor::try_emit_saturate(ir_expression *ir)
263 {
264    ir_rvalue *sat_val = ir->as_rvalue_to_saturate();
265
266    if (!sat_val)
267       return false;
268
269    fs_inst *pre_inst = (fs_inst *) this->instructions.get_tail();
270
271    sat_val->accept(this);
272    fs_reg src = this->result;
273
274    fs_inst *last_inst = (fs_inst *) this->instructions.get_tail();
275
276    /* If the last instruction from our accept() didn't generate our
277     * src, generate a saturated MOV
278     */
279    fs_inst *modify = get_instruction_generating_reg(pre_inst, last_inst, src);
280    if (!modify || modify->regs_written != 1) {
281       this->result = fs_reg(this, ir->type);
282       fs_inst *inst = emit(MOV(this->result, src));
283       inst->saturate = true;
284    } else {
285       modify->saturate = true;
286       this->result = src;
287    }
288
289
290    return true;
291 }
292
293 bool
294 fs_visitor::try_emit_mad(ir_expression *ir, int mul_arg)
295 {
296    /* 3-src instructions were introduced in gen6. */
297    if (brw->gen < 6)
298       return false;
299
300    /* MAD can only handle floating-point data. */
301    if (ir->type != glsl_type::float_type)
302       return false;
303
304    ir_rvalue *nonmul = ir->operands[1 - mul_arg];
305    ir_expression *mul = ir->operands[mul_arg]->as_expression();
306
307    if (!mul || mul->operation != ir_binop_mul)
308       return false;
309
310    if (nonmul->as_constant() ||
311        mul->operands[0]->as_constant() ||
312        mul->operands[1]->as_constant())
313       return false;
314
315    nonmul->accept(this);
316    fs_reg src0 = this->result;
317
318    mul->operands[0]->accept(this);
319    fs_reg src1 = this->result;
320
321    mul->operands[1]->accept(this);
322    fs_reg src2 = this->result;
323
324    this->result = fs_reg(this, ir->type);
325    emit(BRW_OPCODE_MAD, this->result, src0, src1, src2);
326
327    return true;
328 }
329
330 void
331 fs_visitor::visit(ir_expression *ir)
332 {
333    unsigned int operand;
334    fs_reg op[3], temp;
335    fs_inst *inst;
336
337    assert(ir->get_num_operands() <= 3);
338
339    if (try_emit_saturate(ir))
340       return;
341    if (ir->operation == ir_binop_add) {
342       if (try_emit_mad(ir, 0) || try_emit_mad(ir, 1))
343          return;
344    }
345
346    for (operand = 0; operand < ir->get_num_operands(); operand++) {
347       ir->operands[operand]->accept(this);
348       if (this->result.file == BAD_FILE) {
349          fail("Failed to get tree for expression operand:\n");
350          ir->operands[operand]->print();
351          printf("\n");
352       }
353       assert(this->result.is_valid_3src());
354       op[operand] = this->result;
355
356       /* Matrix expression operands should have been broken down to vector
357        * operations already.
358        */
359       assert(!ir->operands[operand]->type->is_matrix());
360       /* And then those vector operands should have been broken down to scalar.
361        */
362       assert(!ir->operands[operand]->type->is_vector());
363    }
364
365    /* Storage for our result.  If our result goes into an assignment, it will
366     * just get copy-propagated out, so no worries.
367     */
368    this->result = fs_reg(this, ir->type);
369
370    switch (ir->operation) {
371    case ir_unop_logic_not:
372       /* Note that BRW_OPCODE_NOT is not appropriate here, since it is
373        * ones complement of the whole register, not just bit 0.
374        */
375       emit(XOR(this->result, op[0], fs_reg(1)));
376       break;
377    case ir_unop_neg:
378       op[0].negate = !op[0].negate;
379       emit(MOV(this->result, op[0]));
380       break;
381    case ir_unop_abs:
382       op[0].abs = true;
383       op[0].negate = false;
384       emit(MOV(this->result, op[0]));
385       break;
386    case ir_unop_sign:
387       if (ir->type->is_float()) {
388          /* AND(val, 0x80000000) gives the sign bit.
389           *
390           * Predicated OR ORs 1.0 (0x3f800000) with the sign bit if val is not
391           * zero.
392           */
393          emit(CMP(reg_null_f, op[0], fs_reg(0.0f), BRW_CONDITIONAL_NZ));
394
395          op[0].type = BRW_REGISTER_TYPE_UD;
396          this->result.type = BRW_REGISTER_TYPE_UD;
397          emit(AND(this->result, op[0], fs_reg(0x80000000u)));
398
399          inst = emit(OR(this->result, this->result, fs_reg(0x3f800000u)));
400          inst->predicate = BRW_PREDICATE_NORMAL;
401
402          this->result.type = BRW_REGISTER_TYPE_F;
403       } else {
404          /*  ASR(val, 31) -> negative val generates 0xffffffff (signed -1).
405           *               -> non-negative val generates 0x00000000.
406           *  Predicated OR sets 1 if val is positive.
407           */
408          emit(CMP(reg_null_d, op[0], fs_reg(0), BRW_CONDITIONAL_G));
409
410          emit(ASR(this->result, op[0], fs_reg(31)));
411
412          inst = emit(OR(this->result, this->result, fs_reg(1)));
413          inst->predicate = BRW_PREDICATE_NORMAL;
414       }
415       break;
416    case ir_unop_rcp:
417       emit_math(SHADER_OPCODE_RCP, this->result, op[0]);
418       break;
419
420    case ir_unop_exp2:
421       emit_math(SHADER_OPCODE_EXP2, this->result, op[0]);
422       break;
423    case ir_unop_log2:
424       emit_math(SHADER_OPCODE_LOG2, this->result, op[0]);
425       break;
426    case ir_unop_exp:
427    case ir_unop_log:
428       assert(!"not reached: should be handled by ir_explog_to_explog2");
429       break;
430    case ir_unop_sin:
431    case ir_unop_sin_reduced:
432       emit_math(SHADER_OPCODE_SIN, this->result, op[0]);
433       break;
434    case ir_unop_cos:
435    case ir_unop_cos_reduced:
436       emit_math(SHADER_OPCODE_COS, this->result, op[0]);
437       break;
438
439    case ir_unop_dFdx:
440       emit(FS_OPCODE_DDX, this->result, op[0]);
441       break;
442    case ir_unop_dFdy:
443       emit(FS_OPCODE_DDY, this->result, op[0]);
444       break;
445
446    case ir_binop_add:
447       emit(ADD(this->result, op[0], op[1]));
448       break;
449    case ir_binop_sub:
450       assert(!"not reached: should be handled by ir_sub_to_add_neg");
451       break;
452
453    case ir_binop_mul:
454       if (brw->gen < 8 && ir->type->is_integer()) {
455          /* For integer multiplication, the MUL uses the low 16 bits
456           * of one of the operands (src0 on gen6, src1 on gen7).  The
457           * MACH accumulates in the contribution of the upper 16 bits
458           * of that operand.
459           *
460           * FINISHME: Emit just the MUL if we know an operand is small
461           * enough.
462           */
463          if (brw->gen >= 7 && dispatch_width == 16)
464             fail("SIMD16 explicit accumulator operands unsupported\n");
465
466          struct brw_reg acc = retype(brw_acc_reg(), this->result.type);
467
468          emit(MUL(acc, op[0], op[1]));
469          emit(MACH(reg_null_d, op[0], op[1]));
470          emit(MOV(this->result, fs_reg(acc)));
471       } else {
472          emit(MUL(this->result, op[0], op[1]));
473       }
474       break;
475    case ir_binop_imul_high: {
476       if (brw->gen >= 7 && dispatch_width == 16)
477          fail("SIMD16 explicit accumulator operands unsupported\n");
478
479       struct brw_reg acc = retype(brw_acc_reg(), this->result.type);
480
481       emit(MUL(acc, op[0], op[1]));
482       emit(MACH(this->result, op[0], op[1]));
483       break;
484    }
485    case ir_binop_div:
486       /* Floating point should be lowered by DIV_TO_MUL_RCP in the compiler. */
487       assert(ir->type->is_integer());
488       emit_math(SHADER_OPCODE_INT_QUOTIENT, this->result, op[0], op[1]);
489       break;
490    case ir_binop_carry: {
491       if (brw->gen >= 7 && dispatch_width == 16)
492          fail("SIMD16 explicit accumulator operands unsupported\n");
493
494       struct brw_reg acc = retype(brw_acc_reg(), BRW_REGISTER_TYPE_UD);
495
496       emit(ADDC(reg_null_ud, op[0], op[1]));
497       emit(MOV(this->result, fs_reg(acc)));
498       break;
499    }
500    case ir_binop_borrow: {
501       if (brw->gen >= 7 && dispatch_width == 16)
502          fail("SIMD16 explicit accumulator operands unsupported\n");
503
504       struct brw_reg acc = retype(brw_acc_reg(), BRW_REGISTER_TYPE_UD);
505
506       emit(SUBB(reg_null_ud, op[0], op[1]));
507       emit(MOV(this->result, fs_reg(acc)));
508       break;
509    }
510    case ir_binop_mod:
511       /* Floating point should be lowered by MOD_TO_FRACT in the compiler. */
512       assert(ir->type->is_integer());
513       emit_math(SHADER_OPCODE_INT_REMAINDER, this->result, op[0], op[1]);
514       break;
515
516    case ir_binop_less:
517    case ir_binop_greater:
518    case ir_binop_lequal:
519    case ir_binop_gequal:
520    case ir_binop_equal:
521    case ir_binop_all_equal:
522    case ir_binop_nequal:
523    case ir_binop_any_nequal:
524       resolve_bool_comparison(ir->operands[0], &op[0]);
525       resolve_bool_comparison(ir->operands[1], &op[1]);
526
527       emit(CMP(this->result, op[0], op[1],
528                brw_conditional_for_comparison(ir->operation)));
529       break;
530
531    case ir_binop_logic_xor:
532       emit(XOR(this->result, op[0], op[1]));
533       break;
534
535    case ir_binop_logic_or:
536       emit(OR(this->result, op[0], op[1]));
537       break;
538
539    case ir_binop_logic_and:
540       emit(AND(this->result, op[0], op[1]));
541       break;
542
543    case ir_binop_dot:
544    case ir_unop_any:
545       assert(!"not reached: should be handled by brw_fs_channel_expressions");
546       break;
547
548    case ir_unop_noise:
549       assert(!"not reached: should be handled by lower_noise");
550       break;
551
552    case ir_quadop_vector:
553       assert(!"not reached: should be handled by lower_quadop_vector");
554       break;
555
556    case ir_binop_vector_extract:
557       assert(!"not reached: should be handled by lower_vec_index_to_cond_assign()");
558       break;
559
560    case ir_triop_vector_insert:
561       assert(!"not reached: should be handled by lower_vector_insert()");
562       break;
563
564    case ir_binop_ldexp:
565       assert(!"not reached: should be handled by ldexp_to_arith()");
566       break;
567
568    case ir_unop_sqrt:
569       emit_math(SHADER_OPCODE_SQRT, this->result, op[0]);
570       break;
571
572    case ir_unop_rsq:
573       emit_math(SHADER_OPCODE_RSQ, this->result, op[0]);
574       break;
575
576    case ir_unop_bitcast_i2f:
577    case ir_unop_bitcast_u2f:
578       op[0].type = BRW_REGISTER_TYPE_F;
579       this->result = op[0];
580       break;
581    case ir_unop_i2u:
582    case ir_unop_bitcast_f2u:
583       op[0].type = BRW_REGISTER_TYPE_UD;
584       this->result = op[0];
585       break;
586    case ir_unop_u2i:
587    case ir_unop_bitcast_f2i:
588       op[0].type = BRW_REGISTER_TYPE_D;
589       this->result = op[0];
590       break;
591    case ir_unop_i2f:
592    case ir_unop_u2f:
593    case ir_unop_f2i:
594    case ir_unop_f2u:
595       emit(MOV(this->result, op[0]));
596       break;
597
598    case ir_unop_b2i:
599       emit(AND(this->result, op[0], fs_reg(1)));
600       break;
601    case ir_unop_b2f:
602       temp = fs_reg(this, glsl_type::int_type);
603       emit(AND(temp, op[0], fs_reg(1)));
604       emit(MOV(this->result, temp));
605       break;
606
607    case ir_unop_f2b:
608       emit(CMP(this->result, op[0], fs_reg(0.0f), BRW_CONDITIONAL_NZ));
609       break;
610    case ir_unop_i2b:
611       emit(CMP(this->result, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
612       break;
613
614    case ir_unop_trunc:
615       emit(RNDZ(this->result, op[0]));
616       break;
617    case ir_unop_ceil:
618       op[0].negate = !op[0].negate;
619       emit(RNDD(this->result, op[0]));
620       this->result.negate = true;
621       break;
622    case ir_unop_floor:
623       emit(RNDD(this->result, op[0]));
624       break;
625    case ir_unop_fract:
626       emit(FRC(this->result, op[0]));
627       break;
628    case ir_unop_round_even:
629       emit(RNDE(this->result, op[0]));
630       break;
631
632    case ir_binop_min:
633    case ir_binop_max:
634       resolve_ud_negate(&op[0]);
635       resolve_ud_negate(&op[1]);
636       emit_minmax(ir->operation == ir_binop_min ?
637                   BRW_CONDITIONAL_L : BRW_CONDITIONAL_GE,
638                   this->result, op[0], op[1]);
639       break;
640    case ir_unop_pack_snorm_2x16:
641    case ir_unop_pack_snorm_4x8:
642    case ir_unop_pack_unorm_2x16:
643    case ir_unop_pack_unorm_4x8:
644    case ir_unop_unpack_snorm_2x16:
645    case ir_unop_unpack_snorm_4x8:
646    case ir_unop_unpack_unorm_2x16:
647    case ir_unop_unpack_unorm_4x8:
648    case ir_unop_unpack_half_2x16:
649    case ir_unop_pack_half_2x16:
650       assert(!"not reached: should be handled by lower_packing_builtins");
651       break;
652    case ir_unop_unpack_half_2x16_split_x:
653       emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X, this->result, op[0]);
654       break;
655    case ir_unop_unpack_half_2x16_split_y:
656       emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y, this->result, op[0]);
657       break;
658    case ir_binop_pow:
659       emit_math(SHADER_OPCODE_POW, this->result, op[0], op[1]);
660       break;
661
662    case ir_unop_bitfield_reverse:
663       emit(BFREV(this->result, op[0]));
664       break;
665    case ir_unop_bit_count:
666       emit(CBIT(this->result, op[0]));
667       break;
668    case ir_unop_find_msb:
669       temp = fs_reg(this, glsl_type::uint_type);
670       emit(FBH(temp, op[0]));
671
672       /* FBH counts from the MSB side, while GLSL's findMSB() wants the count
673        * from the LSB side. If FBH didn't return an error (0xFFFFFFFF), then
674        * subtract the result from 31 to convert the MSB count into an LSB count.
675        */
676
677       /* FBH only supports UD type for dst, so use a MOV to convert UD to D. */
678       emit(MOV(this->result, temp));
679       emit(CMP(reg_null_d, this->result, fs_reg(-1), BRW_CONDITIONAL_NZ));
680
681       temp.negate = true;
682       inst = emit(ADD(this->result, temp, fs_reg(31)));
683       inst->predicate = BRW_PREDICATE_NORMAL;
684       break;
685    case ir_unop_find_lsb:
686       emit(FBL(this->result, op[0]));
687       break;
688    case ir_triop_bitfield_extract:
689       /* Note that the instruction's argument order is reversed from GLSL
690        * and the IR.
691        */
692       emit(BFE(this->result, op[2], op[1], op[0]));
693       break;
694    case ir_binop_bfm:
695       emit(BFI1(this->result, op[0], op[1]));
696       break;
697    case ir_triop_bfi:
698       emit(BFI2(this->result, op[0], op[1], op[2]));
699       break;
700    case ir_quadop_bitfield_insert:
701       assert(!"not reached: should be handled by "
702               "lower_instructions::bitfield_insert_to_bfm_bfi");
703       break;
704
705    case ir_unop_bit_not:
706       emit(NOT(this->result, op[0]));
707       break;
708    case ir_binop_bit_and:
709       emit(AND(this->result, op[0], op[1]));
710       break;
711    case ir_binop_bit_xor:
712       emit(XOR(this->result, op[0], op[1]));
713       break;
714    case ir_binop_bit_or:
715       emit(OR(this->result, op[0], op[1]));
716       break;
717
718    case ir_binop_lshift:
719       emit(SHL(this->result, op[0], op[1]));
720       break;
721
722    case ir_binop_rshift:
723       if (ir->type->base_type == GLSL_TYPE_INT)
724          emit(ASR(this->result, op[0], op[1]));
725       else
726          emit(SHR(this->result, op[0], op[1]));
727       break;
728    case ir_binop_pack_half_2x16_split:
729       emit(FS_OPCODE_PACK_HALF_2x16_SPLIT, this->result, op[0], op[1]);
730       break;
731    case ir_binop_ubo_load: {
732       /* This IR node takes a constant uniform block and a constant or
733        * variable byte offset within the block and loads a vector from that.
734        */
735       ir_constant *uniform_block = ir->operands[0]->as_constant();
736       ir_constant *const_offset = ir->operands[1]->as_constant();
737       fs_reg surf_index = fs_reg(c->prog_data.base.binding_table.ubo_start +
738                                  uniform_block->value.u[0]);
739       if (const_offset) {
740          fs_reg packed_consts = fs_reg(this, glsl_type::float_type);
741          packed_consts.type = result.type;
742
743          fs_reg const_offset_reg = fs_reg(const_offset->value.u[0] & ~15);
744          emit(fs_inst(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
745                       packed_consts, surf_index, const_offset_reg));
746
747          packed_consts.smear = const_offset->value.u[0] % 16 / 4;
748          for (int i = 0; i < ir->type->vector_elements; i++) {
749             /* UBO bools are any nonzero value.  We consider bools to be
750              * values with the low bit set to 1.  Convert them using CMP.
751              */
752             if (ir->type->base_type == GLSL_TYPE_BOOL) {
753                emit(CMP(result, packed_consts, fs_reg(0u), BRW_CONDITIONAL_NZ));
754             } else {
755                emit(MOV(result, packed_consts));
756             }
757
758             packed_consts.smear++;
759             result.reg_offset++;
760
761             /* The std140 packing rules don't allow vectors to cross 16-byte
762              * boundaries, and a reg is 32 bytes.
763              */
764             assert(packed_consts.smear < 8);
765          }
766       } else {
767          /* Turn the byte offset into a dword offset. */
768          fs_reg base_offset = fs_reg(this, glsl_type::int_type);
769          emit(SHR(base_offset, op[1], fs_reg(2)));
770
771          for (int i = 0; i < ir->type->vector_elements; i++) {
772             emit(VARYING_PULL_CONSTANT_LOAD(result, surf_index,
773                                             base_offset, i));
774
775             if (ir->type->base_type == GLSL_TYPE_BOOL)
776                emit(CMP(result, result, fs_reg(0), BRW_CONDITIONAL_NZ));
777
778             result.reg_offset++;
779          }
780       }
781
782       result.reg_offset = 0;
783       break;
784    }
785
786    case ir_triop_fma:
787       /* Note that the instruction's argument order is reversed from GLSL
788        * and the IR.
789        */
790       emit(MAD(this->result, op[2], op[1], op[0]));
791       break;
792
793    case ir_triop_lrp:
794       emit_lrp(this->result, op[0], op[1], op[2]);
795       break;
796
797    case ir_triop_csel:
798       emit(CMP(reg_null_d, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
799       inst = emit(BRW_OPCODE_SEL, this->result, op[1], op[2]);
800       inst->predicate = BRW_PREDICATE_NORMAL;
801       break;
802    }
803 }
804
805 void
806 fs_visitor::emit_assignment_writes(fs_reg &l, fs_reg &r,
807                                    const glsl_type *type, bool predicated)
808 {
809    switch (type->base_type) {
810    case GLSL_TYPE_FLOAT:
811    case GLSL_TYPE_UINT:
812    case GLSL_TYPE_INT:
813    case GLSL_TYPE_BOOL:
814       for (unsigned int i = 0; i < type->components(); i++) {
815          l.type = brw_type_for_base_type(type);
816          r.type = brw_type_for_base_type(type);
817
818          if (predicated || !l.equals(r)) {
819             fs_inst *inst = emit(MOV(l, r));
820             inst->predicate = predicated ? BRW_PREDICATE_NORMAL : BRW_PREDICATE_NONE;
821          }
822
823          l.reg_offset++;
824          r.reg_offset++;
825       }
826       break;
827    case GLSL_TYPE_ARRAY:
828       for (unsigned int i = 0; i < type->length; i++) {
829          emit_assignment_writes(l, r, type->fields.array, predicated);
830       }
831       break;
832
833    case GLSL_TYPE_STRUCT:
834       for (unsigned int i = 0; i < type->length; i++) {
835          emit_assignment_writes(l, r, type->fields.structure[i].type,
836                                 predicated);
837       }
838       break;
839
840    case GLSL_TYPE_SAMPLER:
841    case GLSL_TYPE_IMAGE:
842    case GLSL_TYPE_ATOMIC_UINT:
843       break;
844
845    case GLSL_TYPE_VOID:
846    case GLSL_TYPE_ERROR:
847    case GLSL_TYPE_INTERFACE:
848       assert(!"not reached");
849       break;
850    }
851 }
852
853 /* If the RHS processing resulted in an instruction generating a
854  * temporary value, and it would be easy to rewrite the instruction to
855  * generate its result right into the LHS instead, do so.  This ends
856  * up reliably removing instructions where it can be tricky to do so
857  * later without real UD chain information.
858  */
859 bool
860 fs_visitor::try_rewrite_rhs_to_dst(ir_assignment *ir,
861                                    fs_reg dst,
862                                    fs_reg src,
863                                    fs_inst *pre_rhs_inst,
864                                    fs_inst *last_rhs_inst)
865 {
866    /* Only attempt if we're doing a direct assignment. */
867    if (ir->condition ||
868        !(ir->lhs->type->is_scalar() ||
869         (ir->lhs->type->is_vector() &&
870          ir->write_mask == (1 << ir->lhs->type->vector_elements) - 1)))
871       return false;
872
873    /* Make sure the last instruction generated our source reg. */
874    fs_inst *modify = get_instruction_generating_reg(pre_rhs_inst,
875                                                     last_rhs_inst,
876                                                     src);
877    if (!modify)
878       return false;
879
880    /* If last_rhs_inst wrote a different number of components than our LHS,
881     * we can't safely rewrite it.
882     */
883    if (virtual_grf_sizes[dst.reg] != modify->regs_written)
884       return false;
885
886    /* Success!  Rewrite the instruction. */
887    modify->dst = dst;
888
889    return true;
890 }
891
892 void
893 fs_visitor::visit(ir_assignment *ir)
894 {
895    fs_reg l, r;
896    fs_inst *inst;
897
898    /* FINISHME: arrays on the lhs */
899    ir->lhs->accept(this);
900    l = this->result;
901
902    fs_inst *pre_rhs_inst = (fs_inst *) this->instructions.get_tail();
903
904    ir->rhs->accept(this);
905    r = this->result;
906
907    fs_inst *last_rhs_inst = (fs_inst *) this->instructions.get_tail();
908
909    assert(l.file != BAD_FILE);
910    assert(r.file != BAD_FILE);
911
912    if (try_rewrite_rhs_to_dst(ir, l, r, pre_rhs_inst, last_rhs_inst))
913       return;
914
915    if (ir->condition) {
916       emit_bool_to_cond_code(ir->condition);
917    }
918
919    if (ir->lhs->type->is_scalar() ||
920        ir->lhs->type->is_vector()) {
921       for (int i = 0; i < ir->lhs->type->vector_elements; i++) {
922          if (ir->write_mask & (1 << i)) {
923             inst = emit(MOV(l, r));
924             if (ir->condition)
925                inst->predicate = BRW_PREDICATE_NORMAL;
926             r.reg_offset++;
927          }
928          l.reg_offset++;
929       }
930    } else {
931       emit_assignment_writes(l, r, ir->lhs->type, ir->condition != NULL);
932    }
933 }
934
935 fs_inst *
936 fs_visitor::emit_texture_gen4(ir_texture *ir, fs_reg dst, fs_reg coordinate,
937                               fs_reg shadow_c, fs_reg lod, fs_reg dPdy)
938 {
939    int mlen;
940    int base_mrf = 1;
941    bool simd16 = false;
942    fs_reg orig_dst;
943
944    /* g0 header. */
945    mlen = 1;
946
947    if (ir->shadow_comparitor) {
948       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
949          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
950          coordinate.reg_offset++;
951       }
952
953       /* gen4's SIMD8 sampler always has the slots for u,v,r present.
954        * the unused slots must be zeroed.
955        */
956       for (int i = ir->coordinate->type->vector_elements; i < 3; i++) {
957          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), fs_reg(0.0f)));
958       }
959       mlen += 3;
960
961       if (ir->op == ir_tex) {
962          /* There's no plain shadow compare message, so we use shadow
963           * compare with a bias of 0.0.
964           */
965          emit(MOV(fs_reg(MRF, base_mrf + mlen), fs_reg(0.0f)));
966          mlen++;
967       } else if (ir->op == ir_txb || ir->op == ir_txl) {
968          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
969          mlen++;
970       } else {
971          assert(!"Should not get here.");
972       }
973
974       emit(MOV(fs_reg(MRF, base_mrf + mlen), shadow_c));
975       mlen++;
976    } else if (ir->op == ir_tex) {
977       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
978          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
979          coordinate.reg_offset++;
980       }
981       /* zero the others. */
982       for (int i = ir->coordinate->type->vector_elements; i<3; i++) {
983          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), fs_reg(0.0f)));
984       }
985       /* gen4's SIMD8 sampler always has the slots for u,v,r present. */
986       mlen += 3;
987    } else if (ir->op == ir_txd) {
988       fs_reg &dPdx = lod;
989
990       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
991          emit(MOV(fs_reg(MRF, base_mrf + mlen + i), coordinate));
992          coordinate.reg_offset++;
993       }
994       /* the slots for u and v are always present, but r is optional */
995       mlen += MAX2(ir->coordinate->type->vector_elements, 2);
996
997       /*  P   = u, v, r
998        * dPdx = dudx, dvdx, drdx
999        * dPdy = dudy, dvdy, drdy
1000        *
1001        * 1-arg: Does not exist.
1002        *
1003        * 2-arg: dudx   dvdx   dudy   dvdy
1004        *        dPdx.x dPdx.y dPdy.x dPdy.y
1005        *        m4     m5     m6     m7
1006        *
1007        * 3-arg: dudx   dvdx   drdx   dudy   dvdy   drdy
1008        *        dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
1009        *        m5     m6     m7     m8     m9     m10
1010        */
1011       for (int i = 0; i < ir->lod_info.grad.dPdx->type->vector_elements; i++) {
1012          emit(MOV(fs_reg(MRF, base_mrf + mlen), dPdx));
1013          dPdx.reg_offset++;
1014       }
1015       mlen += MAX2(ir->lod_info.grad.dPdx->type->vector_elements, 2);
1016
1017       for (int i = 0; i < ir->lod_info.grad.dPdy->type->vector_elements; i++) {
1018          emit(MOV(fs_reg(MRF, base_mrf + mlen), dPdy));
1019          dPdy.reg_offset++;
1020       }
1021       mlen += MAX2(ir->lod_info.grad.dPdy->type->vector_elements, 2);
1022    } else if (ir->op == ir_txs) {
1023       /* There's no SIMD8 resinfo message on Gen4.  Use SIMD16 instead. */
1024       simd16 = true;
1025       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), lod));
1026       mlen += 2;
1027    } else {
1028       /* Oh joy.  gen4 doesn't have SIMD8 non-shadow-compare bias/lod
1029        * instructions.  We'll need to do SIMD16 here.
1030        */
1031       simd16 = true;
1032       assert(ir->op == ir_txb || ir->op == ir_txl || ir->op == ir_txf);
1033
1034       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1035          emit(MOV(fs_reg(MRF, base_mrf + mlen + i * 2, coordinate.type),
1036                   coordinate));
1037          coordinate.reg_offset++;
1038       }
1039
1040       /* Initialize the rest of u/v/r with 0.0.  Empirically, this seems to
1041        * be necessary for TXF (ld), but seems wise to do for all messages.
1042        */
1043       for (int i = ir->coordinate->type->vector_elements; i < 3; i++) {
1044          emit(MOV(fs_reg(MRF, base_mrf + mlen + i * 2), fs_reg(0.0f)));
1045       }
1046
1047       /* lod/bias appears after u/v/r. */
1048       mlen += 6;
1049
1050       emit(MOV(fs_reg(MRF, base_mrf + mlen, lod.type), lod));
1051       mlen++;
1052
1053       /* The unused upper half. */
1054       mlen++;
1055    }
1056
1057    if (simd16) {
1058       /* Now, since we're doing simd16, the return is 2 interleaved
1059        * vec4s where the odd-indexed ones are junk. We'll need to move
1060        * this weirdness around to the expected layout.
1061        */
1062       orig_dst = dst;
1063       dst = fs_reg(GRF, virtual_grf_alloc(8),
1064                    (brw->is_g4x ?
1065                     brw_type_for_base_type(ir->type) :
1066                     BRW_REGISTER_TYPE_F));
1067    }
1068
1069    fs_inst *inst = NULL;
1070    switch (ir->op) {
1071    case ir_tex:
1072       inst = emit(SHADER_OPCODE_TEX, dst);
1073       break;
1074    case ir_txb:
1075       inst = emit(FS_OPCODE_TXB, dst);
1076       break;
1077    case ir_txl:
1078       inst = emit(SHADER_OPCODE_TXL, dst);
1079       break;
1080    case ir_txd:
1081       inst = emit(SHADER_OPCODE_TXD, dst);
1082       break;
1083    case ir_txs:
1084       inst = emit(SHADER_OPCODE_TXS, dst);
1085       break;
1086    case ir_txf:
1087       inst = emit(SHADER_OPCODE_TXF, dst);
1088       break;
1089    default:
1090       fail("unrecognized texture opcode");
1091    }
1092    inst->base_mrf = base_mrf;
1093    inst->mlen = mlen;
1094    inst->header_present = true;
1095    inst->regs_written = simd16 ? 8 : 4;
1096
1097    if (simd16) {
1098       for (int i = 0; i < 4; i++) {
1099          emit(MOV(orig_dst, dst));
1100          orig_dst.reg_offset++;
1101          dst.reg_offset += 2;
1102       }
1103    }
1104
1105    return inst;
1106 }
1107
1108 /* gen5's sampler has slots for u, v, r, array index, then optional
1109  * parameters like shadow comparitor or LOD bias.  If optional
1110  * parameters aren't present, those base slots are optional and don't
1111  * need to be included in the message.
1112  *
1113  * We don't fill in the unnecessary slots regardless, which may look
1114  * surprising in the disassembly.
1115  */
1116 fs_inst *
1117 fs_visitor::emit_texture_gen5(ir_texture *ir, fs_reg dst, fs_reg coordinate,
1118                               fs_reg shadow_c, fs_reg lod, fs_reg lod2,
1119                               fs_reg sample_index)
1120 {
1121    int mlen = 0;
1122    int base_mrf = 2;
1123    int reg_width = dispatch_width / 8;
1124    bool header_present = false;
1125    const int vector_elements =
1126       ir->coordinate ? ir->coordinate->type->vector_elements : 0;
1127
1128    if (ir->offset) {
1129       /* The offsets set up by the ir_texture visitor are in the
1130        * m1 header, so we can't go headerless.
1131        */
1132       header_present = true;
1133       mlen++;
1134       base_mrf--;
1135    }
1136
1137    for (int i = 0; i < vector_elements; i++) {
1138       emit(MOV(fs_reg(MRF, base_mrf + mlen + i * reg_width, coordinate.type),
1139                coordinate));
1140       coordinate.reg_offset++;
1141    }
1142    mlen += vector_elements * reg_width;
1143
1144    if (ir->shadow_comparitor) {
1145       mlen = MAX2(mlen, header_present + 4 * reg_width);
1146
1147       emit(MOV(fs_reg(MRF, base_mrf + mlen), shadow_c));
1148       mlen += reg_width;
1149    }
1150
1151    fs_inst *inst = NULL;
1152    switch (ir->op) {
1153    case ir_tex:
1154       inst = emit(SHADER_OPCODE_TEX, dst);
1155       break;
1156    case ir_txb:
1157       mlen = MAX2(mlen, header_present + 4 * reg_width);
1158       emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1159       mlen += reg_width;
1160
1161       inst = emit(FS_OPCODE_TXB, dst);
1162       break;
1163    case ir_txl:
1164       mlen = MAX2(mlen, header_present + 4 * reg_width);
1165       emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1166       mlen += reg_width;
1167
1168       inst = emit(SHADER_OPCODE_TXL, dst);
1169       break;
1170    case ir_txd: {
1171       mlen = MAX2(mlen, header_present + 4 * reg_width); /* skip over 'ai' */
1172
1173       /**
1174        *  P   =  u,    v,    r
1175        * dPdx = dudx, dvdx, drdx
1176        * dPdy = dudy, dvdy, drdy
1177        *
1178        * Load up these values:
1179        * - dudx   dudy   dvdx   dvdy   drdx   drdy
1180        * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
1181        */
1182       for (int i = 0; i < ir->lod_info.grad.dPdx->type->vector_elements; i++) {
1183          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod));
1184          lod.reg_offset++;
1185          mlen += reg_width;
1186
1187          emit(MOV(fs_reg(MRF, base_mrf + mlen), lod2));
1188          lod2.reg_offset++;
1189          mlen += reg_width;
1190       }
1191
1192       inst = emit(SHADER_OPCODE_TXD, dst);
1193       break;
1194    }
1195    case ir_txs:
1196       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), lod));
1197       mlen += reg_width;
1198       inst = emit(SHADER_OPCODE_TXS, dst);
1199       break;
1200    case ir_query_levels:
1201       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), fs_reg(0u)));
1202       mlen += reg_width;
1203       inst = emit(SHADER_OPCODE_TXS, dst);
1204       break;
1205    case ir_txf:
1206       mlen = header_present + 4 * reg_width;
1207       emit(MOV(fs_reg(MRF, base_mrf + mlen - reg_width, BRW_REGISTER_TYPE_UD), lod));
1208       inst = emit(SHADER_OPCODE_TXF, dst);
1209       break;
1210    case ir_txf_ms:
1211       mlen = header_present + 4 * reg_width;
1212
1213       /* lod */
1214       emit(MOV(fs_reg(MRF, base_mrf + mlen - reg_width, BRW_REGISTER_TYPE_UD), fs_reg(0)));
1215       /* sample index */
1216       emit(MOV(fs_reg(MRF, base_mrf + mlen, BRW_REGISTER_TYPE_UD), sample_index));
1217       mlen += reg_width;
1218       inst = emit(SHADER_OPCODE_TXF_CMS, dst);
1219       break;
1220    case ir_lod:
1221       inst = emit(SHADER_OPCODE_LOD, dst);
1222       break;
1223    case ir_tg4:
1224       inst = emit(SHADER_OPCODE_TG4, dst);
1225       break;
1226    default:
1227       fail("unrecognized texture opcode");
1228       break;
1229    }
1230    inst->base_mrf = base_mrf;
1231    inst->mlen = mlen;
1232    inst->header_present = header_present;
1233    inst->regs_written = 4;
1234
1235    if (mlen > MAX_SAMPLER_MESSAGE_SIZE) {
1236       fail("Message length >" STRINGIFY(MAX_SAMPLER_MESSAGE_SIZE)
1237            " disallowed by hardware\n");
1238    }
1239
1240    return inst;
1241 }
1242
1243 fs_inst *
1244 fs_visitor::emit_texture_gen7(ir_texture *ir, fs_reg dst, fs_reg coordinate,
1245                               fs_reg shadow_c, fs_reg lod, fs_reg lod2,
1246                               fs_reg sample_index, fs_reg mcs, int sampler)
1247 {
1248    int reg_width = dispatch_width / 8;
1249    bool header_present = false;
1250
1251    fs_reg payload = fs_reg(this, glsl_type::float_type);
1252    fs_reg next = payload;
1253
1254    if (ir->op == ir_tg4 || (ir->offset && ir->op != ir_txf) || sampler >= 16) {
1255       /* For general texture offsets (no txf workaround), we need a header to
1256        * put them in.  Note that for SIMD16 we're making space for two actual
1257        * hardware registers here, so the emit will have to fix up for this.
1258        *
1259        * * ir4_tg4 needs to place its channel select in the header,
1260        * for interaction with ARB_texture_swizzle
1261        *
1262        * The sampler index is only 4-bits, so for larger sampler numbers we
1263        * need to offset the Sampler State Pointer in the header.
1264        */
1265       header_present = true;
1266       next.reg_offset++;
1267    }
1268
1269    if (ir->shadow_comparitor) {
1270       emit(MOV(next, shadow_c));
1271       next.reg_offset++;
1272    }
1273
1274    bool has_nonconstant_offset = ir->offset && !ir->offset->as_constant();
1275    bool coordinate_done = false;
1276
1277    /* Set up the LOD info */
1278    switch (ir->op) {
1279    case ir_tex:
1280    case ir_lod:
1281       break;
1282    case ir_txb:
1283       emit(MOV(next, lod));
1284       next.reg_offset++;
1285       break;
1286    case ir_txl:
1287       emit(MOV(next, lod));
1288       next.reg_offset++;
1289       break;
1290    case ir_txd: {
1291       if (dispatch_width == 16)
1292          fail("Gen7 does not support sample_d/sample_d_c in SIMD16 mode.");
1293
1294       /* Load dPdx and the coordinate together:
1295        * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
1296        */
1297       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1298          emit(MOV(next, coordinate));
1299          coordinate.reg_offset++;
1300          next.reg_offset++;
1301
1302          /* For cube map array, the coordinate is (u,v,r,ai) but there are
1303           * only derivatives for (u, v, r).
1304           */
1305          if (i < ir->lod_info.grad.dPdx->type->vector_elements) {
1306             emit(MOV(next, lod));
1307             lod.reg_offset++;
1308             next.reg_offset++;
1309
1310             emit(MOV(next, lod2));
1311             lod2.reg_offset++;
1312             next.reg_offset++;
1313          }
1314       }
1315
1316       coordinate_done = true;
1317       break;
1318    }
1319    case ir_txs:
1320       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), lod));
1321       next.reg_offset++;
1322       break;
1323    case ir_query_levels:
1324       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), fs_reg(0u)));
1325       next.reg_offset++;
1326       break;
1327    case ir_txf:
1328       /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r. */
1329       emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1330       coordinate.reg_offset++;
1331       next.reg_offset++;
1332
1333       emit(MOV(next.retype(BRW_REGISTER_TYPE_D), lod));
1334       next.reg_offset++;
1335
1336       for (int i = 1; i < ir->coordinate->type->vector_elements; i++) {
1337          emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1338          coordinate.reg_offset++;
1339          next.reg_offset++;
1340       }
1341
1342       coordinate_done = true;
1343       break;
1344    case ir_txf_ms:
1345       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), sample_index));
1346       next.reg_offset++;
1347
1348       /* data from the multisample control surface */
1349       emit(MOV(next.retype(BRW_REGISTER_TYPE_UD), mcs));
1350       next.reg_offset++;
1351
1352       /* there is no offsetting for this message; just copy in the integer
1353        * texture coordinates
1354        */
1355       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1356          emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1357          coordinate.reg_offset++;
1358          next.reg_offset++;
1359       }
1360
1361       coordinate_done = true;
1362       break;
1363    case ir_tg4:
1364       if (has_nonconstant_offset) {
1365          if (ir->shadow_comparitor && dispatch_width == 16)
1366             fail("Gen7 does not support gather4_po_c in SIMD16 mode.");
1367
1368          /* More crazy intermixing */
1369          ir->offset->accept(this);
1370          fs_reg offset_value = this->result;
1371
1372          for (int i = 0; i < 2; i++) { /* u, v */
1373             emit(MOV(next, coordinate));
1374             coordinate.reg_offset++;
1375             next.reg_offset++;
1376          }
1377
1378          for (int i = 0; i < 2; i++) { /* offu, offv */
1379             emit(MOV(next.retype(BRW_REGISTER_TYPE_D), offset_value));
1380             offset_value.reg_offset++;
1381             next.reg_offset++;
1382          }
1383
1384          if (ir->coordinate->type->vector_elements == 3) { /* r if present */
1385             emit(MOV(next, coordinate));
1386             coordinate.reg_offset++;
1387             next.reg_offset++;
1388          }
1389
1390          coordinate_done = true;
1391       }
1392       break;
1393    }
1394
1395    /* Set up the coordinate (except for cases where it was done above) */
1396    if (ir->coordinate && !coordinate_done) {
1397       for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1398          emit(MOV(next, coordinate));
1399          coordinate.reg_offset++;
1400          next.reg_offset++;
1401       }
1402    }
1403
1404    /* Generate the SEND */
1405    fs_inst *inst = NULL;
1406    switch (ir->op) {
1407    case ir_tex: inst = emit(SHADER_OPCODE_TEX, dst, payload); break;
1408    case ir_txb: inst = emit(FS_OPCODE_TXB, dst, payload); break;
1409    case ir_txl: inst = emit(SHADER_OPCODE_TXL, dst, payload); break;
1410    case ir_txd: inst = emit(SHADER_OPCODE_TXD, dst, payload); break;
1411    case ir_txf: inst = emit(SHADER_OPCODE_TXF, dst, payload); break;
1412    case ir_txf_ms: inst = emit(SHADER_OPCODE_TXF_CMS, dst, payload); break;
1413    case ir_txs: inst = emit(SHADER_OPCODE_TXS, dst, payload); break;
1414    case ir_query_levels: inst = emit(SHADER_OPCODE_TXS, dst, payload); break;
1415    case ir_lod: inst = emit(SHADER_OPCODE_LOD, dst, payload); break;
1416    case ir_tg4:
1417       if (has_nonconstant_offset)
1418          inst = emit(SHADER_OPCODE_TG4_OFFSET, dst, payload);
1419       else
1420          inst = emit(SHADER_OPCODE_TG4, dst, payload);
1421       break;
1422    }
1423    inst->base_mrf = -1;
1424    if (reg_width == 2)
1425       inst->mlen = next.reg_offset * reg_width - header_present;
1426    else
1427       inst->mlen = next.reg_offset * reg_width;
1428    inst->header_present = header_present;
1429    inst->regs_written = 4;
1430
1431    virtual_grf_sizes[payload.reg] = next.reg_offset;
1432    if (inst->mlen > MAX_SAMPLER_MESSAGE_SIZE) {
1433       fail("Message length >" STRINGIFY(MAX_SAMPLER_MESSAGE_SIZE)
1434            " disallowed by hardware\n");
1435    }
1436
1437    return inst;
1438 }
1439
1440 fs_reg
1441 fs_visitor::rescale_texcoord(ir_texture *ir, fs_reg coordinate,
1442                              bool is_rect, int sampler, int texunit)
1443 {
1444    fs_inst *inst = NULL;
1445    bool needs_gl_clamp = true;
1446    fs_reg scale_x, scale_y;
1447
1448    /* The 965 requires the EU to do the normalization of GL rectangle
1449     * texture coordinates.  We use the program parameter state
1450     * tracking to get the scaling factor.
1451     */
1452    if (is_rect &&
1453        (brw->gen < 6 ||
1454         (brw->gen >= 6 && (c->key.tex.gl_clamp_mask[0] & (1 << sampler) ||
1455                              c->key.tex.gl_clamp_mask[1] & (1 << sampler))))) {
1456       struct gl_program_parameter_list *params = prog->Parameters;
1457       int tokens[STATE_LENGTH] = {
1458          STATE_INTERNAL,
1459          STATE_TEXRECT_SCALE,
1460          texunit,
1461          0,
1462          0
1463       };
1464
1465       if (dispatch_width == 16) {
1466          fail("rectangle scale uniform setup not supported on SIMD16\n");
1467          return coordinate;
1468       }
1469
1470       scale_x = fs_reg(UNIFORM, c->prog_data.nr_params);
1471       scale_y = fs_reg(UNIFORM, c->prog_data.nr_params + 1);
1472
1473       GLuint index = _mesa_add_state_reference(params,
1474                                                (gl_state_index *)tokens);
1475       c->prog_data.param[c->prog_data.nr_params++] =
1476          &prog->Parameters->ParameterValues[index][0].f;
1477       c->prog_data.param[c->prog_data.nr_params++] =
1478          &prog->Parameters->ParameterValues[index][1].f;
1479    }
1480
1481    /* The 965 requires the EU to do the normalization of GL rectangle
1482     * texture coordinates.  We use the program parameter state
1483     * tracking to get the scaling factor.
1484     */
1485    if (brw->gen < 6 && is_rect) {
1486       fs_reg dst = fs_reg(this, ir->coordinate->type);
1487       fs_reg src = coordinate;
1488       coordinate = dst;
1489
1490       emit(MUL(dst, src, scale_x));
1491       dst.reg_offset++;
1492       src.reg_offset++;
1493       emit(MUL(dst, src, scale_y));
1494    } else if (is_rect) {
1495       /* On gen6+, the sampler handles the rectangle coordinates
1496        * natively, without needing rescaling.  But that means we have
1497        * to do GL_CLAMP clamping at the [0, width], [0, height] scale,
1498        * not [0, 1] like the default case below.
1499        */
1500       needs_gl_clamp = false;
1501
1502       for (int i = 0; i < 2; i++) {
1503          if (c->key.tex.gl_clamp_mask[i] & (1 << sampler)) {
1504             fs_reg chan = coordinate;
1505             chan.reg_offset += i;
1506
1507             inst = emit(BRW_OPCODE_SEL, chan, chan, brw_imm_f(0.0));
1508             inst->conditional_mod = BRW_CONDITIONAL_G;
1509
1510             /* Our parameter comes in as 1.0/width or 1.0/height,
1511              * because that's what people normally want for doing
1512              * texture rectangle handling.  We need width or height
1513              * for clamping, but we don't care enough to make a new
1514              * parameter type, so just invert back.
1515              */
1516             fs_reg limit = fs_reg(this, glsl_type::float_type);
1517             emit(MOV(limit, i == 0 ? scale_x : scale_y));
1518             emit(SHADER_OPCODE_RCP, limit, limit);
1519
1520             inst = emit(BRW_OPCODE_SEL, chan, chan, limit);
1521             inst->conditional_mod = BRW_CONDITIONAL_L;
1522          }
1523       }
1524    }
1525
1526    if (ir->coordinate && needs_gl_clamp) {
1527       for (unsigned int i = 0;
1528            i < MIN2(ir->coordinate->type->vector_elements, 3); i++) {
1529          if (c->key.tex.gl_clamp_mask[i] & (1 << sampler)) {
1530             fs_reg chan = coordinate;
1531             chan.reg_offset += i;
1532
1533             fs_inst *inst = emit(MOV(chan, chan));
1534             inst->saturate = true;
1535          }
1536       }
1537    }
1538    return coordinate;
1539 }
1540
1541 /* Sample from the MCS surface attached to this multisample texture. */
1542 fs_reg
1543 fs_visitor::emit_mcs_fetch(ir_texture *ir, fs_reg coordinate, int sampler)
1544 {
1545    int reg_width = dispatch_width / 8;
1546    fs_reg payload = fs_reg(this, glsl_type::float_type);
1547    fs_reg dest = fs_reg(this, glsl_type::uvec4_type);
1548    fs_reg next = payload;
1549
1550    /* parameters are: u, v, r, lod; missing parameters are treated as zero */
1551    for (int i = 0; i < ir->coordinate->type->vector_elements; i++) {
1552       emit(MOV(next.retype(BRW_REGISTER_TYPE_D), coordinate));
1553       coordinate.reg_offset++;
1554       next.reg_offset++;
1555    }
1556
1557    fs_inst *inst = emit(SHADER_OPCODE_TXF_MCS, dest, payload);
1558    virtual_grf_sizes[payload.reg] = next.reg_offset;
1559    inst->base_mrf = -1;
1560    inst->mlen = next.reg_offset * reg_width;
1561    inst->header_present = false;
1562    inst->regs_written = 4 * reg_width; /* we only care about one reg of response,
1563                                         * but the sampler always writes 4/8
1564                                         */
1565    inst->sampler = sampler;
1566
1567    return dest;
1568 }
1569
1570 void
1571 fs_visitor::visit(ir_texture *ir)
1572 {
1573    fs_inst *inst = NULL;
1574
1575    int sampler =
1576       _mesa_get_sampler_uniform_value(ir->sampler, shader_prog, prog);
1577    /* FINISHME: We're failing to recompile our programs when the sampler is
1578     * updated.  This only matters for the texture rectangle scale parameters
1579     * (pre-gen6, or gen6+ with GL_CLAMP).
1580     */
1581    int texunit = prog->SamplerUnits[sampler];
1582
1583    if (ir->op == ir_tg4) {
1584       /* When tg4 is used with the degenerate ZERO/ONE swizzles, don't bother
1585        * emitting anything other than setting up the constant result.
1586        */
1587       ir_constant *chan = ir->lod_info.component->as_constant();
1588       int swiz = GET_SWZ(c->key.tex.swizzles[sampler], chan->value.i[0]);
1589       if (swiz == SWIZZLE_ZERO || swiz == SWIZZLE_ONE) {
1590
1591          fs_reg res = fs_reg(this, glsl_type::vec4_type);
1592          this->result = res;
1593
1594          for (int i=0; i<4; i++) {
1595             emit(MOV(res, fs_reg(swiz == SWIZZLE_ZERO ? 0.0f : 1.0f)));
1596             res.reg_offset++;
1597          }
1598          return;
1599       }
1600    }
1601
1602    /* Should be lowered by do_lower_texture_projection */
1603    assert(!ir->projector);
1604
1605    /* Should be lowered */
1606    assert(!ir->offset || !ir->offset->type->is_array());
1607
1608    /* Generate code to compute all the subexpression trees.  This has to be
1609     * done before loading any values into MRFs for the sampler message since
1610     * generating these values may involve SEND messages that need the MRFs.
1611     */
1612    fs_reg coordinate;
1613    if (ir->coordinate) {
1614       ir->coordinate->accept(this);
1615
1616       coordinate = rescale_texcoord(ir, this->result,
1617                                     ir->sampler->type->sampler_dimensionality ==
1618                                     GLSL_SAMPLER_DIM_RECT,
1619                                     sampler, texunit);
1620    }
1621
1622    fs_reg shadow_comparitor;
1623    if (ir->shadow_comparitor) {
1624       ir->shadow_comparitor->accept(this);
1625       shadow_comparitor = this->result;
1626    }
1627
1628    fs_reg lod, lod2, sample_index, mcs;
1629    switch (ir->op) {
1630    case ir_tex:
1631    case ir_lod:
1632    case ir_tg4:
1633    case ir_query_levels:
1634       break;
1635    case ir_txb:
1636       ir->lod_info.bias->accept(this);
1637       lod = this->result;
1638       break;
1639    case ir_txd:
1640       ir->lod_info.grad.dPdx->accept(this);
1641       lod = this->result;
1642
1643       ir->lod_info.grad.dPdy->accept(this);
1644       lod2 = this->result;
1645       break;
1646    case ir_txf:
1647    case ir_txl:
1648    case ir_txs:
1649       ir->lod_info.lod->accept(this);
1650       lod = this->result;
1651       break;
1652    case ir_txf_ms:
1653       ir->lod_info.sample_index->accept(this);
1654       sample_index = this->result;
1655
1656       if (brw->gen >= 7 && c->key.tex.compressed_multisample_layout_mask & (1<<sampler))
1657          mcs = emit_mcs_fetch(ir, coordinate, sampler);
1658       else
1659          mcs = fs_reg(0u);
1660       break;
1661    default:
1662       assert(!"Unrecognized texture opcode");
1663    };
1664
1665    /* Writemasking doesn't eliminate channels on SIMD8 texture
1666     * samples, so don't worry about them.
1667     */
1668    fs_reg dst = fs_reg(this, glsl_type::get_instance(ir->type->base_type, 4, 1));
1669
1670    if (brw->gen >= 7) {
1671       inst = emit_texture_gen7(ir, dst, coordinate, shadow_comparitor,
1672                                lod, lod2, sample_index, mcs, sampler);
1673    } else if (brw->gen >= 5) {
1674       inst = emit_texture_gen5(ir, dst, coordinate, shadow_comparitor,
1675                                lod, lod2, sample_index);
1676    } else {
1677       inst = emit_texture_gen4(ir, dst, coordinate, shadow_comparitor,
1678                                lod, lod2);
1679    }
1680
1681    if (ir->offset != NULL && ir->op != ir_txf)
1682       inst->texture_offset = brw_texture_offset(ctx, ir->offset->as_constant());
1683
1684    if (ir->op == ir_tg4)
1685       inst->texture_offset |= gather_channel(ir, sampler) << 16; // M0.2:16-17
1686
1687    inst->sampler = sampler;
1688
1689    if (ir->shadow_comparitor)
1690       inst->shadow_compare = true;
1691
1692    /* fixup #layers for cube map arrays */
1693    if (ir->op == ir_txs) {
1694       glsl_type const *type = ir->sampler->type;
1695       if (type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
1696           type->sampler_array) {
1697          fs_reg depth = dst;
1698          depth.reg_offset = 2;
1699          emit_math(SHADER_OPCODE_INT_QUOTIENT, depth, depth, fs_reg(6));
1700       }
1701    }
1702
1703    if (brw->gen == 6 && ir->op == ir_tg4) {
1704       emit_gen6_gather_wa(c->key.tex.gen6_gather_wa[sampler], dst);
1705    }
1706
1707    swizzle_result(ir, dst, sampler);
1708 }
1709
1710 /**
1711  * Apply workarounds for Gen6 gather with UINT/SINT
1712  */
1713 void
1714 fs_visitor::emit_gen6_gather_wa(uint8_t wa, fs_reg dst)
1715 {
1716    if (!wa)
1717       return;
1718
1719    int width = (wa & WA_8BIT) ? 8 : 16;
1720
1721    for (int i = 0; i < 4; i++) {
1722       fs_reg dst_f = dst.retype(BRW_REGISTER_TYPE_F);
1723       /* Convert from UNORM to UINT */
1724       emit(MUL(dst_f, dst_f, fs_reg((float)((1 << width) - 1))));
1725       emit(MOV(dst, dst_f));
1726
1727       if (wa & WA_SIGN) {
1728          /* Reinterpret the UINT value as a signed INT value by
1729           * shifting the sign bit into place, then shifting back
1730           * preserving sign.
1731           */
1732          emit(SHL(dst, dst, fs_reg(32 - width)));
1733          emit(ASR(dst, dst, fs_reg(32 - width)));
1734       }
1735
1736       dst.reg_offset++;
1737    }
1738 }
1739
1740 /**
1741  * Set up the gather channel based on the swizzle, for gather4.
1742  */
1743 uint32_t
1744 fs_visitor::gather_channel(ir_texture *ir, int sampler)
1745 {
1746    ir_constant *chan = ir->lod_info.component->as_constant();
1747    int swiz = GET_SWZ(c->key.tex.swizzles[sampler], chan->value.i[0]);
1748    switch (swiz) {
1749       case SWIZZLE_X: return 0;
1750       case SWIZZLE_Y:
1751          /* gather4 sampler is broken for green channel on RG32F --
1752           * we must ask for blue instead.
1753           */
1754          if (c->key.tex.gather_channel_quirk_mask & (1<<sampler))
1755             return 2;
1756          return 1;
1757       case SWIZZLE_Z: return 2;
1758       case SWIZZLE_W: return 3;
1759       default:
1760          assert(!"Not reached"); /* zero, one swizzles handled already */
1761          return 0;
1762    }
1763 }
1764
1765 /**
1766  * Swizzle the result of a texture result.  This is necessary for
1767  * EXT_texture_swizzle as well as DEPTH_TEXTURE_MODE for shadow comparisons.
1768  */
1769 void
1770 fs_visitor::swizzle_result(ir_texture *ir, fs_reg orig_val, int sampler)
1771 {
1772    if (ir->op == ir_query_levels) {
1773       /* # levels is in .w */
1774       orig_val.reg_offset += 3;
1775       this->result = orig_val;
1776       return;
1777    }
1778
1779    this->result = orig_val;
1780
1781    /* txs,lod don't actually sample the texture, so swizzling the result
1782     * makes no sense.
1783     */
1784    if (ir->op == ir_txs || ir->op == ir_lod || ir->op == ir_tg4)
1785       return;
1786
1787    if (ir->type == glsl_type::float_type) {
1788       /* Ignore DEPTH_TEXTURE_MODE swizzling. */
1789       assert(ir->sampler->type->sampler_shadow);
1790    } else if (c->key.tex.swizzles[sampler] != SWIZZLE_NOOP) {
1791       fs_reg swizzled_result = fs_reg(this, glsl_type::vec4_type);
1792
1793       for (int i = 0; i < 4; i++) {
1794          int swiz = GET_SWZ(c->key.tex.swizzles[sampler], i);
1795          fs_reg l = swizzled_result;
1796          l.reg_offset += i;
1797
1798          if (swiz == SWIZZLE_ZERO) {
1799             emit(MOV(l, fs_reg(0.0f)));
1800          } else if (swiz == SWIZZLE_ONE) {
1801             emit(MOV(l, fs_reg(1.0f)));
1802          } else {
1803             fs_reg r = orig_val;
1804             r.reg_offset += GET_SWZ(c->key.tex.swizzles[sampler], i);
1805             emit(MOV(l, r));
1806          }
1807       }
1808       this->result = swizzled_result;
1809    }
1810 }
1811
1812 void
1813 fs_visitor::visit(ir_swizzle *ir)
1814 {
1815    ir->val->accept(this);
1816    fs_reg val = this->result;
1817
1818    if (ir->type->vector_elements == 1) {
1819       this->result.reg_offset += ir->mask.x;
1820       return;
1821    }
1822
1823    fs_reg result = fs_reg(this, ir->type);
1824    this->result = result;
1825
1826    for (unsigned int i = 0; i < ir->type->vector_elements; i++) {
1827       fs_reg channel = val;
1828       int swiz = 0;
1829
1830       switch (i) {
1831       case 0:
1832          swiz = ir->mask.x;
1833          break;
1834       case 1:
1835          swiz = ir->mask.y;
1836          break;
1837       case 2:
1838          swiz = ir->mask.z;
1839          break;
1840       case 3:
1841          swiz = ir->mask.w;
1842          break;
1843       }
1844
1845       channel.reg_offset += swiz;
1846       emit(MOV(result, channel));
1847       result.reg_offset++;
1848    }
1849 }
1850
1851 void
1852 fs_visitor::visit(ir_discard *ir)
1853 {
1854    assert(ir->condition == NULL); /* FINISHME */
1855
1856    /* We track our discarded pixels in f0.1.  By predicating on it, we can
1857     * update just the flag bits that aren't yet discarded.  By emitting a
1858     * CMP of g0 != g0, all our currently executing channels will get turned
1859     * off.
1860     */
1861    fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
1862                                    BRW_REGISTER_TYPE_UW));
1863    fs_inst *cmp = emit(CMP(reg_null_f, some_reg, some_reg,
1864                            BRW_CONDITIONAL_NZ));
1865    cmp->predicate = BRW_PREDICATE_NORMAL;
1866    cmp->flag_subreg = 1;
1867
1868    if (brw->gen >= 6) {
1869       /* For performance, after a discard, jump to the end of the shader.
1870        * However, many people will do foliage by discarding based on a
1871        * texture's alpha mask, and then continue on to texture with the
1872        * remaining pixels.  To avoid trashing the derivatives for those
1873        * texture samples, we'll only jump if all of the pixels in the subspan
1874        * have been discarded.
1875        */
1876       fs_inst *discard_jump = emit(FS_OPCODE_DISCARD_JUMP);
1877       discard_jump->flag_subreg = 1;
1878       discard_jump->predicate = BRW_PREDICATE_ALIGN1_ANY4H;
1879       discard_jump->predicate_inverse = true;
1880    }
1881 }
1882
1883 void
1884 fs_visitor::visit(ir_constant *ir)
1885 {
1886    /* Set this->result to reg at the bottom of the function because some code
1887     * paths will cause this visitor to be applied to other fields.  This will
1888     * cause the value stored in this->result to be modified.
1889     *
1890     * Make reg constant so that it doesn't get accidentally modified along the
1891     * way.  Yes, I actually had this problem. :(
1892     */
1893    const fs_reg reg(this, ir->type);
1894    fs_reg dst_reg = reg;
1895
1896    if (ir->type->is_array()) {
1897       const unsigned size = type_size(ir->type->fields.array);
1898
1899       for (unsigned i = 0; i < ir->type->length; i++) {
1900          ir->array_elements[i]->accept(this);
1901          fs_reg src_reg = this->result;
1902
1903          dst_reg.type = src_reg.type;
1904          for (unsigned j = 0; j < size; j++) {
1905             emit(MOV(dst_reg, src_reg));
1906             src_reg.reg_offset++;
1907             dst_reg.reg_offset++;
1908          }
1909       }
1910    } else if (ir->type->is_record()) {
1911       foreach_list(node, &ir->components) {
1912          ir_constant *const field = (ir_constant *) node;
1913          const unsigned size = type_size(field->type);
1914
1915          field->accept(this);
1916          fs_reg src_reg = this->result;
1917
1918          dst_reg.type = src_reg.type;
1919          for (unsigned j = 0; j < size; j++) {
1920             emit(MOV(dst_reg, src_reg));
1921             src_reg.reg_offset++;
1922             dst_reg.reg_offset++;
1923          }
1924       }
1925    } else {
1926       const unsigned size = type_size(ir->type);
1927
1928       for (unsigned i = 0; i < size; i++) {
1929          switch (ir->type->base_type) {
1930          case GLSL_TYPE_FLOAT:
1931             emit(MOV(dst_reg, fs_reg(ir->value.f[i])));
1932             break;
1933          case GLSL_TYPE_UINT:
1934             emit(MOV(dst_reg, fs_reg(ir->value.u[i])));
1935             break;
1936          case GLSL_TYPE_INT:
1937             emit(MOV(dst_reg, fs_reg(ir->value.i[i])));
1938             break;
1939          case GLSL_TYPE_BOOL:
1940             emit(MOV(dst_reg, fs_reg((int)ir->value.b[i])));
1941             break;
1942          default:
1943             assert(!"Non-float/uint/int/bool constant");
1944          }
1945          dst_reg.reg_offset++;
1946       }
1947    }
1948
1949    this->result = reg;
1950 }
1951
1952 void
1953 fs_visitor::emit_bool_to_cond_code(ir_rvalue *ir)
1954 {
1955    ir_expression *expr = ir->as_expression();
1956
1957    if (expr &&
1958        expr->operation != ir_binop_logic_and &&
1959        expr->operation != ir_binop_logic_or &&
1960        expr->operation != ir_binop_logic_xor) {
1961       fs_reg op[2];
1962       fs_inst *inst;
1963
1964       assert(expr->get_num_operands() <= 2);
1965       for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
1966          assert(expr->operands[i]->type->is_scalar());
1967
1968          expr->operands[i]->accept(this);
1969          op[i] = this->result;
1970
1971          resolve_ud_negate(&op[i]);
1972       }
1973
1974       switch (expr->operation) {
1975       case ir_unop_logic_not:
1976          inst = emit(AND(reg_null_d, op[0], fs_reg(1)));
1977          inst->conditional_mod = BRW_CONDITIONAL_Z;
1978          break;
1979
1980       case ir_unop_f2b:
1981          if (brw->gen >= 6) {
1982             emit(CMP(reg_null_d, op[0], fs_reg(0.0f), BRW_CONDITIONAL_NZ));
1983          } else {
1984             inst = emit(MOV(reg_null_f, op[0]));
1985             inst->conditional_mod = BRW_CONDITIONAL_NZ;
1986          }
1987          break;
1988
1989       case ir_unop_i2b:
1990          if (brw->gen >= 6) {
1991             emit(CMP(reg_null_d, op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
1992          } else {
1993             inst = emit(MOV(reg_null_d, op[0]));
1994             inst->conditional_mod = BRW_CONDITIONAL_NZ;
1995          }
1996          break;
1997
1998       case ir_binop_greater:
1999       case ir_binop_gequal:
2000       case ir_binop_less:
2001       case ir_binop_lequal:
2002       case ir_binop_equal:
2003       case ir_binop_all_equal:
2004       case ir_binop_nequal:
2005       case ir_binop_any_nequal:
2006          resolve_bool_comparison(expr->operands[0], &op[0]);
2007          resolve_bool_comparison(expr->operands[1], &op[1]);
2008
2009          emit(CMP(reg_null_d, op[0], op[1],
2010                   brw_conditional_for_comparison(expr->operation)));
2011          break;
2012
2013       default:
2014          assert(!"not reached");
2015          fail("bad cond code\n");
2016          break;
2017       }
2018       return;
2019    }
2020
2021    ir->accept(this);
2022
2023    fs_inst *inst = emit(AND(reg_null_d, this->result, fs_reg(1)));
2024    inst->conditional_mod = BRW_CONDITIONAL_NZ;
2025 }
2026
2027 /**
2028  * Emit a gen6 IF statement with the comparison folded into the IF
2029  * instruction.
2030  */
2031 void
2032 fs_visitor::emit_if_gen6(ir_if *ir)
2033 {
2034    ir_expression *expr = ir->condition->as_expression();
2035
2036    if (expr) {
2037       fs_reg op[2];
2038       fs_inst *inst;
2039       fs_reg temp;
2040
2041       assert(expr->get_num_operands() <= 2);
2042       for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
2043          assert(expr->operands[i]->type->is_scalar());
2044
2045          expr->operands[i]->accept(this);
2046          op[i] = this->result;
2047       }
2048
2049       switch (expr->operation) {
2050       case ir_unop_logic_not:
2051       case ir_binop_logic_xor:
2052       case ir_binop_logic_or:
2053       case ir_binop_logic_and:
2054          /* For operations on bool arguments, only the low bit of the bool is
2055           * valid, and the others are undefined.  Fall back to the condition
2056           * code path.
2057           */
2058          break;
2059
2060       case ir_unop_f2b:
2061          inst = emit(BRW_OPCODE_IF, reg_null_f, op[0], fs_reg(0));
2062          inst->conditional_mod = BRW_CONDITIONAL_NZ;
2063          return;
2064
2065       case ir_unop_i2b:
2066          emit(IF(op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
2067          return;
2068
2069       case ir_binop_greater:
2070       case ir_binop_gequal:
2071       case ir_binop_less:
2072       case ir_binop_lequal:
2073       case ir_binop_equal:
2074       case ir_binop_all_equal:
2075       case ir_binop_nequal:
2076       case ir_binop_any_nequal:
2077          resolve_bool_comparison(expr->operands[0], &op[0]);
2078          resolve_bool_comparison(expr->operands[1], &op[1]);
2079
2080          emit(IF(op[0], op[1],
2081                  brw_conditional_for_comparison(expr->operation)));
2082          return;
2083       default:
2084          assert(!"not reached");
2085          emit(IF(op[0], fs_reg(0), BRW_CONDITIONAL_NZ));
2086          fail("bad condition\n");
2087          return;
2088       }
2089    }
2090
2091    emit_bool_to_cond_code(ir->condition);
2092    fs_inst *inst = emit(BRW_OPCODE_IF);
2093    inst->predicate = BRW_PREDICATE_NORMAL;
2094 }
2095
2096 /**
2097  * Try to replace IF/MOV/ELSE/MOV/ENDIF with SEL.
2098  *
2099  * Many GLSL shaders contain the following pattern:
2100  *
2101  *    x = condition ? foo : bar
2102  *
2103  * The compiler emits an ir_if tree for this, since each subexpression might be
2104  * a complex tree that could have side-effects or short-circuit logic.
2105  *
2106  * However, the common case is to simply select one of two constants or
2107  * variable values---which is exactly what SEL is for.  In this case, the
2108  * assembly looks like:
2109  *
2110  *    (+f0) IF
2111  *    MOV dst src0
2112  *    ELSE
2113  *    MOV dst src1
2114  *    ENDIF
2115  *
2116  * which can be easily translated into:
2117  *
2118  *    (+f0) SEL dst src0 src1
2119  *
2120  * If src0 is an immediate value, we promote it to a temporary GRF.
2121  */
2122 void
2123 fs_visitor::try_replace_with_sel()
2124 {
2125    fs_inst *endif_inst = (fs_inst *) instructions.get_tail();
2126    assert(endif_inst->opcode == BRW_OPCODE_ENDIF);
2127
2128    /* Pattern match in reverse: IF, MOV, ELSE, MOV, ENDIF. */
2129    int opcodes[] = {
2130       BRW_OPCODE_IF, BRW_OPCODE_MOV, BRW_OPCODE_ELSE, BRW_OPCODE_MOV,
2131    };
2132
2133    fs_inst *match = (fs_inst *) endif_inst->prev;
2134    for (int i = 0; i < 4; i++) {
2135       if (match->is_head_sentinel() || match->opcode != opcodes[4-i-1])
2136          return;
2137       match = (fs_inst *) match->prev;
2138    }
2139
2140    /* The opcodes match; it looks like the right sequence of instructions. */
2141    fs_inst *else_mov = (fs_inst *) endif_inst->prev;
2142    fs_inst *then_mov = (fs_inst *) else_mov->prev->prev;
2143    fs_inst *if_inst = (fs_inst *) then_mov->prev;
2144
2145    /* Check that the MOVs are the right form. */
2146    if (then_mov->dst.equals(else_mov->dst) &&
2147        !then_mov->is_partial_write() &&
2148        !else_mov->is_partial_write()) {
2149
2150       /* Remove the matched instructions; we'll emit a SEL to replace them. */
2151       while (!if_inst->next->is_tail_sentinel())
2152          if_inst->next->remove();
2153       if_inst->remove();
2154
2155       /* Only the last source register can be a constant, so if the MOV in
2156        * the "then" clause uses a constant, we need to put it in a temporary.
2157        */
2158       fs_reg src0(then_mov->src[0]);
2159       if (src0.file == IMM) {
2160          src0 = fs_reg(this, glsl_type::float_type);
2161          src0.type = then_mov->src[0].type;
2162          emit(MOV(src0, then_mov->src[0]));
2163       }
2164
2165       fs_inst *sel;
2166       if (if_inst->conditional_mod) {
2167          /* Sandybridge-specific IF with embedded comparison */
2168          emit(CMP(reg_null_d, if_inst->src[0], if_inst->src[1],
2169                   if_inst->conditional_mod));
2170          sel = emit(BRW_OPCODE_SEL, then_mov->dst, src0, else_mov->src[0]);
2171          sel->predicate = BRW_PREDICATE_NORMAL;
2172       } else {
2173          /* Separate CMP and IF instructions */
2174          sel = emit(BRW_OPCODE_SEL, then_mov->dst, src0, else_mov->src[0]);
2175          sel->predicate = if_inst->predicate;
2176          sel->predicate_inverse = if_inst->predicate_inverse;
2177       }
2178    }
2179 }
2180
2181 void
2182 fs_visitor::visit(ir_if *ir)
2183 {
2184    if (brw->gen < 6 && dispatch_width == 16) {
2185       fail("Can't support (non-uniform) control flow on SIMD16\n");
2186    }
2187
2188    /* Don't point the annotation at the if statement, because then it plus
2189     * the then and else blocks get printed.
2190     */
2191    this->base_ir = ir->condition;
2192
2193    if (brw->gen == 6) {
2194       emit_if_gen6(ir);
2195    } else {
2196       emit_bool_to_cond_code(ir->condition);
2197
2198       emit(IF(BRW_PREDICATE_NORMAL));
2199    }
2200
2201    foreach_list(node, &ir->then_instructions) {
2202       ir_instruction *ir = (ir_instruction *)node;
2203       this->base_ir = ir;
2204
2205       ir->accept(this);
2206    }
2207
2208    if (!ir->else_instructions.is_empty()) {
2209       emit(BRW_OPCODE_ELSE);
2210
2211       foreach_list(node, &ir->else_instructions) {
2212          ir_instruction *ir = (ir_instruction *)node;
2213          this->base_ir = ir;
2214
2215          ir->accept(this);
2216       }
2217    }
2218
2219    emit(BRW_OPCODE_ENDIF);
2220
2221    try_replace_with_sel();
2222 }
2223
2224 void
2225 fs_visitor::visit(ir_loop *ir)
2226 {
2227    if (brw->gen < 6 && dispatch_width == 16) {
2228       fail("Can't support (non-uniform) control flow on SIMD16\n");
2229    }
2230
2231    this->base_ir = NULL;
2232    emit(BRW_OPCODE_DO);
2233
2234    foreach_list(node, &ir->body_instructions) {
2235       ir_instruction *ir = (ir_instruction *)node;
2236
2237       this->base_ir = ir;
2238       ir->accept(this);
2239    }
2240
2241    this->base_ir = NULL;
2242    emit(BRW_OPCODE_WHILE);
2243 }
2244
2245 void
2246 fs_visitor::visit(ir_loop_jump *ir)
2247 {
2248    switch (ir->mode) {
2249    case ir_loop_jump::jump_break:
2250       emit(BRW_OPCODE_BREAK);
2251       break;
2252    case ir_loop_jump::jump_continue:
2253       emit(BRW_OPCODE_CONTINUE);
2254       break;
2255    }
2256 }
2257
2258 void
2259 fs_visitor::visit_atomic_counter_intrinsic(ir_call *ir)
2260 {
2261    ir_dereference *deref = static_cast<ir_dereference *>(
2262       ir->actual_parameters.get_head());
2263    ir_variable *location = deref->variable_referenced();
2264    unsigned surf_index = (c->prog_data.base.binding_table.abo_start +
2265                           location->data.atomic.buffer_index);
2266
2267    /* Calculate the surface offset */
2268    fs_reg offset(this, glsl_type::uint_type);
2269    ir_dereference_array *deref_array = deref->as_dereference_array();
2270
2271    if (deref_array) {
2272       deref_array->array_index->accept(this);
2273
2274       fs_reg tmp(this, glsl_type::uint_type);
2275       emit(MUL(tmp, this->result, ATOMIC_COUNTER_SIZE));
2276       emit(ADD(offset, tmp, location->data.atomic.offset));
2277    } else {
2278       offset = location->data.atomic.offset;
2279    }
2280
2281    /* Emit the appropriate machine instruction */
2282    const char *callee = ir->callee->function_name();
2283    ir->return_deref->accept(this);
2284    fs_reg dst = this->result;
2285
2286    if (!strcmp("__intrinsic_atomic_read", callee)) {
2287       emit_untyped_surface_read(surf_index, dst, offset);
2288
2289    } else if (!strcmp("__intrinsic_atomic_increment", callee)) {
2290       emit_untyped_atomic(BRW_AOP_INC, surf_index, dst, offset,
2291                           fs_reg(), fs_reg());
2292
2293    } else if (!strcmp("__intrinsic_atomic_predecrement", callee)) {
2294       emit_untyped_atomic(BRW_AOP_PREDEC, surf_index, dst, offset,
2295                           fs_reg(), fs_reg());
2296    }
2297 }
2298
2299 void
2300 fs_visitor::visit(ir_call *ir)
2301 {
2302    const char *callee = ir->callee->function_name();
2303
2304    if (!strcmp("__intrinsic_atomic_read", callee) ||
2305        !strcmp("__intrinsic_atomic_increment", callee) ||
2306        !strcmp("__intrinsic_atomic_predecrement", callee)) {
2307       visit_atomic_counter_intrinsic(ir);
2308    } else {
2309       assert(!"Unsupported intrinsic.");
2310    }
2311 }
2312
2313 void
2314 fs_visitor::visit(ir_return *ir)
2315 {
2316    assert(!"FINISHME");
2317 }
2318
2319 void
2320 fs_visitor::visit(ir_function *ir)
2321 {
2322    /* Ignore function bodies other than main() -- we shouldn't see calls to
2323     * them since they should all be inlined before we get to ir_to_mesa.
2324     */
2325    if (strcmp(ir->name, "main") == 0) {
2326       const ir_function_signature *sig;
2327       exec_list empty;
2328
2329       sig = ir->matching_signature(NULL, &empty);
2330
2331       assert(sig);
2332
2333       foreach_list(node, &sig->body) {
2334          ir_instruction *ir = (ir_instruction *)node;
2335          this->base_ir = ir;
2336
2337          ir->accept(this);
2338       }
2339    }
2340 }
2341
2342 void
2343 fs_visitor::visit(ir_function_signature *ir)
2344 {
2345    assert(!"not reached");
2346    (void)ir;
2347 }
2348
2349 void
2350 fs_visitor::visit(ir_emit_vertex *)
2351 {
2352    assert(!"not reached");
2353 }
2354
2355 void
2356 fs_visitor::visit(ir_end_primitive *)
2357 {
2358    assert(!"not reached");
2359 }
2360
2361 void
2362 fs_visitor::emit_untyped_atomic(unsigned atomic_op, unsigned surf_index,
2363                                 fs_reg dst, fs_reg offset, fs_reg src0,
2364                                 fs_reg src1)
2365 {
2366    const unsigned operand_len = dispatch_width / 8;
2367    unsigned mlen = 0;
2368
2369    /* Initialize the sample mask in the message header. */
2370    emit(MOV(brw_uvec_mrf(8, mlen, 0), brw_imm_ud(0)))
2371       ->force_writemask_all = true;
2372
2373    if (fp->UsesKill) {
2374       emit(MOV(brw_uvec_mrf(1, mlen, 7), brw_flag_reg(0, 1)))
2375          ->force_writemask_all = true;
2376    } else {
2377       emit(MOV(brw_uvec_mrf(1, mlen, 7),
2378                retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UD)))
2379          ->force_writemask_all = true;
2380    }
2381
2382    mlen++;
2383
2384    /* Set the atomic operation offset. */
2385    emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), offset));
2386    mlen += operand_len;
2387
2388    /* Set the atomic operation arguments. */
2389    if (src0.file != BAD_FILE) {
2390       emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), src0));
2391       mlen += operand_len;
2392    }
2393
2394    if (src1.file != BAD_FILE) {
2395       emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), src1));
2396       mlen += operand_len;
2397    }
2398
2399    /* Emit the instruction. */
2400    fs_inst inst(SHADER_OPCODE_UNTYPED_ATOMIC, dst, atomic_op, surf_index);
2401    inst.base_mrf = 0;
2402    inst.mlen = mlen;
2403    emit(inst);
2404 }
2405
2406 void
2407 fs_visitor::emit_untyped_surface_read(unsigned surf_index, fs_reg dst,
2408                                       fs_reg offset)
2409 {
2410    const unsigned operand_len = dispatch_width / 8;
2411    unsigned mlen = 0;
2412
2413    /* Initialize the sample mask in the message header. */
2414    emit(MOV(brw_uvec_mrf(8, mlen, 0), brw_imm_ud(0)))
2415       ->force_writemask_all = true;
2416
2417    if (fp->UsesKill) {
2418       emit(MOV(brw_uvec_mrf(1, mlen, 7), brw_flag_reg(0, 1)))
2419          ->force_writemask_all = true;
2420    } else {
2421       emit(MOV(brw_uvec_mrf(1, mlen, 7),
2422                retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UD)))
2423          ->force_writemask_all = true;
2424    }
2425
2426    mlen++;
2427
2428    /* Set the surface read offset. */
2429    emit(MOV(brw_uvec_mrf(dispatch_width, mlen, 0), offset));
2430    mlen += operand_len;
2431
2432    /* Emit the instruction. */
2433    fs_inst inst(SHADER_OPCODE_UNTYPED_SURFACE_READ, dst, surf_index);
2434    inst.base_mrf = 0;
2435    inst.mlen = mlen;
2436    emit(inst);
2437 }
2438
2439 fs_inst *
2440 fs_visitor::emit(fs_inst inst)
2441 {
2442    fs_inst *list_inst = new(mem_ctx) fs_inst;
2443    *list_inst = inst;
2444    emit(list_inst);
2445    return list_inst;
2446 }
2447
2448 fs_inst *
2449 fs_visitor::emit(fs_inst *inst)
2450 {
2451    if (force_uncompressed_stack > 0)
2452       inst->force_uncompressed = true;
2453
2454    inst->annotation = this->current_annotation;
2455    inst->ir = this->base_ir;
2456
2457    this->instructions.push_tail(inst);
2458
2459    return inst;
2460 }
2461
2462 void
2463 fs_visitor::emit(exec_list list)
2464 {
2465    foreach_list_safe(node, &list) {
2466       fs_inst *inst = (fs_inst *)node;
2467       inst->remove();
2468       emit(inst);
2469    }
2470 }
2471
2472 /** Emits a dummy fragment shader consisting of magenta for bringup purposes. */
2473 void
2474 fs_visitor::emit_dummy_fs()
2475 {
2476    int reg_width = dispatch_width / 8;
2477
2478    /* Everyone's favorite color. */
2479    emit(MOV(fs_reg(MRF, 2 + 0 * reg_width), fs_reg(1.0f)));
2480    emit(MOV(fs_reg(MRF, 2 + 1 * reg_width), fs_reg(0.0f)));
2481    emit(MOV(fs_reg(MRF, 2 + 2 * reg_width), fs_reg(1.0f)));
2482    emit(MOV(fs_reg(MRF, 2 + 3 * reg_width), fs_reg(0.0f)));
2483
2484    fs_inst *write;
2485    write = emit(FS_OPCODE_FB_WRITE, fs_reg(0), fs_reg(0));
2486    write->base_mrf = 2;
2487    write->mlen = 4 * reg_width;
2488    write->eot = true;
2489 }
2490
2491 /* The register location here is relative to the start of the URB
2492  * data.  It will get adjusted to be a real location before
2493  * generate_code() time.
2494  */
2495 struct brw_reg
2496 fs_visitor::interp_reg(int location, int channel)
2497 {
2498    int regnr = c->prog_data.urb_setup[location] * 2 + channel / 2;
2499    int stride = (channel & 1) * 4;
2500
2501    assert(c->prog_data.urb_setup[location] != -1);
2502
2503    return brw_vec1_grf(regnr, stride);
2504 }
2505
2506 /** Emits the interpolation for the varying inputs. */
2507 void
2508 fs_visitor::emit_interpolation_setup_gen4()
2509 {
2510    this->current_annotation = "compute pixel centers";
2511    this->pixel_x = fs_reg(this, glsl_type::uint_type);
2512    this->pixel_y = fs_reg(this, glsl_type::uint_type);
2513    this->pixel_x.type = BRW_REGISTER_TYPE_UW;
2514    this->pixel_y.type = BRW_REGISTER_TYPE_UW;
2515
2516    emit(FS_OPCODE_PIXEL_X, this->pixel_x);
2517    emit(FS_OPCODE_PIXEL_Y, this->pixel_y);
2518
2519    this->current_annotation = "compute pixel deltas from v0";
2520    if (brw->has_pln) {
2521       this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2522          fs_reg(this, glsl_type::vec2_type);
2523       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2524          this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC];
2525       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].reg_offset++;
2526    } else {
2527       this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2528          fs_reg(this, glsl_type::float_type);
2529       this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC] =
2530          fs_reg(this, glsl_type::float_type);
2531    }
2532    emit(ADD(this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2533             this->pixel_x, fs_reg(negate(brw_vec1_grf(1, 0)))));
2534    emit(ADD(this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2535             this->pixel_y, fs_reg(negate(brw_vec1_grf(1, 1)))));
2536
2537    this->current_annotation = "compute pos.w and 1/pos.w";
2538    /* Compute wpos.w.  It's always in our setup, since it's needed to
2539     * interpolate the other attributes.
2540     */
2541    this->wpos_w = fs_reg(this, glsl_type::float_type);
2542    emit(FS_OPCODE_LINTERP, wpos_w,
2543         this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2544         this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
2545         interp_reg(VARYING_SLOT_POS, 3));
2546    /* Compute the pixel 1/W value from wpos.w. */
2547    this->pixel_w = fs_reg(this, glsl_type::float_type);
2548    emit_math(SHADER_OPCODE_RCP, this->pixel_w, wpos_w);
2549    this->current_annotation = NULL;
2550 }
2551
2552 /** Emits the interpolation for the varying inputs. */
2553 void
2554 fs_visitor::emit_interpolation_setup_gen6()
2555 {
2556    struct brw_reg g1_uw = retype(brw_vec1_grf(1, 0), BRW_REGISTER_TYPE_UW);
2557
2558    /* If the pixel centers end up used, the setup is the same as for gen4. */
2559    this->current_annotation = "compute pixel centers";
2560    fs_reg int_pixel_x = fs_reg(this, glsl_type::uint_type);
2561    fs_reg int_pixel_y = fs_reg(this, glsl_type::uint_type);
2562    int_pixel_x.type = BRW_REGISTER_TYPE_UW;
2563    int_pixel_y.type = BRW_REGISTER_TYPE_UW;
2564    emit(ADD(int_pixel_x,
2565             fs_reg(stride(suboffset(g1_uw, 4), 2, 4, 0)),
2566             fs_reg(brw_imm_v(0x10101010))));
2567    emit(ADD(int_pixel_y,
2568             fs_reg(stride(suboffset(g1_uw, 5), 2, 4, 0)),
2569             fs_reg(brw_imm_v(0x11001100))));
2570
2571    /* As of gen6, we can no longer mix float and int sources.  We have
2572     * to turn the integer pixel centers into floats for their actual
2573     * use.
2574     */
2575    this->pixel_x = fs_reg(this, glsl_type::float_type);
2576    this->pixel_y = fs_reg(this, glsl_type::float_type);
2577    emit(MOV(this->pixel_x, int_pixel_x));
2578    emit(MOV(this->pixel_y, int_pixel_y));
2579
2580    this->current_annotation = "compute pos.w";
2581    this->pixel_w = fs_reg(brw_vec8_grf(c->source_w_reg, 0));
2582    this->wpos_w = fs_reg(this, glsl_type::float_type);
2583    emit_math(SHADER_OPCODE_RCP, this->wpos_w, this->pixel_w);
2584
2585    for (int i = 0; i < BRW_WM_BARYCENTRIC_INTERP_MODE_COUNT; ++i) {
2586       uint8_t reg = c->barycentric_coord_reg[i];
2587       this->delta_x[i] = fs_reg(brw_vec8_grf(reg, 0));
2588       this->delta_y[i] = fs_reg(brw_vec8_grf(reg + 1, 0));
2589    }
2590
2591    this->current_annotation = NULL;
2592 }
2593
2594 void
2595 fs_visitor::emit_color_write(int target, int index, int first_color_mrf)
2596 {
2597    int reg_width = dispatch_width / 8;
2598    fs_inst *inst;
2599    fs_reg color = outputs[target];
2600    fs_reg mrf;
2601
2602    /* If there's no color data to be written, skip it. */
2603    if (color.file == BAD_FILE)
2604       return;
2605
2606    color.reg_offset += index;
2607
2608    if (dispatch_width == 8 || brw->gen >= 6) {
2609       /* SIMD8 write looks like:
2610        * m + 0: r0
2611        * m + 1: r1
2612        * m + 2: g0
2613        * m + 3: g1
2614        *
2615        * gen6 SIMD16 DP write looks like:
2616        * m + 0: r0
2617        * m + 1: r1
2618        * m + 2: g0
2619        * m + 3: g1
2620        * m + 4: b0
2621        * m + 5: b1
2622        * m + 6: a0
2623        * m + 7: a1
2624        */
2625       inst = emit(MOV(fs_reg(MRF, first_color_mrf + index * reg_width,
2626                              color.type),
2627                       color));
2628       inst->saturate = c->key.clamp_fragment_color;
2629    } else {
2630       /* pre-gen6 SIMD16 single source DP write looks like:
2631        * m + 0: r0
2632        * m + 1: g0
2633        * m + 2: b0
2634        * m + 3: a0
2635        * m + 4: r1
2636        * m + 5: g1
2637        * m + 6: b1
2638        * m + 7: a1
2639        */
2640       if (brw->has_compr4) {
2641          /* By setting the high bit of the MRF register number, we
2642           * indicate that we want COMPR4 mode - instead of doing the
2643           * usual destination + 1 for the second half we get
2644           * destination + 4.
2645           */
2646          inst = emit(MOV(fs_reg(MRF, BRW_MRF_COMPR4 + first_color_mrf + index,
2647                                 color.type),
2648                          color));
2649          inst->saturate = c->key.clamp_fragment_color;
2650       } else {
2651          push_force_uncompressed();
2652          inst = emit(MOV(fs_reg(MRF, first_color_mrf + index, color.type),
2653                          color));
2654          inst->saturate = c->key.clamp_fragment_color;
2655          pop_force_uncompressed();
2656
2657          color.sechalf = true;
2658          inst = emit(MOV(fs_reg(MRF, first_color_mrf + index + 4, color.type),
2659                          color));
2660          inst->force_sechalf = true;
2661          inst->saturate = c->key.clamp_fragment_color;
2662          color.sechalf = false;
2663       }
2664    }
2665 }
2666
2667 static int
2668 cond_for_alpha_func(GLenum func)
2669 {
2670    switch(func) {
2671       case GL_GREATER:
2672          return BRW_CONDITIONAL_G;
2673       case GL_GEQUAL:
2674          return BRW_CONDITIONAL_GE;
2675       case GL_LESS:
2676          return BRW_CONDITIONAL_L;
2677       case GL_LEQUAL:
2678          return BRW_CONDITIONAL_LE;
2679       case GL_EQUAL:
2680          return BRW_CONDITIONAL_EQ;
2681       case GL_NOTEQUAL:
2682          return BRW_CONDITIONAL_NEQ;
2683       default:
2684          assert(!"Not reached");
2685          return 0;
2686    }
2687 }
2688
2689 /**
2690  * Alpha test support for when we compile it into the shader instead
2691  * of using the normal fixed-function alpha test.
2692  */
2693 void
2694 fs_visitor::emit_alpha_test()
2695 {
2696    this->current_annotation = "Alpha test";
2697
2698    fs_inst *cmp;
2699    if (c->key.alpha_test_func == GL_ALWAYS)
2700       return;
2701
2702    if (c->key.alpha_test_func == GL_NEVER) {
2703       /* f0.1 = 0 */
2704       fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
2705                                       BRW_REGISTER_TYPE_UW));
2706       cmp = emit(CMP(reg_null_f, some_reg, some_reg,
2707                      BRW_CONDITIONAL_NEQ));
2708    } else {
2709       /* RT0 alpha */
2710       fs_reg color = outputs[0];
2711       color.reg_offset += 3;
2712
2713       /* f0.1 &= func(color, ref) */
2714       cmp = emit(CMP(reg_null_f, color, fs_reg(c->key.alpha_test_ref),
2715                      cond_for_alpha_func(c->key.alpha_test_func)));
2716    }
2717    cmp->predicate = BRW_PREDICATE_NORMAL;
2718    cmp->flag_subreg = 1;
2719 }
2720
2721 void
2722 fs_visitor::emit_fb_writes()
2723 {
2724    this->current_annotation = "FB write header";
2725    bool header_present = true;
2726    /* We can potentially have a message length of up to 15, so we have to set
2727     * base_mrf to either 0 or 1 in order to fit in m0..m15.
2728     */
2729    int base_mrf = 1;
2730    int nr = base_mrf;
2731    int reg_width = dispatch_width / 8;
2732    bool do_dual_src = this->dual_src_output.file != BAD_FILE;
2733    bool src0_alpha_to_render_target = false;
2734
2735    if (dispatch_width == 16 && do_dual_src) {
2736       fail("GL_ARB_blend_func_extended not yet supported in SIMD16.");
2737       do_dual_src = false;
2738    }
2739
2740    /* From the Sandy Bridge PRM, volume 4, page 198:
2741     *
2742     *     "Dispatched Pixel Enables. One bit per pixel indicating
2743     *      which pixels were originally enabled when the thread was
2744     *      dispatched. This field is only required for the end-of-
2745     *      thread message and on all dual-source messages."
2746     */
2747    if (brw->gen >= 6 &&
2748        !this->fp->UsesKill &&
2749        !do_dual_src &&
2750        c->key.nr_color_regions == 1) {
2751       header_present = false;
2752    }
2753
2754    if (header_present) {
2755       src0_alpha_to_render_target = brw->gen >= 6 &&
2756                                     !do_dual_src &&
2757                                     c->key.replicate_alpha;
2758       /* m2, m3 header */
2759       nr += 2;
2760    }
2761
2762    if (c->aa_dest_stencil_reg) {
2763       push_force_uncompressed();
2764       emit(MOV(fs_reg(MRF, nr++),
2765                fs_reg(brw_vec8_grf(c->aa_dest_stencil_reg, 0))));
2766       pop_force_uncompressed();
2767    }
2768
2769    c->prog_data.uses_omask =
2770       fp->Base.OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
2771    if(c->prog_data.uses_omask) {
2772       this->current_annotation = "FB write oMask";
2773       assert(this->sample_mask.file != BAD_FILE);
2774       /* Hand over gl_SampleMask. Only lower 16 bits are relevant. */
2775       emit(FS_OPCODE_SET_OMASK, fs_reg(MRF, nr, BRW_REGISTER_TYPE_UW), this->sample_mask);
2776       nr += 1;
2777    }
2778
2779    /* Reserve space for color. It'll be filled in per MRT below. */
2780    int color_mrf = nr;
2781    nr += 4 * reg_width;
2782    if (do_dual_src)
2783       nr += 4;
2784    if (src0_alpha_to_render_target)
2785       nr += reg_width;
2786
2787    if (c->source_depth_to_render_target) {
2788       if (brw->gen == 6 && dispatch_width == 16) {
2789          /* For outputting oDepth on gen6, SIMD8 writes have to be
2790           * used.  This would require SIMD8 moves of each half to
2791           * message regs, kind of like pre-gen5 SIMD16 FB writes.
2792           * Just bail on doing so for now.
2793           */
2794          fail("Missing support for simd16 depth writes on gen6\n");
2795       }
2796
2797       if (prog->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
2798          /* Hand over gl_FragDepth. */
2799          assert(this->frag_depth.file != BAD_FILE);
2800          emit(MOV(fs_reg(MRF, nr), this->frag_depth));
2801       } else {
2802          /* Pass through the payload depth. */
2803          emit(MOV(fs_reg(MRF, nr),
2804                   fs_reg(brw_vec8_grf(c->source_depth_reg, 0))));
2805       }
2806       nr += reg_width;
2807    }
2808
2809    if (c->dest_depth_reg) {
2810       emit(MOV(fs_reg(MRF, nr),
2811                fs_reg(brw_vec8_grf(c->dest_depth_reg, 0))));
2812       nr += reg_width;
2813    }
2814
2815    if (do_dual_src) {
2816       fs_reg src0 = this->outputs[0];
2817       fs_reg src1 = this->dual_src_output;
2818
2819       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2820                                                  "FB write src0");
2821       for (int i = 0; i < 4; i++) {
2822          fs_inst *inst = emit(MOV(fs_reg(MRF, color_mrf + i, src0.type), src0));
2823          src0.reg_offset++;
2824          inst->saturate = c->key.clamp_fragment_color;
2825       }
2826
2827       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2828                                                  "FB write src1");
2829       for (int i = 0; i < 4; i++) {
2830          fs_inst *inst = emit(MOV(fs_reg(MRF, color_mrf + 4 + i, src1.type),
2831                                   src1));
2832          src1.reg_offset++;
2833          inst->saturate = c->key.clamp_fragment_color;
2834       }
2835
2836       if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2837          emit_shader_time_end();
2838
2839       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2840       inst->target = 0;
2841       inst->base_mrf = base_mrf;
2842       inst->mlen = nr - base_mrf;
2843       inst->eot = true;
2844       inst->header_present = header_present;
2845
2846       c->prog_data.dual_src_blend = true;
2847       this->current_annotation = NULL;
2848       return;
2849    }
2850
2851    for (int target = 0; target < c->key.nr_color_regions; target++) {
2852       this->current_annotation = ralloc_asprintf(this->mem_ctx,
2853                                                  "FB write target %d",
2854                                                  target);
2855       /* If src0_alpha_to_render_target is true, include source zero alpha
2856        * data in RenderTargetWrite message for targets > 0.
2857        */
2858       int write_color_mrf = color_mrf;
2859       if (src0_alpha_to_render_target && target != 0) {
2860          fs_inst *inst;
2861          fs_reg color = outputs[0];
2862          color.reg_offset += 3;
2863
2864          inst = emit(MOV(fs_reg(MRF, write_color_mrf, color.type),
2865                          color));
2866          inst->saturate = c->key.clamp_fragment_color;
2867          write_color_mrf = color_mrf + reg_width;
2868       }
2869
2870       for (unsigned i = 0; i < this->output_components[target]; i++)
2871          emit_color_write(target, i, write_color_mrf);
2872
2873       bool eot = false;
2874       if (target == c->key.nr_color_regions - 1) {
2875          eot = true;
2876
2877          if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2878             emit_shader_time_end();
2879       }
2880
2881       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2882       inst->target = target;
2883       inst->base_mrf = base_mrf;
2884       if (src0_alpha_to_render_target && target == 0)
2885          inst->mlen = nr - base_mrf - reg_width;
2886       else
2887          inst->mlen = nr - base_mrf;
2888       inst->eot = eot;
2889       inst->header_present = header_present;
2890    }
2891
2892    if (c->key.nr_color_regions == 0) {
2893       /* Even if there's no color buffers enabled, we still need to send
2894        * alpha out the pipeline to our null renderbuffer to support
2895        * alpha-testing, alpha-to-coverage, and so on.
2896        */
2897       emit_color_write(0, 3, color_mrf);
2898
2899       if (INTEL_DEBUG & DEBUG_SHADER_TIME)
2900          emit_shader_time_end();
2901
2902       fs_inst *inst = emit(FS_OPCODE_FB_WRITE);
2903       inst->base_mrf = base_mrf;
2904       inst->mlen = nr - base_mrf;
2905       inst->eot = true;
2906       inst->header_present = header_present;
2907    }
2908
2909    this->current_annotation = NULL;
2910 }
2911
2912 void
2913 fs_visitor::resolve_ud_negate(fs_reg *reg)
2914 {
2915    if (reg->type != BRW_REGISTER_TYPE_UD ||
2916        !reg->negate)
2917       return;
2918
2919    fs_reg temp = fs_reg(this, glsl_type::uint_type);
2920    emit(MOV(temp, *reg));
2921    *reg = temp;
2922 }
2923
2924 void
2925 fs_visitor::resolve_bool_comparison(ir_rvalue *rvalue, fs_reg *reg)
2926 {
2927    if (rvalue->type != glsl_type::bool_type)
2928       return;
2929
2930    fs_reg temp = fs_reg(this, glsl_type::bool_type);
2931    emit(AND(temp, *reg, fs_reg(1)));
2932    *reg = temp;
2933 }
2934
2935 fs_visitor::fs_visitor(struct brw_context *brw,
2936                        struct brw_wm_compile *c,
2937                        struct gl_shader_program *shader_prog,
2938                        struct gl_fragment_program *fp,
2939                        unsigned dispatch_width)
2940    : dispatch_width(dispatch_width)
2941 {
2942    this->c = c;
2943    this->brw = brw;
2944    this->fp = fp;
2945    this->prog = &fp->Base;
2946    this->shader_prog = shader_prog;
2947    this->prog = &fp->Base;
2948    this->stage_prog_data = &c->prog_data.base;
2949    this->ctx = &brw->ctx;
2950    this->mem_ctx = ralloc_context(NULL);
2951    if (shader_prog)
2952       shader = (struct brw_shader *)
2953          shader_prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2954    else
2955       shader = NULL;
2956    this->failed = false;
2957    this->variable_ht = hash_table_ctor(0,
2958                                        hash_table_pointer_hash,
2959                                        hash_table_pointer_compare);
2960
2961    memset(this->outputs, 0, sizeof(this->outputs));
2962    memset(this->output_components, 0, sizeof(this->output_components));
2963    this->first_non_payload_grf = 0;
2964    this->max_grf = brw->gen >= 7 ? GEN7_MRF_HACK_START : BRW_MAX_GRF;
2965
2966    this->current_annotation = NULL;
2967    this->base_ir = NULL;
2968
2969    this->virtual_grf_sizes = NULL;
2970    this->virtual_grf_count = 0;
2971    this->virtual_grf_array_size = 0;
2972    this->virtual_grf_start = NULL;
2973    this->virtual_grf_end = NULL;
2974    this->live_intervals = NULL;
2975    this->regs_live_at_ip = NULL;
2976
2977    this->params_remap = NULL;
2978    this->nr_params_remap = 0;
2979
2980    this->force_uncompressed_stack = 0;
2981
2982    this->spilled_any_registers = false;
2983
2984    memset(&this->param_size, 0, sizeof(this->param_size));
2985 }
2986
2987 fs_visitor::~fs_visitor()
2988 {
2989    ralloc_free(this->mem_ctx);
2990    hash_table_dtor(this->variable_ht);
2991 }