brw_vec4_visitor.cpp revision 010cc547ca8c1fb2107106b0ad0de560780ce9aa
1/*
2 * Copyright © 2011 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24#include "brw_vec4.h"
25extern "C" {
26#include "main/macros.h"
27#include "program/prog_parameter.h"
28}
29
30namespace brw {
31
32src_reg::src_reg(dst_reg reg)
33{
34   init();
35
36   this->file = reg.file;
37   this->reg = reg.reg;
38   this->reg_offset = reg.reg_offset;
39   this->type = reg.type;
40   this->reladdr = reg.reladdr;
41   this->fixed_hw_reg = reg.fixed_hw_reg;
42
43   int swizzles[4];
44   int next_chan = 0;
45   int last = 0;
46
47   for (int i = 0; i < 4; i++) {
48      if (!(reg.writemask & (1 << i)))
49	 continue;
50
51      swizzles[next_chan++] = last = i;
52   }
53
54   for (; next_chan < 4; next_chan++) {
55      swizzles[next_chan] = last;
56   }
57
58   this->swizzle = BRW_SWIZZLE4(swizzles[0], swizzles[1],
59				swizzles[2], swizzles[3]);
60}
61
62dst_reg::dst_reg(src_reg reg)
63{
64   init();
65
66   this->file = reg.file;
67   this->reg = reg.reg;
68   this->reg_offset = reg.reg_offset;
69   this->type = reg.type;
70   this->writemask = WRITEMASK_XYZW;
71   this->reladdr = reg.reladdr;
72   this->fixed_hw_reg = reg.fixed_hw_reg;
73}
74
75vec4_instruction::vec4_instruction(vec4_visitor *v,
76				   enum opcode opcode, dst_reg dst,
77				   src_reg src0, src_reg src1, src_reg src2)
78{
79   this->opcode = opcode;
80   this->dst = dst;
81   this->src[0] = src0;
82   this->src[1] = src1;
83   this->src[2] = src2;
84   this->ir = v->base_ir;
85   this->annotation = v->current_annotation;
86}
87
88vec4_instruction *
89vec4_visitor::emit(vec4_instruction *inst)
90{
91   this->instructions.push_tail(inst);
92
93   return inst;
94}
95
96vec4_instruction *
97vec4_visitor::emit_before(vec4_instruction *inst, vec4_instruction *new_inst)
98{
99   new_inst->ir = inst->ir;
100   new_inst->annotation = inst->annotation;
101
102   inst->insert_before(new_inst);
103
104   return inst;
105}
106
107vec4_instruction *
108vec4_visitor::emit(enum opcode opcode, dst_reg dst,
109		   src_reg src0, src_reg src1, src_reg src2)
110{
111   return emit(new(mem_ctx) vec4_instruction(this, opcode, dst,
112					     src0, src1, src2));
113}
114
115
116vec4_instruction *
117vec4_visitor::emit(enum opcode opcode, dst_reg dst, src_reg src0, src_reg src1)
118{
119   return emit(new(mem_ctx) vec4_instruction(this, opcode, dst, src0, src1));
120}
121
122vec4_instruction *
123vec4_visitor::emit(enum opcode opcode, dst_reg dst, src_reg src0)
124{
125   return emit(new(mem_ctx) vec4_instruction(this, opcode, dst, src0));
126}
127
128vec4_instruction *
129vec4_visitor::emit(enum opcode opcode)
130{
131   return emit(new(mem_ctx) vec4_instruction(this, opcode, dst_reg()));
132}
133
134#define ALU1(op)							\
135   vec4_instruction *							\
136   vec4_visitor::op(dst_reg dst, src_reg src0)				\
137   {									\
138      return new(mem_ctx) vec4_instruction(this, BRW_OPCODE_##op, dst,	\
139					   src0);			\
140   }
141
142#define ALU2(op)							\
143   vec4_instruction *							\
144   vec4_visitor::op(dst_reg dst, src_reg src0, src_reg src1)		\
145   {									\
146      return new(mem_ctx) vec4_instruction(this, BRW_OPCODE_##op, dst,	\
147					   src0, src1);			\
148   }
149
150ALU1(NOT)
151ALU1(MOV)
152ALU1(FRC)
153ALU1(RNDD)
154ALU1(RNDE)
155ALU1(RNDZ)
156ALU2(ADD)
157ALU2(MUL)
158ALU2(MACH)
159ALU2(AND)
160ALU2(OR)
161ALU2(XOR)
162ALU2(DP3)
163ALU2(DP4)
164
165/** Gen4 predicated IF. */
166vec4_instruction *
167vec4_visitor::IF(uint32_t predicate)
168{
169   vec4_instruction *inst;
170
171   inst = new(mem_ctx) vec4_instruction(this, BRW_OPCODE_IF);
172   inst->predicate = predicate;
173
174   return inst;
175}
176
177/** Gen6+ IF with embedded comparison. */
178vec4_instruction *
179vec4_visitor::IF(src_reg src0, src_reg src1, uint32_t condition)
180{
181   assert(intel->gen >= 6);
182
183   vec4_instruction *inst;
184
185   inst = new(mem_ctx) vec4_instruction(this, BRW_OPCODE_IF, dst_null_d(),
186					src0, src1);
187   inst->conditional_mod = condition;
188
189   return inst;
190}
191
192/**
193 * CMP: Sets the low bit of the destination channels with the result
194 * of the comparison, while the upper bits are undefined, and updates
195 * the flag register with the packed 16 bits of the result.
196 */
197vec4_instruction *
198vec4_visitor::CMP(dst_reg dst, src_reg src0, src_reg src1, uint32_t condition)
199{
200   vec4_instruction *inst;
201
202   /* original gen4 does type conversion to the destination type
203    * before before comparison, producing garbage results for floating
204    * point comparisons.
205    */
206   if (intel->gen == 4) {
207      dst.type = src0.type;
208      if (dst.file == HW_REG)
209	 dst.fixed_hw_reg.type = dst.type;
210   }
211
212   inst = new(mem_ctx) vec4_instruction(this, BRW_OPCODE_CMP, dst, src0, src1);
213   inst->conditional_mod = condition;
214
215   return inst;
216}
217
218vec4_instruction *
219vec4_visitor::SCRATCH_READ(dst_reg dst, src_reg index)
220{
221   vec4_instruction *inst;
222
223   inst = new(mem_ctx) vec4_instruction(this, VS_OPCODE_SCRATCH_READ,
224					dst, index);
225   inst->base_mrf = 14;
226   inst->mlen = 1;
227
228   return inst;
229}
230
231vec4_instruction *
232vec4_visitor::SCRATCH_WRITE(dst_reg dst, src_reg src, src_reg index)
233{
234   vec4_instruction *inst;
235
236   inst = new(mem_ctx) vec4_instruction(this, VS_OPCODE_SCRATCH_WRITE,
237					dst, src, index);
238   inst->base_mrf = 13;
239   inst->mlen = 2;
240
241   return inst;
242}
243
244void
245vec4_visitor::emit_dp(dst_reg dst, src_reg src0, src_reg src1, unsigned elements)
246{
247   static enum opcode dot_opcodes[] = {
248      BRW_OPCODE_DP2, BRW_OPCODE_DP3, BRW_OPCODE_DP4
249   };
250
251   emit(dot_opcodes[elements - 2], dst, src0, src1);
252}
253
254void
255vec4_visitor::emit_math1_gen6(enum opcode opcode, dst_reg dst, src_reg src)
256{
257   /* The gen6 math instruction ignores the source modifiers --
258    * swizzle, abs, negate, and at least some parts of the register
259    * region description.
260    *
261    * While it would seem that this MOV could be avoided at this point
262    * in the case that the swizzle is matched up with the destination
263    * writemask, note that uniform packing and register allocation
264    * could rearrange our swizzle, so let's leave this matter up to
265    * copy propagation later.
266    */
267   src_reg temp_src = src_reg(this, glsl_type::vec4_type);
268   emit(MOV(dst_reg(temp_src), src));
269
270   if (dst.writemask != WRITEMASK_XYZW) {
271      /* The gen6 math instruction must be align1, so we can't do
272       * writemasks.
273       */
274      dst_reg temp_dst = dst_reg(this, glsl_type::vec4_type);
275
276      emit(opcode, temp_dst, temp_src);
277
278      emit(MOV(dst, src_reg(temp_dst)));
279   } else {
280      emit(opcode, dst, temp_src);
281   }
282}
283
284void
285vec4_visitor::emit_math1_gen4(enum opcode opcode, dst_reg dst, src_reg src)
286{
287   vec4_instruction *inst = emit(opcode, dst, src);
288   inst->base_mrf = 1;
289   inst->mlen = 1;
290}
291
292void
293vec4_visitor::emit_math(opcode opcode, dst_reg dst, src_reg src)
294{
295   switch (opcode) {
296   case SHADER_OPCODE_RCP:
297   case SHADER_OPCODE_RSQ:
298   case SHADER_OPCODE_SQRT:
299   case SHADER_OPCODE_EXP2:
300   case SHADER_OPCODE_LOG2:
301   case SHADER_OPCODE_SIN:
302   case SHADER_OPCODE_COS:
303      break;
304   default:
305      assert(!"not reached: bad math opcode");
306      return;
307   }
308
309   if (intel->gen >= 6) {
310      return emit_math1_gen6(opcode, dst, src);
311   } else {
312      return emit_math1_gen4(opcode, dst, src);
313   }
314}
315
316void
317vec4_visitor::emit_math2_gen6(enum opcode opcode,
318			      dst_reg dst, src_reg src0, src_reg src1)
319{
320   src_reg expanded;
321
322   /* The gen6 math instruction ignores the source modifiers --
323    * swizzle, abs, negate, and at least some parts of the register
324    * region description.  Move the sources to temporaries to make it
325    * generally work.
326    */
327
328   expanded = src_reg(this, glsl_type::vec4_type);
329   expanded.type = src0.type;
330   emit(MOV(dst_reg(expanded), src0));
331   src0 = expanded;
332
333   expanded = src_reg(this, glsl_type::vec4_type);
334   expanded.type = src1.type;
335   emit(MOV(dst_reg(expanded), src1));
336   src1 = expanded;
337
338   if (dst.writemask != WRITEMASK_XYZW) {
339      /* The gen6 math instruction must be align1, so we can't do
340       * writemasks.
341       */
342      dst_reg temp_dst = dst_reg(this, glsl_type::vec4_type);
343      temp_dst.type = dst.type;
344
345      emit(opcode, temp_dst, src0, src1);
346
347      emit(MOV(dst, src_reg(temp_dst)));
348   } else {
349      emit(opcode, dst, src0, src1);
350   }
351}
352
353void
354vec4_visitor::emit_math2_gen4(enum opcode opcode,
355			      dst_reg dst, src_reg src0, src_reg src1)
356{
357   vec4_instruction *inst = emit(opcode, dst, src0, src1);
358   inst->base_mrf = 1;
359   inst->mlen = 2;
360}
361
362void
363vec4_visitor::emit_math(enum opcode opcode,
364			dst_reg dst, src_reg src0, src_reg src1)
365{
366   switch (opcode) {
367   case SHADER_OPCODE_POW:
368   case SHADER_OPCODE_INT_QUOTIENT:
369   case SHADER_OPCODE_INT_REMAINDER:
370      break;
371   default:
372      assert(!"not reached: unsupported binary math opcode");
373      return;
374   }
375
376   if (intel->gen >= 6) {
377      return emit_math2_gen6(opcode, dst, src0, src1);
378   } else {
379      return emit_math2_gen4(opcode, dst, src0, src1);
380   }
381}
382
383void
384vec4_visitor::visit_instructions(const exec_list *list)
385{
386   foreach_list(node, list) {
387      ir_instruction *ir = (ir_instruction *)node;
388
389      base_ir = ir;
390      ir->accept(this);
391   }
392}
393
394
395static int
396type_size(const struct glsl_type *type)
397{
398   unsigned int i;
399   int size;
400
401   switch (type->base_type) {
402   case GLSL_TYPE_UINT:
403   case GLSL_TYPE_INT:
404   case GLSL_TYPE_FLOAT:
405   case GLSL_TYPE_BOOL:
406      if (type->is_matrix()) {
407	 return type->matrix_columns;
408      } else {
409	 /* Regardless of size of vector, it gets a vec4. This is bad
410	  * packing for things like floats, but otherwise arrays become a
411	  * mess.  Hopefully a later pass over the code can pack scalars
412	  * down if appropriate.
413	  */
414	 return 1;
415      }
416   case GLSL_TYPE_ARRAY:
417      assert(type->length > 0);
418      return type_size(type->fields.array) * type->length;
419   case GLSL_TYPE_STRUCT:
420      size = 0;
421      for (i = 0; i < type->length; i++) {
422	 size += type_size(type->fields.structure[i].type);
423      }
424      return size;
425   case GLSL_TYPE_SAMPLER:
426      /* Samplers take up one slot in UNIFORMS[], but they're baked in
427       * at link time.
428       */
429      return 1;
430   default:
431      assert(0);
432      return 0;
433   }
434}
435
436int
437vec4_visitor::virtual_grf_alloc(int size)
438{
439   if (virtual_grf_array_size <= virtual_grf_count) {
440      if (virtual_grf_array_size == 0)
441	 virtual_grf_array_size = 16;
442      else
443	 virtual_grf_array_size *= 2;
444      virtual_grf_sizes = reralloc(mem_ctx, virtual_grf_sizes, int,
445				   virtual_grf_array_size);
446      virtual_grf_reg_map = reralloc(mem_ctx, virtual_grf_reg_map, int,
447				     virtual_grf_array_size);
448   }
449   virtual_grf_reg_map[virtual_grf_count] = virtual_grf_reg_count;
450   virtual_grf_reg_count += size;
451   virtual_grf_sizes[virtual_grf_count] = size;
452   return virtual_grf_count++;
453}
454
455src_reg::src_reg(class vec4_visitor *v, const struct glsl_type *type)
456{
457   init();
458
459   this->file = GRF;
460   this->reg = v->virtual_grf_alloc(type_size(type));
461
462   if (type->is_array() || type->is_record()) {
463      this->swizzle = BRW_SWIZZLE_NOOP;
464   } else {
465      this->swizzle = swizzle_for_size(type->vector_elements);
466   }
467
468   this->type = brw_type_for_base_type(type);
469}
470
471dst_reg::dst_reg(class vec4_visitor *v, const struct glsl_type *type)
472{
473   init();
474
475   this->file = GRF;
476   this->reg = v->virtual_grf_alloc(type_size(type));
477
478   if (type->is_array() || type->is_record()) {
479      this->writemask = WRITEMASK_XYZW;
480   } else {
481      this->writemask = (1 << type->vector_elements) - 1;
482   }
483
484   this->type = brw_type_for_base_type(type);
485}
486
487/* Our support for uniforms is piggy-backed on the struct
488 * gl_fragment_program, because that's where the values actually
489 * get stored, rather than in some global gl_shader_program uniform
490 * store.
491 */
492int
493vec4_visitor::setup_uniform_values(int loc, const glsl_type *type)
494{
495   unsigned int offset = 0;
496   float *values = &this->vp->Base.Parameters->ParameterValues[loc][0].f;
497
498   if (type->is_matrix()) {
499      const glsl_type *column = glsl_type::get_instance(GLSL_TYPE_FLOAT,
500							type->vector_elements,
501							1);
502
503      for (unsigned int i = 0; i < type->matrix_columns; i++) {
504	 offset += setup_uniform_values(loc + offset, column);
505      }
506
507      return offset;
508   }
509
510   switch (type->base_type) {
511   case GLSL_TYPE_FLOAT:
512   case GLSL_TYPE_UINT:
513   case GLSL_TYPE_INT:
514   case GLSL_TYPE_BOOL:
515      for (unsigned int i = 0; i < type->vector_elements; i++) {
516	 c->prog_data.param[this->uniforms * 4 + i] = &values[i];
517      }
518
519      /* Set up pad elements to get things aligned to a vec4 boundary. */
520      for (unsigned int i = type->vector_elements; i < 4; i++) {
521	 static float zero = 0;
522
523	 c->prog_data.param[this->uniforms * 4 + i] = &zero;
524      }
525
526      /* Track the size of this uniform vector, for future packing of
527       * uniforms.
528       */
529      this->uniform_vector_size[this->uniforms] = type->vector_elements;
530      this->uniforms++;
531
532      return 1;
533
534   case GLSL_TYPE_STRUCT:
535      for (unsigned int i = 0; i < type->length; i++) {
536	 offset += setup_uniform_values(loc + offset,
537					type->fields.structure[i].type);
538      }
539      return offset;
540
541   case GLSL_TYPE_ARRAY:
542      for (unsigned int i = 0; i < type->length; i++) {
543	 offset += setup_uniform_values(loc + offset, type->fields.array);
544      }
545      return offset;
546
547   case GLSL_TYPE_SAMPLER:
548      /* The sampler takes up a slot, but we don't use any values from it. */
549      return 1;
550
551   default:
552      assert(!"not reached");
553      return 0;
554   }
555}
556
557void
558vec4_visitor::setup_uniform_clipplane_values()
559{
560   gl_clip_plane *clip_planes = brw_select_clip_planes(ctx);
561
562   /* Pre-Gen6, we compact clip planes.  For example, if the user
563    * enables just clip planes 0, 1, and 3, we will enable clip planes
564    * 0, 1, and 2 in the hardware, and we'll move clip plane 3 to clip
565    * plane 2.  This simplifies the implementation of the Gen6 clip
566    * thread.
567    *
568    * In Gen6 and later, we don't compact clip planes, because this
569    * simplifies the implementation of gl_ClipDistance.
570    */
571   int compacted_clipplane_index = 0;
572   for (int i = 0; i < c->key.nr_userclip_plane_consts; ++i) {
573      if (intel->gen < 6 &&
574          !(c->key.userclip_planes_enabled_gen_4_5 & (1 << i))) {
575         continue;
576      }
577      this->uniform_vector_size[this->uniforms] = 4;
578      this->userplane[compacted_clipplane_index] = dst_reg(UNIFORM, this->uniforms);
579      this->userplane[compacted_clipplane_index].type = BRW_REGISTER_TYPE_F;
580      for (int j = 0; j < 4; ++j) {
581         c->prog_data.param[this->uniforms * 4 + j] = &clip_planes[i][j];
582      }
583      ++compacted_clipplane_index;
584      ++this->uniforms;
585   }
586}
587
588/* Our support for builtin uniforms is even scarier than non-builtin.
589 * It sits on top of the PROG_STATE_VAR parameters that are
590 * automatically updated from GL context state.
591 */
592void
593vec4_visitor::setup_builtin_uniform_values(ir_variable *ir)
594{
595   const ir_state_slot *const slots = ir->state_slots;
596   assert(ir->state_slots != NULL);
597
598   for (unsigned int i = 0; i < ir->num_state_slots; i++) {
599      /* This state reference has already been setup by ir_to_mesa,
600       * but we'll get the same index back here.  We can reference
601       * ParameterValues directly, since unlike brw_fs.cpp, we never
602       * add new state references during compile.
603       */
604      int index = _mesa_add_state_reference(this->vp->Base.Parameters,
605					    (gl_state_index *)slots[i].tokens);
606      float *values = &this->vp->Base.Parameters->ParameterValues[index][0].f;
607
608      this->uniform_vector_size[this->uniforms] = 0;
609      /* Add each of the unique swizzled channels of the element.
610       * This will end up matching the size of the glsl_type of this field.
611       */
612      int last_swiz = -1;
613      for (unsigned int j = 0; j < 4; j++) {
614	 int swiz = GET_SWZ(slots[i].swizzle, j);
615	 last_swiz = swiz;
616
617	 c->prog_data.param[this->uniforms * 4 + j] = &values[swiz];
618	 if (swiz <= last_swiz)
619	    this->uniform_vector_size[this->uniforms]++;
620      }
621      this->uniforms++;
622   }
623}
624
625dst_reg *
626vec4_visitor::variable_storage(ir_variable *var)
627{
628   return (dst_reg *)hash_table_find(this->variable_ht, var);
629}
630
631void
632vec4_visitor::emit_bool_to_cond_code(ir_rvalue *ir, uint32_t *predicate)
633{
634   ir_expression *expr = ir->as_expression();
635
636   *predicate = BRW_PREDICATE_NORMAL;
637
638   if (expr) {
639      src_reg op[2];
640      vec4_instruction *inst;
641
642      assert(expr->get_num_operands() <= 2);
643      for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
644	 expr->operands[i]->accept(this);
645	 op[i] = this->result;
646      }
647
648      switch (expr->operation) {
649      case ir_unop_logic_not:
650	 inst = emit(AND(dst_null_d(), op[0], src_reg(1)));
651	 inst->conditional_mod = BRW_CONDITIONAL_Z;
652	 break;
653
654      case ir_binop_logic_xor:
655	 inst = emit(XOR(dst_null_d(), op[0], op[1]));
656	 inst->conditional_mod = BRW_CONDITIONAL_NZ;
657	 break;
658
659      case ir_binop_logic_or:
660	 inst = emit(OR(dst_null_d(), op[0], op[1]));
661	 inst->conditional_mod = BRW_CONDITIONAL_NZ;
662	 break;
663
664      case ir_binop_logic_and:
665	 inst = emit(AND(dst_null_d(), op[0], op[1]));
666	 inst->conditional_mod = BRW_CONDITIONAL_NZ;
667	 break;
668
669      case ir_unop_f2b:
670	 if (intel->gen >= 6) {
671	    emit(CMP(dst_null_d(), op[0], src_reg(0.0f), BRW_CONDITIONAL_NZ));
672	 } else {
673	    inst = emit(MOV(dst_null_f(), op[0]));
674	    inst->conditional_mod = BRW_CONDITIONAL_NZ;
675	 }
676	 break;
677
678      case ir_unop_i2b:
679	 if (intel->gen >= 6) {
680	    emit(CMP(dst_null_d(), op[0], src_reg(0), BRW_CONDITIONAL_NZ));
681	 } else {
682	    inst = emit(MOV(dst_null_d(), op[0]));
683	    inst->conditional_mod = BRW_CONDITIONAL_NZ;
684	 }
685	 break;
686
687      case ir_binop_all_equal:
688	 inst = emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_Z));
689	 *predicate = BRW_PREDICATE_ALIGN16_ALL4H;
690	 break;
691
692      case ir_binop_any_nequal:
693	 inst = emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_NZ));
694	 *predicate = BRW_PREDICATE_ALIGN16_ANY4H;
695	 break;
696
697      case ir_unop_any:
698	 inst = emit(CMP(dst_null_d(), op[0], src_reg(0), BRW_CONDITIONAL_NZ));
699	 *predicate = BRW_PREDICATE_ALIGN16_ANY4H;
700	 break;
701
702      case ir_binop_greater:
703      case ir_binop_gequal:
704      case ir_binop_less:
705      case ir_binop_lequal:
706      case ir_binop_equal:
707      case ir_binop_nequal:
708	 emit(CMP(dst_null_d(), op[0], op[1],
709		  brw_conditional_for_comparison(expr->operation)));
710	 break;
711
712      default:
713	 assert(!"not reached");
714	 break;
715      }
716      return;
717   }
718
719   ir->accept(this);
720
721   if (intel->gen >= 6) {
722      vec4_instruction *inst = emit(AND(dst_null_d(),
723					this->result, src_reg(1)));
724      inst->conditional_mod = BRW_CONDITIONAL_NZ;
725   } else {
726      vec4_instruction *inst = emit(MOV(dst_null_d(), this->result));
727      inst->conditional_mod = BRW_CONDITIONAL_NZ;
728   }
729}
730
731/**
732 * Emit a gen6 IF statement with the comparison folded into the IF
733 * instruction.
734 */
735void
736vec4_visitor::emit_if_gen6(ir_if *ir)
737{
738   ir_expression *expr = ir->condition->as_expression();
739
740   if (expr) {
741      src_reg op[2];
742      dst_reg temp;
743
744      assert(expr->get_num_operands() <= 2);
745      for (unsigned int i = 0; i < expr->get_num_operands(); i++) {
746	 expr->operands[i]->accept(this);
747	 op[i] = this->result;
748      }
749
750      switch (expr->operation) {
751      case ir_unop_logic_not:
752	 emit(IF(op[0], src_reg(0), BRW_CONDITIONAL_Z));
753	 return;
754
755      case ir_binop_logic_xor:
756	 emit(IF(op[0], op[1], BRW_CONDITIONAL_NZ));
757	 return;
758
759      case ir_binop_logic_or:
760	 temp = dst_reg(this, glsl_type::bool_type);
761	 emit(OR(temp, op[0], op[1]));
762	 emit(IF(src_reg(temp), src_reg(0), BRW_CONDITIONAL_NZ));
763	 return;
764
765      case ir_binop_logic_and:
766	 temp = dst_reg(this, glsl_type::bool_type);
767	 emit(AND(temp, op[0], op[1]));
768	 emit(IF(src_reg(temp), src_reg(0), BRW_CONDITIONAL_NZ));
769	 return;
770
771      case ir_unop_f2b:
772	 emit(IF(op[0], src_reg(0), BRW_CONDITIONAL_NZ));
773	 return;
774
775      case ir_unop_i2b:
776	 emit(IF(op[0], src_reg(0), BRW_CONDITIONAL_NZ));
777	 return;
778
779      case ir_binop_greater:
780      case ir_binop_gequal:
781      case ir_binop_less:
782      case ir_binop_lequal:
783      case ir_binop_equal:
784      case ir_binop_nequal:
785	 emit(IF(op[0], op[1],
786		 brw_conditional_for_comparison(expr->operation)));
787	 return;
788
789      case ir_binop_all_equal:
790	 emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_Z));
791	 emit(IF(BRW_PREDICATE_ALIGN16_ALL4H));
792	 return;
793
794      case ir_binop_any_nequal:
795	 emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_NZ));
796	 emit(IF(BRW_PREDICATE_ALIGN16_ANY4H));
797	 return;
798
799      case ir_unop_any:
800	 emit(CMP(dst_null_d(), op[0], src_reg(0), BRW_CONDITIONAL_NZ));
801	 emit(IF(BRW_PREDICATE_ALIGN16_ANY4H));
802	 return;
803
804      default:
805	 assert(!"not reached");
806	 emit(IF(op[0], src_reg(0), BRW_CONDITIONAL_NZ));
807	 return;
808      }
809      return;
810   }
811
812   ir->condition->accept(this);
813
814   emit(IF(this->result, src_reg(0), BRW_CONDITIONAL_NZ));
815}
816
817void
818vec4_visitor::visit(ir_variable *ir)
819{
820   dst_reg *reg = NULL;
821
822   if (variable_storage(ir))
823      return;
824
825   switch (ir->mode) {
826   case ir_var_in:
827      reg = new(mem_ctx) dst_reg(ATTR, ir->location);
828
829      /* Do GL_FIXED rescaling for GLES2.0.  Our GL_FIXED attributes
830       * come in as floating point conversions of the integer values.
831       */
832      for (int i = ir->location; i < ir->location + type_size(ir->type); i++) {
833	 if (!c->key.gl_fixed_input_size[i])
834	    continue;
835
836	 dst_reg dst = *reg;
837	 dst.writemask = (1 << c->key.gl_fixed_input_size[i]) - 1;
838	 emit(MUL(dst, src_reg(dst), src_reg(1.0f / 65536.0f)));
839      }
840      break;
841
842   case ir_var_out:
843      reg = new(mem_ctx) dst_reg(this, ir->type);
844
845      for (int i = 0; i < type_size(ir->type); i++) {
846	 output_reg[ir->location + i] = *reg;
847	 output_reg[ir->location + i].reg_offset = i;
848	 output_reg[ir->location + i].type = BRW_REGISTER_TYPE_F;
849	 output_reg_annotation[ir->location + i] = ir->name;
850      }
851      break;
852
853   case ir_var_auto:
854   case ir_var_temporary:
855      reg = new(mem_ctx) dst_reg(this, ir->type);
856      break;
857
858   case ir_var_uniform:
859      reg = new(this->mem_ctx) dst_reg(UNIFORM, this->uniforms);
860
861      /* Track how big the whole uniform variable is, in case we need to put a
862       * copy of its data into pull constants for array access.
863       */
864      this->uniform_size[this->uniforms] = type_size(ir->type);
865
866      if (!strncmp(ir->name, "gl_", 3)) {
867	 setup_builtin_uniform_values(ir);
868      } else {
869	 setup_uniform_values(ir->location, ir->type);
870      }
871      break;
872
873   default:
874      assert(!"not reached");
875   }
876
877   reg->type = brw_type_for_base_type(ir->type);
878   hash_table_insert(this->variable_ht, reg, ir);
879}
880
881void
882vec4_visitor::visit(ir_loop *ir)
883{
884   dst_reg counter;
885
886   /* We don't want debugging output to print the whole body of the
887    * loop as the annotation.
888    */
889   this->base_ir = NULL;
890
891   if (ir->counter != NULL) {
892      this->base_ir = ir->counter;
893      ir->counter->accept(this);
894      counter = *(variable_storage(ir->counter));
895
896      if (ir->from != NULL) {
897	 this->base_ir = ir->from;
898	 ir->from->accept(this);
899
900	 emit(MOV(counter, this->result));
901      }
902   }
903
904   emit(BRW_OPCODE_DO);
905
906   if (ir->to) {
907      this->base_ir = ir->to;
908      ir->to->accept(this);
909
910      emit(CMP(dst_null_d(), src_reg(counter), this->result,
911	       brw_conditional_for_comparison(ir->cmp)));
912
913      vec4_instruction *inst = emit(BRW_OPCODE_BREAK);
914      inst->predicate = BRW_PREDICATE_NORMAL;
915   }
916
917   visit_instructions(&ir->body_instructions);
918
919
920   if (ir->increment) {
921      this->base_ir = ir->increment;
922      ir->increment->accept(this);
923      emit(ADD(counter, src_reg(counter), this->result));
924   }
925
926   emit(BRW_OPCODE_WHILE);
927}
928
929void
930vec4_visitor::visit(ir_loop_jump *ir)
931{
932   switch (ir->mode) {
933   case ir_loop_jump::jump_break:
934      emit(BRW_OPCODE_BREAK);
935      break;
936   case ir_loop_jump::jump_continue:
937      emit(BRW_OPCODE_CONTINUE);
938      break;
939   }
940}
941
942
943void
944vec4_visitor::visit(ir_function_signature *ir)
945{
946   assert(0);
947   (void)ir;
948}
949
950void
951vec4_visitor::visit(ir_function *ir)
952{
953   /* Ignore function bodies other than main() -- we shouldn't see calls to
954    * them since they should all be inlined.
955    */
956   if (strcmp(ir->name, "main") == 0) {
957      const ir_function_signature *sig;
958      exec_list empty;
959
960      sig = ir->matching_signature(&empty);
961
962      assert(sig);
963
964      visit_instructions(&sig->body);
965   }
966}
967
968GLboolean
969vec4_visitor::try_emit_sat(ir_expression *ir)
970{
971   ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
972   if (!sat_src)
973      return false;
974
975   sat_src->accept(this);
976   src_reg src = this->result;
977
978   this->result = src_reg(this, ir->type);
979   vec4_instruction *inst;
980   inst = emit(MOV(dst_reg(this->result), src));
981   inst->saturate = true;
982
983   return true;
984}
985
986void
987vec4_visitor::emit_bool_comparison(unsigned int op,
988				 dst_reg dst, src_reg src0, src_reg src1)
989{
990   /* original gen4 does destination conversion before comparison. */
991   if (intel->gen < 5)
992      dst.type = src0.type;
993
994   emit(CMP(dst, src0, src1, brw_conditional_for_comparison(op)));
995
996   dst.type = BRW_REGISTER_TYPE_D;
997   emit(AND(dst, src_reg(dst), src_reg(0x1)));
998}
999
1000void
1001vec4_visitor::visit(ir_expression *ir)
1002{
1003   unsigned int operand;
1004   src_reg op[Elements(ir->operands)];
1005   src_reg result_src;
1006   dst_reg result_dst;
1007   vec4_instruction *inst;
1008
1009   if (try_emit_sat(ir))
1010      return;
1011
1012   for (operand = 0; operand < ir->get_num_operands(); operand++) {
1013      this->result.file = BAD_FILE;
1014      ir->operands[operand]->accept(this);
1015      if (this->result.file == BAD_FILE) {
1016	 printf("Failed to get tree for expression operand:\n");
1017	 ir->operands[operand]->print();
1018	 exit(1);
1019      }
1020      op[operand] = this->result;
1021
1022      /* Matrix expression operands should have been broken down to vector
1023       * operations already.
1024       */
1025      assert(!ir->operands[operand]->type->is_matrix());
1026   }
1027
1028   int vector_elements = ir->operands[0]->type->vector_elements;
1029   if (ir->operands[1]) {
1030      vector_elements = MAX2(vector_elements,
1031			     ir->operands[1]->type->vector_elements);
1032   }
1033
1034   this->result.file = BAD_FILE;
1035
1036   /* Storage for our result.  Ideally for an assignment we'd be using
1037    * the actual storage for the result here, instead.
1038    */
1039   result_src = src_reg(this, ir->type);
1040   /* convenience for the emit functions below. */
1041   result_dst = dst_reg(result_src);
1042   /* If nothing special happens, this is the result. */
1043   this->result = result_src;
1044   /* Limit writes to the channels that will be used by result_src later.
1045    * This does limit this temp's use as a temporary for multi-instruction
1046    * sequences.
1047    */
1048   result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1049
1050   switch (ir->operation) {
1051   case ir_unop_logic_not:
1052      /* Note that BRW_OPCODE_NOT is not appropriate here, since it is
1053       * ones complement of the whole register, not just bit 0.
1054       */
1055      emit(XOR(result_dst, op[0], src_reg(1)));
1056      break;
1057   case ir_unop_neg:
1058      op[0].negate = !op[0].negate;
1059      this->result = op[0];
1060      break;
1061   case ir_unop_abs:
1062      op[0].abs = true;
1063      op[0].negate = false;
1064      this->result = op[0];
1065      break;
1066
1067   case ir_unop_sign:
1068      emit(MOV(result_dst, src_reg(0.0f)));
1069
1070      emit(CMP(dst_null_d(), op[0], src_reg(0.0f), BRW_CONDITIONAL_G));
1071      inst = emit(MOV(result_dst, src_reg(1.0f)));
1072      inst->predicate = BRW_PREDICATE_NORMAL;
1073
1074      emit(CMP(dst_null_d(), op[0], src_reg(0.0f), BRW_CONDITIONAL_L));
1075      inst = emit(MOV(result_dst, src_reg(-1.0f)));
1076      inst->predicate = BRW_PREDICATE_NORMAL;
1077
1078      break;
1079
1080   case ir_unop_rcp:
1081      emit_math(SHADER_OPCODE_RCP, result_dst, op[0]);
1082      break;
1083
1084   case ir_unop_exp2:
1085      emit_math(SHADER_OPCODE_EXP2, result_dst, op[0]);
1086      break;
1087   case ir_unop_log2:
1088      emit_math(SHADER_OPCODE_LOG2, result_dst, op[0]);
1089      break;
1090   case ir_unop_exp:
1091   case ir_unop_log:
1092      assert(!"not reached: should be handled by ir_explog_to_explog2");
1093      break;
1094   case ir_unop_sin:
1095   case ir_unop_sin_reduced:
1096      emit_math(SHADER_OPCODE_SIN, result_dst, op[0]);
1097      break;
1098   case ir_unop_cos:
1099   case ir_unop_cos_reduced:
1100      emit_math(SHADER_OPCODE_COS, result_dst, op[0]);
1101      break;
1102
1103   case ir_unop_dFdx:
1104   case ir_unop_dFdy:
1105      assert(!"derivatives not valid in vertex shader");
1106      break;
1107
1108   case ir_unop_noise:
1109      assert(!"not reached: should be handled by lower_noise");
1110      break;
1111
1112   case ir_binop_add:
1113      emit(ADD(result_dst, op[0], op[1]));
1114      break;
1115   case ir_binop_sub:
1116      assert(!"not reached: should be handled by ir_sub_to_add_neg");
1117      break;
1118
1119   case ir_binop_mul:
1120      if (ir->type->is_integer()) {
1121	 /* For integer multiplication, the MUL uses the low 16 bits
1122	  * of one of the operands (src0 on gen6, src1 on gen7).  The
1123	  * MACH accumulates in the contribution of the upper 16 bits
1124	  * of that operand.
1125	  *
1126	  * FINISHME: Emit just the MUL if we know an operand is small
1127	  * enough.
1128	  */
1129	 struct brw_reg acc = retype(brw_acc_reg(), BRW_REGISTER_TYPE_D);
1130
1131	 emit(MUL(acc, op[0], op[1]));
1132	 emit(MACH(dst_null_d(), op[0], op[1]));
1133	 emit(MOV(result_dst, src_reg(acc)));
1134      } else {
1135	 emit(MUL(result_dst, op[0], op[1]));
1136      }
1137      break;
1138   case ir_binop_div:
1139      /* Floating point should be lowered by DIV_TO_MUL_RCP in the compiler. */
1140      assert(ir->type->is_integer());
1141      emit_math(SHADER_OPCODE_INT_QUOTIENT, result_dst, op[0], op[1]);
1142      break;
1143   case ir_binop_mod:
1144      /* Floating point should be lowered by MOD_TO_FRACT in the compiler. */
1145      assert(ir->type->is_integer());
1146      emit_math(SHADER_OPCODE_INT_REMAINDER, result_dst, op[0], op[1]);
1147      break;
1148
1149   case ir_binop_less:
1150   case ir_binop_greater:
1151   case ir_binop_lequal:
1152   case ir_binop_gequal:
1153   case ir_binop_equal:
1154   case ir_binop_nequal: {
1155      emit(CMP(result_dst, op[0], op[1],
1156	       brw_conditional_for_comparison(ir->operation)));
1157      emit(AND(result_dst, result_src, src_reg(0x1)));
1158      break;
1159   }
1160
1161   case ir_binop_all_equal:
1162      /* "==" operator producing a scalar boolean. */
1163      if (ir->operands[0]->type->is_vector() ||
1164	  ir->operands[1]->type->is_vector()) {
1165	 emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_Z));
1166	 emit(MOV(result_dst, src_reg(0)));
1167	 inst = emit(MOV(result_dst, src_reg(1)));
1168	 inst->predicate = BRW_PREDICATE_ALIGN16_ALL4H;
1169      } else {
1170	 emit(CMP(result_dst, op[0], op[1], BRW_CONDITIONAL_Z));
1171	 emit(AND(result_dst, result_src, src_reg(0x1)));
1172      }
1173      break;
1174   case ir_binop_any_nequal:
1175      /* "!=" operator producing a scalar boolean. */
1176      if (ir->operands[0]->type->is_vector() ||
1177	  ir->operands[1]->type->is_vector()) {
1178	 emit(CMP(dst_null_d(), op[0], op[1], BRW_CONDITIONAL_NZ));
1179
1180	 emit(MOV(result_dst, src_reg(0)));
1181	 inst = emit(MOV(result_dst, src_reg(1)));
1182	 inst->predicate = BRW_PREDICATE_ALIGN16_ANY4H;
1183      } else {
1184	 emit(CMP(result_dst, op[0], op[1], BRW_CONDITIONAL_NZ));
1185	 emit(AND(result_dst, result_src, src_reg(0x1)));
1186      }
1187      break;
1188
1189   case ir_unop_any:
1190      emit(CMP(dst_null_d(), op[0], src_reg(0), BRW_CONDITIONAL_NZ));
1191      emit(MOV(result_dst, src_reg(0)));
1192
1193      inst = emit(MOV(result_dst, src_reg(1)));
1194      inst->predicate = BRW_PREDICATE_ALIGN16_ANY4H;
1195      break;
1196
1197   case ir_binop_logic_xor:
1198      emit(XOR(result_dst, op[0], op[1]));
1199      break;
1200
1201   case ir_binop_logic_or:
1202      emit(OR(result_dst, op[0], op[1]));
1203      break;
1204
1205   case ir_binop_logic_and:
1206      emit(AND(result_dst, op[0], op[1]));
1207      break;
1208
1209   case ir_binop_dot:
1210      assert(ir->operands[0]->type->is_vector());
1211      assert(ir->operands[0]->type == ir->operands[1]->type);
1212      emit_dp(result_dst, op[0], op[1], ir->operands[0]->type->vector_elements);
1213      break;
1214
1215   case ir_unop_sqrt:
1216      emit_math(SHADER_OPCODE_SQRT, result_dst, op[0]);
1217      break;
1218   case ir_unop_rsq:
1219      emit_math(SHADER_OPCODE_RSQ, result_dst, op[0]);
1220      break;
1221   case ir_unop_i2f:
1222   case ir_unop_i2u:
1223   case ir_unop_u2i:
1224   case ir_unop_u2f:
1225   case ir_unop_b2f:
1226   case ir_unop_b2i:
1227   case ir_unop_f2i:
1228      emit(MOV(result_dst, op[0]));
1229      break;
1230   case ir_unop_f2b:
1231   case ir_unop_i2b: {
1232      emit(CMP(result_dst, op[0], src_reg(0.0f), BRW_CONDITIONAL_NZ));
1233      emit(AND(result_dst, result_src, src_reg(1)));
1234      break;
1235   }
1236
1237   case ir_unop_trunc:
1238      emit(RNDZ(result_dst, op[0]));
1239      break;
1240   case ir_unop_ceil:
1241      op[0].negate = !op[0].negate;
1242      inst = emit(RNDD(result_dst, op[0]));
1243      this->result.negate = true;
1244      break;
1245   case ir_unop_floor:
1246      inst = emit(RNDD(result_dst, op[0]));
1247      break;
1248   case ir_unop_fract:
1249      inst = emit(FRC(result_dst, op[0]));
1250      break;
1251   case ir_unop_round_even:
1252      emit(RNDE(result_dst, op[0]));
1253      break;
1254
1255   case ir_binop_min:
1256      emit(CMP(result_dst, op[0], op[1], BRW_CONDITIONAL_L));
1257
1258      inst = emit(BRW_OPCODE_SEL, result_dst, op[0], op[1]);
1259      inst->predicate = BRW_PREDICATE_NORMAL;
1260      break;
1261   case ir_binop_max:
1262      emit(CMP(result_dst, op[0], op[1], BRW_CONDITIONAL_G));
1263
1264      inst = emit(BRW_OPCODE_SEL, result_dst, op[0], op[1]);
1265      inst->predicate = BRW_PREDICATE_NORMAL;
1266      break;
1267
1268   case ir_binop_pow:
1269      emit_math(SHADER_OPCODE_POW, result_dst, op[0], op[1]);
1270      break;
1271
1272   case ir_unop_bit_not:
1273      inst = emit(NOT(result_dst, op[0]));
1274      break;
1275   case ir_binop_bit_and:
1276      inst = emit(AND(result_dst, op[0], op[1]));
1277      break;
1278   case ir_binop_bit_xor:
1279      inst = emit(XOR(result_dst, op[0], op[1]));
1280      break;
1281   case ir_binop_bit_or:
1282      inst = emit(OR(result_dst, op[0], op[1]));
1283      break;
1284
1285   case ir_binop_lshift:
1286      inst = emit(BRW_OPCODE_SHL, result_dst, op[0], op[1]);
1287      break;
1288
1289   case ir_binop_rshift:
1290      if (ir->type->base_type == GLSL_TYPE_INT)
1291	 inst = emit(BRW_OPCODE_ASR, result_dst, op[0], op[1]);
1292      else
1293	 inst = emit(BRW_OPCODE_SHR, result_dst, op[0], op[1]);
1294      break;
1295
1296   case ir_quadop_vector:
1297      assert(!"not reached: should be handled by lower_quadop_vector");
1298      break;
1299   }
1300}
1301
1302
1303void
1304vec4_visitor::visit(ir_swizzle *ir)
1305{
1306   src_reg src;
1307   int i = 0;
1308   int swizzle[4];
1309
1310   /* Note that this is only swizzles in expressions, not those on the left
1311    * hand side of an assignment, which do write masking.  See ir_assignment
1312    * for that.
1313    */
1314
1315   ir->val->accept(this);
1316   src = this->result;
1317   assert(src.file != BAD_FILE);
1318
1319   for (i = 0; i < ir->type->vector_elements; i++) {
1320      switch (i) {
1321      case 0:
1322	 swizzle[i] = BRW_GET_SWZ(src.swizzle, ir->mask.x);
1323	 break;
1324      case 1:
1325	 swizzle[i] = BRW_GET_SWZ(src.swizzle, ir->mask.y);
1326	 break;
1327      case 2:
1328	 swizzle[i] = BRW_GET_SWZ(src.swizzle, ir->mask.z);
1329	 break;
1330      case 3:
1331	 swizzle[i] = BRW_GET_SWZ(src.swizzle, ir->mask.w);
1332	    break;
1333      }
1334   }
1335   for (; i < 4; i++) {
1336      /* Replicate the last channel out. */
1337      swizzle[i] = swizzle[ir->type->vector_elements - 1];
1338   }
1339
1340   src.swizzle = BRW_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
1341
1342   this->result = src;
1343}
1344
1345void
1346vec4_visitor::visit(ir_dereference_variable *ir)
1347{
1348   const struct glsl_type *type = ir->type;
1349   dst_reg *reg = variable_storage(ir->var);
1350
1351   if (!reg) {
1352      fail("Failed to find variable storage for %s\n", ir->var->name);
1353      this->result = src_reg(brw_null_reg());
1354      return;
1355   }
1356
1357   this->result = src_reg(*reg);
1358
1359   if (type->is_scalar() || type->is_vector() || type->is_matrix())
1360      this->result.swizzle = swizzle_for_size(type->vector_elements);
1361}
1362
1363void
1364vec4_visitor::visit(ir_dereference_array *ir)
1365{
1366   ir_constant *constant_index;
1367   src_reg src;
1368   int element_size = type_size(ir->type);
1369
1370   constant_index = ir->array_index->constant_expression_value();
1371
1372   ir->array->accept(this);
1373   src = this->result;
1374
1375   if (constant_index) {
1376      src.reg_offset += constant_index->value.i[0] * element_size;
1377   } else {
1378      /* Variable index array dereference.  It eats the "vec4" of the
1379       * base of the array and an index that offsets the Mesa register
1380       * index.
1381       */
1382      ir->array_index->accept(this);
1383
1384      src_reg index_reg;
1385
1386      if (element_size == 1) {
1387	 index_reg = this->result;
1388      } else {
1389	 index_reg = src_reg(this, glsl_type::int_type);
1390
1391	 emit(MUL(dst_reg(index_reg), this->result, src_reg(element_size)));
1392      }
1393
1394      if (src.reladdr) {
1395	 src_reg temp = src_reg(this, glsl_type::int_type);
1396
1397	 emit(ADD(dst_reg(temp), *src.reladdr, index_reg));
1398
1399	 index_reg = temp;
1400      }
1401
1402      src.reladdr = ralloc(mem_ctx, src_reg);
1403      memcpy(src.reladdr, &index_reg, sizeof(index_reg));
1404   }
1405
1406   /* If the type is smaller than a vec4, replicate the last channel out. */
1407   if (ir->type->is_scalar() || ir->type->is_vector())
1408      src.swizzle = swizzle_for_size(ir->type->vector_elements);
1409   else
1410      src.swizzle = BRW_SWIZZLE_NOOP;
1411   src.type = brw_type_for_base_type(ir->type);
1412
1413   this->result = src;
1414}
1415
1416void
1417vec4_visitor::visit(ir_dereference_record *ir)
1418{
1419   unsigned int i;
1420   const glsl_type *struct_type = ir->record->type;
1421   int offset = 0;
1422
1423   ir->record->accept(this);
1424
1425   for (i = 0; i < struct_type->length; i++) {
1426      if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1427	 break;
1428      offset += type_size(struct_type->fields.structure[i].type);
1429   }
1430
1431   /* If the type is smaller than a vec4, replicate the last channel out. */
1432   if (ir->type->is_scalar() || ir->type->is_vector())
1433      this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1434   else
1435      this->result.swizzle = BRW_SWIZZLE_NOOP;
1436   this->result.type = brw_type_for_base_type(ir->type);
1437
1438   this->result.reg_offset += offset;
1439}
1440
1441/**
1442 * We want to be careful in assignment setup to hit the actual storage
1443 * instead of potentially using a temporary like we might with the
1444 * ir_dereference handler.
1445 */
1446static dst_reg
1447get_assignment_lhs(ir_dereference *ir, vec4_visitor *v)
1448{
1449   /* The LHS must be a dereference.  If the LHS is a variable indexed array
1450    * access of a vector, it must be separated into a series conditional moves
1451    * before reaching this point (see ir_vec_index_to_cond_assign).
1452    */
1453   assert(ir->as_dereference());
1454   ir_dereference_array *deref_array = ir->as_dereference_array();
1455   if (deref_array) {
1456      assert(!deref_array->array->type->is_vector());
1457   }
1458
1459   /* Use the rvalue deref handler for the most part.  We'll ignore
1460    * swizzles in it and write swizzles using writemask, though.
1461    */
1462   ir->accept(v);
1463   return dst_reg(v->result);
1464}
1465
1466void
1467vec4_visitor::emit_block_move(dst_reg *dst, src_reg *src,
1468			      const struct glsl_type *type, uint32_t predicate)
1469{
1470   if (type->base_type == GLSL_TYPE_STRUCT) {
1471      for (unsigned int i = 0; i < type->length; i++) {
1472	 emit_block_move(dst, src, type->fields.structure[i].type, predicate);
1473      }
1474      return;
1475   }
1476
1477   if (type->is_array()) {
1478      for (unsigned int i = 0; i < type->length; i++) {
1479	 emit_block_move(dst, src, type->fields.array, predicate);
1480      }
1481      return;
1482   }
1483
1484   if (type->is_matrix()) {
1485      const struct glsl_type *vec_type;
1486
1487      vec_type = glsl_type::get_instance(GLSL_TYPE_FLOAT,
1488					 type->vector_elements, 1);
1489
1490      for (int i = 0; i < type->matrix_columns; i++) {
1491	 emit_block_move(dst, src, vec_type, predicate);
1492      }
1493      return;
1494   }
1495
1496   assert(type->is_scalar() || type->is_vector());
1497
1498   dst->type = brw_type_for_base_type(type);
1499   src->type = dst->type;
1500
1501   dst->writemask = (1 << type->vector_elements) - 1;
1502
1503   /* Do we need to worry about swizzling a swizzle? */
1504   assert(src->swizzle == BRW_SWIZZLE_NOOP
1505	  || src->swizzle == swizzle_for_size(type->vector_elements));
1506   src->swizzle = swizzle_for_size(type->vector_elements);
1507
1508   vec4_instruction *inst = emit(MOV(*dst, *src));
1509   inst->predicate = predicate;
1510
1511   dst->reg_offset++;
1512   src->reg_offset++;
1513}
1514
1515
1516/* If the RHS processing resulted in an instruction generating a
1517 * temporary value, and it would be easy to rewrite the instruction to
1518 * generate its result right into the LHS instead, do so.  This ends
1519 * up reliably removing instructions where it can be tricky to do so
1520 * later without real UD chain information.
1521 */
1522bool
1523vec4_visitor::try_rewrite_rhs_to_dst(ir_assignment *ir,
1524				     dst_reg dst,
1525				     src_reg src,
1526				     vec4_instruction *pre_rhs_inst,
1527				     vec4_instruction *last_rhs_inst)
1528{
1529   /* This could be supported, but it would take more smarts. */
1530   if (ir->condition)
1531      return false;
1532
1533   if (pre_rhs_inst == last_rhs_inst)
1534      return false; /* No instructions generated to work with. */
1535
1536   /* Make sure the last instruction generated our source reg. */
1537   if (src.file != GRF ||
1538       src.file != last_rhs_inst->dst.file ||
1539       src.reg != last_rhs_inst->dst.reg ||
1540       src.reg_offset != last_rhs_inst->dst.reg_offset ||
1541       src.reladdr ||
1542       src.abs ||
1543       src.negate ||
1544       last_rhs_inst->predicate != BRW_PREDICATE_NONE)
1545      return false;
1546
1547   /* Check that that last instruction fully initialized the channels
1548    * we want to use, in the order we want to use them.  We could
1549    * potentially reswizzle the operands of many instructions so that
1550    * we could handle out of order channels, but don't yet.
1551    */
1552   for (int i = 0; i < 4; i++) {
1553      if (dst.writemask & (1 << i)) {
1554	 if (!(last_rhs_inst->dst.writemask & (1 << i)))
1555	    return false;
1556
1557	 if (BRW_GET_SWZ(src.swizzle, i) != i)
1558	    return false;
1559      }
1560   }
1561
1562   /* Success!  Rewrite the instruction. */
1563   last_rhs_inst->dst.file = dst.file;
1564   last_rhs_inst->dst.reg = dst.reg;
1565   last_rhs_inst->dst.reg_offset = dst.reg_offset;
1566   last_rhs_inst->dst.reladdr = dst.reladdr;
1567   last_rhs_inst->dst.writemask &= dst.writemask;
1568
1569   return true;
1570}
1571
1572void
1573vec4_visitor::visit(ir_assignment *ir)
1574{
1575   dst_reg dst = get_assignment_lhs(ir->lhs, this);
1576   uint32_t predicate = BRW_PREDICATE_NONE;
1577
1578   if (!ir->lhs->type->is_scalar() &&
1579       !ir->lhs->type->is_vector()) {
1580      ir->rhs->accept(this);
1581      src_reg src = this->result;
1582
1583      if (ir->condition) {
1584	 emit_bool_to_cond_code(ir->condition, &predicate);
1585      }
1586
1587      emit_block_move(&dst, &src, ir->rhs->type, predicate);
1588      return;
1589   }
1590
1591   /* Now we're down to just a scalar/vector with writemasks. */
1592   int i;
1593
1594   vec4_instruction *pre_rhs_inst, *last_rhs_inst;
1595   pre_rhs_inst = (vec4_instruction *)this->instructions.get_tail();
1596
1597   ir->rhs->accept(this);
1598
1599   last_rhs_inst = (vec4_instruction *)this->instructions.get_tail();
1600
1601   src_reg src = this->result;
1602
1603   int swizzles[4];
1604   int first_enabled_chan = 0;
1605   int src_chan = 0;
1606
1607   assert(ir->lhs->type->is_vector() ||
1608	  ir->lhs->type->is_scalar());
1609   dst.writemask = ir->write_mask;
1610
1611   for (int i = 0; i < 4; i++) {
1612      if (dst.writemask & (1 << i)) {
1613	 first_enabled_chan = BRW_GET_SWZ(src.swizzle, i);
1614	 break;
1615      }
1616   }
1617
1618   /* Swizzle a small RHS vector into the channels being written.
1619    *
1620    * glsl ir treats write_mask as dictating how many channels are
1621    * present on the RHS while in our instructions we need to make
1622    * those channels appear in the slots of the vec4 they're written to.
1623    */
1624   for (int i = 0; i < 4; i++) {
1625      if (dst.writemask & (1 << i))
1626	 swizzles[i] = BRW_GET_SWZ(src.swizzle, src_chan++);
1627      else
1628	 swizzles[i] = first_enabled_chan;
1629   }
1630   src.swizzle = BRW_SWIZZLE4(swizzles[0], swizzles[1],
1631			      swizzles[2], swizzles[3]);
1632
1633   if (try_rewrite_rhs_to_dst(ir, dst, src, pre_rhs_inst, last_rhs_inst)) {
1634      return;
1635   }
1636
1637   if (ir->condition) {
1638      emit_bool_to_cond_code(ir->condition, &predicate);
1639   }
1640
1641   for (i = 0; i < type_size(ir->lhs->type); i++) {
1642      vec4_instruction *inst = emit(MOV(dst, src));
1643      inst->predicate = predicate;
1644
1645      dst.reg_offset++;
1646      src.reg_offset++;
1647   }
1648}
1649
1650void
1651vec4_visitor::emit_constant_values(dst_reg *dst, ir_constant *ir)
1652{
1653   if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1654      foreach_list(node, &ir->components) {
1655	 ir_constant *field_value = (ir_constant *)node;
1656
1657	 emit_constant_values(dst, field_value);
1658      }
1659      return;
1660   }
1661
1662   if (ir->type->is_array()) {
1663      for (unsigned int i = 0; i < ir->type->length; i++) {
1664	 emit_constant_values(dst, ir->array_elements[i]);
1665      }
1666      return;
1667   }
1668
1669   if (ir->type->is_matrix()) {
1670      for (int i = 0; i < ir->type->matrix_columns; i++) {
1671	 for (int j = 0; j < ir->type->vector_elements; j++) {
1672	    dst->writemask = 1 << j;
1673	    dst->type = BRW_REGISTER_TYPE_F;
1674
1675	    emit(MOV(*dst,
1676		     src_reg(ir->value.f[i * ir->type->vector_elements + j])));
1677	 }
1678	 dst->reg_offset++;
1679      }
1680      return;
1681   }
1682
1683   for (int i = 0; i < ir->type->vector_elements; i++) {
1684      dst->writemask = 1 << i;
1685      dst->type = brw_type_for_base_type(ir->type);
1686
1687      switch (ir->type->base_type) {
1688      case GLSL_TYPE_FLOAT:
1689	 emit(MOV(*dst, src_reg(ir->value.f[i])));
1690	 break;
1691      case GLSL_TYPE_INT:
1692	 emit(MOV(*dst, src_reg(ir->value.i[i])));
1693	 break;
1694      case GLSL_TYPE_UINT:
1695	 emit(MOV(*dst, src_reg(ir->value.u[i])));
1696	 break;
1697      case GLSL_TYPE_BOOL:
1698	 emit(MOV(*dst, src_reg(ir->value.b[i])));
1699	 break;
1700      default:
1701	 assert(!"Non-float/uint/int/bool constant");
1702	 break;
1703      }
1704   }
1705   dst->reg_offset++;
1706}
1707
1708void
1709vec4_visitor::visit(ir_constant *ir)
1710{
1711   dst_reg dst = dst_reg(this, ir->type);
1712   this->result = src_reg(dst);
1713
1714   emit_constant_values(&dst, ir);
1715}
1716
1717void
1718vec4_visitor::visit(ir_call *ir)
1719{
1720   assert(!"not reached");
1721}
1722
1723void
1724vec4_visitor::visit(ir_texture *ir)
1725{
1726   /* FINISHME: Implement vertex texturing.
1727    *
1728    * With 0 vertex samplers available, the linker will reject
1729    * programs that do vertex texturing, but after our visitor has
1730    * run.
1731    */
1732   this->result = src_reg(this, glsl_type::vec4_type);
1733}
1734
1735void
1736vec4_visitor::visit(ir_return *ir)
1737{
1738   assert(!"not reached");
1739}
1740
1741void
1742vec4_visitor::visit(ir_discard *ir)
1743{
1744   assert(!"not reached");
1745}
1746
1747void
1748vec4_visitor::visit(ir_if *ir)
1749{
1750   /* Don't point the annotation at the if statement, because then it plus
1751    * the then and else blocks get printed.
1752    */
1753   this->base_ir = ir->condition;
1754
1755   if (intel->gen == 6) {
1756      emit_if_gen6(ir);
1757   } else {
1758      uint32_t predicate;
1759      emit_bool_to_cond_code(ir->condition, &predicate);
1760      emit(IF(predicate));
1761   }
1762
1763   visit_instructions(&ir->then_instructions);
1764
1765   if (!ir->else_instructions.is_empty()) {
1766      this->base_ir = ir->condition;
1767      emit(BRW_OPCODE_ELSE);
1768
1769      visit_instructions(&ir->else_instructions);
1770   }
1771
1772   this->base_ir = ir->condition;
1773   emit(BRW_OPCODE_ENDIF);
1774}
1775
1776void
1777vec4_visitor::emit_ndc_computation()
1778{
1779   /* Get the position */
1780   src_reg pos = src_reg(output_reg[VERT_RESULT_HPOS]);
1781
1782   /* Build ndc coords, which are (x/w, y/w, z/w, 1/w) */
1783   dst_reg ndc = dst_reg(this, glsl_type::vec4_type);
1784   output_reg[BRW_VERT_RESULT_NDC] = ndc;
1785
1786   current_annotation = "NDC";
1787   dst_reg ndc_w = ndc;
1788   ndc_w.writemask = WRITEMASK_W;
1789   src_reg pos_w = pos;
1790   pos_w.swizzle = BRW_SWIZZLE4(SWIZZLE_W, SWIZZLE_W, SWIZZLE_W, SWIZZLE_W);
1791   emit_math(SHADER_OPCODE_RCP, ndc_w, pos_w);
1792
1793   dst_reg ndc_xyz = ndc;
1794   ndc_xyz.writemask = WRITEMASK_XYZ;
1795
1796   emit(MUL(ndc_xyz, pos, src_reg(ndc_w)));
1797}
1798
1799void
1800vec4_visitor::emit_psiz_and_flags(struct brw_reg reg)
1801{
1802   if (intel->gen < 6 &&
1803       ((c->prog_data.outputs_written & BITFIELD64_BIT(VERT_RESULT_PSIZ)) ||
1804        c->key.userclip_active || brw->has_negative_rhw_bug)) {
1805      dst_reg header1 = dst_reg(this, glsl_type::uvec4_type);
1806      dst_reg header1_w = header1;
1807      header1_w.writemask = WRITEMASK_W;
1808      GLuint i;
1809
1810      emit(MOV(header1, 0u));
1811
1812      if (c->prog_data.outputs_written & BITFIELD64_BIT(VERT_RESULT_PSIZ)) {
1813	 src_reg psiz = src_reg(output_reg[VERT_RESULT_PSIZ]);
1814
1815	 current_annotation = "Point size";
1816	 emit(MUL(header1_w, psiz, src_reg((float)(1 << 11))));
1817	 emit(AND(header1_w, src_reg(header1_w), 0x7ff << 8));
1818      }
1819
1820      current_annotation = "Clipping flags";
1821      for (i = 0; i < c->key.nr_userclip_plane_consts; i++) {
1822	 vec4_instruction *inst;
1823
1824	 inst = emit(DP4(dst_null_f(), src_reg(output_reg[VERT_RESULT_HPOS]),
1825                         src_reg(this->userplane[i])));
1826	 inst->conditional_mod = BRW_CONDITIONAL_L;
1827
1828	 inst = emit(OR(header1_w, src_reg(header1_w), 1u << i));
1829	 inst->predicate = BRW_PREDICATE_NORMAL;
1830      }
1831
1832      /* i965 clipping workaround:
1833       * 1) Test for -ve rhw
1834       * 2) If set,
1835       *      set ndc = (0,0,0,0)
1836       *      set ucp[6] = 1
1837       *
1838       * Later, clipping will detect ucp[6] and ensure the primitive is
1839       * clipped against all fixed planes.
1840       */
1841      if (brw->has_negative_rhw_bug) {
1842#if 0
1843	 /* FINISHME */
1844	 brw_CMP(p,
1845		 vec8(brw_null_reg()),
1846		 BRW_CONDITIONAL_L,
1847		 brw_swizzle1(output_reg[BRW_VERT_RESULT_NDC], 3),
1848		 brw_imm_f(0));
1849
1850	 brw_OR(p, brw_writemask(header1, WRITEMASK_W), header1, brw_imm_ud(1<<6));
1851	 brw_MOV(p, output_reg[BRW_VERT_RESULT_NDC], brw_imm_f(0));
1852	 brw_set_predicate_control(p, BRW_PREDICATE_NONE);
1853#endif
1854      }
1855
1856      emit(MOV(retype(reg, BRW_REGISTER_TYPE_UD), src_reg(header1)));
1857   } else if (intel->gen < 6) {
1858      emit(MOV(retype(reg, BRW_REGISTER_TYPE_UD), 0u));
1859   } else {
1860      emit(MOV(retype(reg, BRW_REGISTER_TYPE_D), src_reg(0)));
1861      if (c->prog_data.outputs_written & BITFIELD64_BIT(VERT_RESULT_PSIZ)) {
1862         emit(MOV(brw_writemask(reg, WRITEMASK_W),
1863                  src_reg(output_reg[VERT_RESULT_PSIZ])));
1864      }
1865   }
1866}
1867
1868void
1869vec4_visitor::emit_clip_distances(struct brw_reg reg, int offset)
1870{
1871   if (intel->gen < 6) {
1872      /* Clip distance slots are set aside in gen5, but they are not used.  It
1873       * is not clear whether we actually need to set aside space for them,
1874       * but the performance cost is negligible.
1875       */
1876      return;
1877   }
1878
1879   /* From the GLSL 1.30 spec, section 7.1 (Vertex Shader Special Variables):
1880    *
1881    *     "If a linked set of shaders forming the vertex stage contains no
1882    *     static write to gl_ClipVertex or gl_ClipDistance, but the
1883    *     application has requested clipping against user clip planes through
1884    *     the API, then the coordinate written to gl_Position is used for
1885    *     comparison against the user clip planes."
1886    *
1887    * This function is only called if the shader didn't write to
1888    * gl_ClipDistance.  Accordingly, we use gl_ClipVertex to perform clipping
1889    * if the user wrote to it; otherwise we use gl_Position.
1890    */
1891   gl_vert_result clip_vertex = VERT_RESULT_CLIP_VERTEX;
1892   if (!(c->prog_data.outputs_written
1893         & BITFIELD64_BIT(VERT_RESULT_CLIP_VERTEX))) {
1894      clip_vertex = VERT_RESULT_HPOS;
1895   }
1896
1897   for (int i = 0; i + offset < c->key.nr_userclip_plane_consts && i < 4;
1898        ++i) {
1899      emit(DP4(dst_reg(brw_writemask(reg, 1 << i)),
1900               src_reg(output_reg[clip_vertex]),
1901               src_reg(this->userplane[i + offset])));
1902   }
1903}
1904
1905void
1906vec4_visitor::emit_generic_urb_slot(dst_reg reg, int vert_result)
1907{
1908   assert (vert_result < VERT_RESULT_MAX);
1909   current_annotation = output_reg_annotation[vert_result];
1910   /* Copy the register, saturating if necessary */
1911   vec4_instruction *inst = emit(MOV(reg,
1912                                     src_reg(output_reg[vert_result])));
1913   if ((vert_result == VERT_RESULT_COL0 ||
1914        vert_result == VERT_RESULT_COL1 ||
1915        vert_result == VERT_RESULT_BFC0 ||
1916        vert_result == VERT_RESULT_BFC1) &&
1917       c->key.clamp_vertex_color) {
1918      inst->saturate = true;
1919   }
1920}
1921
1922void
1923vec4_visitor::emit_urb_slot(int mrf, int vert_result)
1924{
1925   struct brw_reg hw_reg = brw_message_reg(mrf);
1926   dst_reg reg = dst_reg(MRF, mrf);
1927   reg.type = BRW_REGISTER_TYPE_F;
1928
1929   switch (vert_result) {
1930   case VERT_RESULT_PSIZ:
1931      /* PSIZ is always in slot 0, and is coupled with other flags. */
1932      current_annotation = "indices, point width, clip flags";
1933      emit_psiz_and_flags(hw_reg);
1934      break;
1935   case BRW_VERT_RESULT_NDC:
1936      current_annotation = "NDC";
1937      emit(MOV(reg, src_reg(output_reg[BRW_VERT_RESULT_NDC])));
1938      break;
1939   case BRW_VERT_RESULT_HPOS_DUPLICATE:
1940   case VERT_RESULT_HPOS:
1941      current_annotation = "gl_Position";
1942      emit(MOV(reg, src_reg(output_reg[VERT_RESULT_HPOS])));
1943      break;
1944   case VERT_RESULT_CLIP_DIST0:
1945   case VERT_RESULT_CLIP_DIST1:
1946      if (this->c->key.uses_clip_distance) {
1947         emit_generic_urb_slot(reg, vert_result);
1948      } else {
1949         current_annotation = "user clip distances";
1950         emit_clip_distances(hw_reg, (vert_result - VERT_RESULT_CLIP_DIST0) * 4);
1951      }
1952      break;
1953   case BRW_VERT_RESULT_PAD:
1954      /* No need to write to this slot */
1955      break;
1956   default:
1957      emit_generic_urb_slot(reg, vert_result);
1958      break;
1959   }
1960}
1961
1962static int
1963align_interleaved_urb_mlen(struct brw_context *brw, int mlen)
1964{
1965   struct intel_context *intel = &brw->intel;
1966
1967   if (intel->gen >= 6) {
1968      /* URB data written (does not include the message header reg) must
1969       * be a multiple of 256 bits, or 2 VS registers.  See vol5c.5,
1970       * section 5.4.3.2.2: URB_INTERLEAVED.
1971       *
1972       * URB entries are allocated on a multiple of 1024 bits, so an
1973       * extra 128 bits written here to make the end align to 256 is
1974       * no problem.
1975       */
1976      if ((mlen % 2) != 1)
1977	 mlen++;
1978   }
1979
1980   return mlen;
1981}
1982
1983/**
1984 * Generates the VUE payload plus the 1 or 2 URB write instructions to
1985 * complete the VS thread.
1986 *
1987 * The VUE layout is documented in Volume 2a.
1988 */
1989void
1990vec4_visitor::emit_urb_writes()
1991{
1992   /* MRF 0 is reserved for the debugger, so start with message header
1993    * in MRF 1.
1994    */
1995   int base_mrf = 1;
1996   int mrf = base_mrf;
1997   /* In the process of generating our URB write message contents, we
1998    * may need to unspill a register or load from an array.  Those
1999    * reads would use MRFs 14-15.
2000    */
2001   int max_usable_mrf = 13;
2002
2003   /* The following assertion verifies that max_usable_mrf causes an
2004    * even-numbered amount of URB write data, which will meet gen6's
2005    * requirements for length alignment.
2006    */
2007   assert ((max_usable_mrf - base_mrf) % 2 == 0);
2008
2009   /* FINISHME: edgeflag */
2010
2011   brw_compute_vue_map(&c->vue_map, intel, c->key.userclip_active,
2012                       c->prog_data.outputs_written);
2013
2014   /* First mrf is the g0-based message header containing URB handles and such,
2015    * which is implied in VS_OPCODE_URB_WRITE.
2016    */
2017   mrf++;
2018
2019   if (intel->gen < 6) {
2020      emit_ndc_computation();
2021   }
2022
2023   /* Set up the VUE data for the first URB write */
2024   int slot;
2025   for (slot = 0; slot < c->vue_map.num_slots; ++slot) {
2026      emit_urb_slot(mrf++, c->vue_map.slot_to_vert_result[slot]);
2027
2028      /* If this was max_usable_mrf, we can't fit anything more into this URB
2029       * WRITE.
2030       */
2031      if (mrf > max_usable_mrf) {
2032	 slot++;
2033	 break;
2034      }
2035   }
2036
2037   current_annotation = "URB write";
2038   vec4_instruction *inst = emit(VS_OPCODE_URB_WRITE);
2039   inst->base_mrf = base_mrf;
2040   inst->mlen = align_interleaved_urb_mlen(brw, mrf - base_mrf);
2041   inst->eot = (slot >= c->vue_map.num_slots);
2042
2043   /* Optional second URB write */
2044   if (!inst->eot) {
2045      mrf = base_mrf + 1;
2046
2047      for (; slot < c->vue_map.num_slots; ++slot) {
2048	 assert(mrf < max_usable_mrf);
2049
2050         emit_urb_slot(mrf++, c->vue_map.slot_to_vert_result[slot]);
2051      }
2052
2053      current_annotation = "URB write";
2054      inst = emit(VS_OPCODE_URB_WRITE);
2055      inst->base_mrf = base_mrf;
2056      inst->mlen = align_interleaved_urb_mlen(brw, mrf - base_mrf);
2057      inst->eot = true;
2058      /* URB destination offset.  In the previous write, we got MRFs
2059       * 2-13 minus the one header MRF, so 12 regs.  URB offset is in
2060       * URB row increments, and each of our MRFs is half of one of
2061       * those, since we're doing interleaved writes.
2062       */
2063      inst->offset = (max_usable_mrf - base_mrf) / 2;
2064   }
2065
2066   if (intel->gen == 6)
2067      c->prog_data.urb_entry_size = ALIGN(c->vue_map.num_slots, 8) / 8;
2068   else
2069      c->prog_data.urb_entry_size = ALIGN(c->vue_map.num_slots, 4) / 4;
2070}
2071
2072src_reg
2073vec4_visitor::get_scratch_offset(vec4_instruction *inst,
2074				 src_reg *reladdr, int reg_offset)
2075{
2076   /* Because we store the values to scratch interleaved like our
2077    * vertex data, we need to scale the vec4 index by 2.
2078    */
2079   int message_header_scale = 2;
2080
2081   /* Pre-gen6, the message header uses byte offsets instead of vec4
2082    * (16-byte) offset units.
2083    */
2084   if (intel->gen < 6)
2085      message_header_scale *= 16;
2086
2087   if (reladdr) {
2088      src_reg index = src_reg(this, glsl_type::int_type);
2089
2090      emit_before(inst, ADD(dst_reg(index), *reladdr, src_reg(reg_offset)));
2091      emit_before(inst, MUL(dst_reg(index),
2092			    index, src_reg(message_header_scale)));
2093
2094      return index;
2095   } else {
2096      return src_reg(reg_offset * message_header_scale);
2097   }
2098}
2099
2100src_reg
2101vec4_visitor::get_pull_constant_offset(vec4_instruction *inst,
2102				       src_reg *reladdr, int reg_offset)
2103{
2104   if (reladdr) {
2105      src_reg index = src_reg(this, glsl_type::int_type);
2106
2107      emit_before(inst, ADD(dst_reg(index), *reladdr, src_reg(reg_offset)));
2108
2109      /* Pre-gen6, the message header uses byte offsets instead of vec4
2110       * (16-byte) offset units.
2111       */
2112      if (intel->gen < 6) {
2113	 emit_before(inst, MUL(dst_reg(index), index, src_reg(16)));
2114      }
2115
2116      return index;
2117   } else {
2118      int message_header_scale = intel->gen < 6 ? 16 : 1;
2119      return src_reg(reg_offset * message_header_scale);
2120   }
2121}
2122
2123/**
2124 * Emits an instruction before @inst to load the value named by @orig_src
2125 * from scratch space at @base_offset to @temp.
2126 */
2127void
2128vec4_visitor::emit_scratch_read(vec4_instruction *inst,
2129				dst_reg temp, src_reg orig_src,
2130				int base_offset)
2131{
2132   int reg_offset = base_offset + orig_src.reg_offset;
2133   src_reg index = get_scratch_offset(inst, orig_src.reladdr, reg_offset);
2134
2135   emit_before(inst, SCRATCH_READ(temp, index));
2136}
2137
2138/**
2139 * Emits an instruction after @inst to store the value to be written
2140 * to @orig_dst to scratch space at @base_offset, from @temp.
2141 */
2142void
2143vec4_visitor::emit_scratch_write(vec4_instruction *inst,
2144				 src_reg temp, dst_reg orig_dst,
2145				 int base_offset)
2146{
2147   int reg_offset = base_offset + orig_dst.reg_offset;
2148   src_reg index = get_scratch_offset(inst, orig_dst.reladdr, reg_offset);
2149
2150   dst_reg dst = dst_reg(brw_writemask(brw_vec8_grf(0, 0),
2151				       orig_dst.writemask));
2152   vec4_instruction *write = SCRATCH_WRITE(dst, temp, index);
2153   write->predicate = inst->predicate;
2154   write->ir = inst->ir;
2155   write->annotation = inst->annotation;
2156   inst->insert_after(write);
2157}
2158
2159/**
2160 * We can't generally support array access in GRF space, because a
2161 * single instruction's destination can only span 2 contiguous
2162 * registers.  So, we send all GRF arrays that get variable index
2163 * access to scratch space.
2164 */
2165void
2166vec4_visitor::move_grf_array_access_to_scratch()
2167{
2168   int scratch_loc[this->virtual_grf_count];
2169
2170   for (int i = 0; i < this->virtual_grf_count; i++) {
2171      scratch_loc[i] = -1;
2172   }
2173
2174   /* First, calculate the set of virtual GRFs that need to be punted
2175    * to scratch due to having any array access on them, and where in
2176    * scratch.
2177    */
2178   foreach_list(node, &this->instructions) {
2179      vec4_instruction *inst = (vec4_instruction *)node;
2180
2181      if (inst->dst.file == GRF && inst->dst.reladdr &&
2182	  scratch_loc[inst->dst.reg] == -1) {
2183	 scratch_loc[inst->dst.reg] = c->last_scratch;
2184	 c->last_scratch += this->virtual_grf_sizes[inst->dst.reg] * 8 * 4;
2185      }
2186
2187      for (int i = 0 ; i < 3; i++) {
2188	 src_reg *src = &inst->src[i];
2189
2190	 if (src->file == GRF && src->reladdr &&
2191	     scratch_loc[src->reg] == -1) {
2192	    scratch_loc[src->reg] = c->last_scratch;
2193	    c->last_scratch += this->virtual_grf_sizes[src->reg] * 8 * 4;
2194	 }
2195      }
2196   }
2197
2198   /* Now, for anything that will be accessed through scratch, rewrite
2199    * it to load/store.  Note that this is a _safe list walk, because
2200    * we may generate a new scratch_write instruction after the one
2201    * we're processing.
2202    */
2203   foreach_list_safe(node, &this->instructions) {
2204      vec4_instruction *inst = (vec4_instruction *)node;
2205
2206      /* Set up the annotation tracking for new generated instructions. */
2207      base_ir = inst->ir;
2208      current_annotation = inst->annotation;
2209
2210      if (inst->dst.file == GRF && scratch_loc[inst->dst.reg] != -1) {
2211	 src_reg temp = src_reg(this, glsl_type::vec4_type);
2212
2213	 emit_scratch_write(inst, temp, inst->dst, scratch_loc[inst->dst.reg]);
2214
2215	 inst->dst.file = temp.file;
2216	 inst->dst.reg = temp.reg;
2217	 inst->dst.reg_offset = temp.reg_offset;
2218	 inst->dst.reladdr = NULL;
2219      }
2220
2221      for (int i = 0 ; i < 3; i++) {
2222	 if (inst->src[i].file != GRF || scratch_loc[inst->src[i].reg] == -1)
2223	    continue;
2224
2225	 dst_reg temp = dst_reg(this, glsl_type::vec4_type);
2226
2227	 emit_scratch_read(inst, temp, inst->src[i],
2228			   scratch_loc[inst->src[i].reg]);
2229
2230	 inst->src[i].file = temp.file;
2231	 inst->src[i].reg = temp.reg;
2232	 inst->src[i].reg_offset = temp.reg_offset;
2233	 inst->src[i].reladdr = NULL;
2234      }
2235   }
2236}
2237
2238/**
2239 * Emits an instruction before @inst to load the value named by @orig_src
2240 * from the pull constant buffer (surface) at @base_offset to @temp.
2241 */
2242void
2243vec4_visitor::emit_pull_constant_load(vec4_instruction *inst,
2244				      dst_reg temp, src_reg orig_src,
2245				      int base_offset)
2246{
2247   int reg_offset = base_offset + orig_src.reg_offset;
2248   src_reg index = get_pull_constant_offset(inst, orig_src.reladdr, reg_offset);
2249   vec4_instruction *load;
2250
2251   load = new(mem_ctx) vec4_instruction(this, VS_OPCODE_PULL_CONSTANT_LOAD,
2252					temp, index);
2253   load->base_mrf = 14;
2254   load->mlen = 1;
2255   emit_before(inst, load);
2256}
2257
2258/**
2259 * Implements array access of uniforms by inserting a
2260 * PULL_CONSTANT_LOAD instruction.
2261 *
2262 * Unlike temporary GRF array access (where we don't support it due to
2263 * the difficulty of doing relative addressing on instruction
2264 * destinations), we could potentially do array access of uniforms
2265 * that were loaded in GRF space as push constants.  In real-world
2266 * usage we've seen, though, the arrays being used are always larger
2267 * than we could load as push constants, so just always move all
2268 * uniform array access out to a pull constant buffer.
2269 */
2270void
2271vec4_visitor::move_uniform_array_access_to_pull_constants()
2272{
2273   int pull_constant_loc[this->uniforms];
2274
2275   for (int i = 0; i < this->uniforms; i++) {
2276      pull_constant_loc[i] = -1;
2277   }
2278
2279   /* Walk through and find array access of uniforms.  Put a copy of that
2280    * uniform in the pull constant buffer.
2281    *
2282    * Note that we don't move constant-indexed accesses to arrays.  No
2283    * testing has been done of the performance impact of this choice.
2284    */
2285   foreach_list_safe(node, &this->instructions) {
2286      vec4_instruction *inst = (vec4_instruction *)node;
2287
2288      for (int i = 0 ; i < 3; i++) {
2289	 if (inst->src[i].file != UNIFORM || !inst->src[i].reladdr)
2290	    continue;
2291
2292	 int uniform = inst->src[i].reg;
2293
2294	 /* If this array isn't already present in the pull constant buffer,
2295	  * add it.
2296	  */
2297	 if (pull_constant_loc[uniform] == -1) {
2298	    const float **values = &prog_data->param[uniform * 4];
2299
2300	    pull_constant_loc[uniform] = prog_data->nr_pull_params / 4;
2301
2302	    for (int j = 0; j < uniform_size[uniform] * 4; j++) {
2303	       prog_data->pull_param[prog_data->nr_pull_params++] = values[j];
2304	    }
2305	 }
2306
2307	 /* Set up the annotation tracking for new generated instructions. */
2308	 base_ir = inst->ir;
2309	 current_annotation = inst->annotation;
2310
2311	 dst_reg temp = dst_reg(this, glsl_type::vec4_type);
2312
2313	 emit_pull_constant_load(inst, temp, inst->src[i],
2314				 pull_constant_loc[uniform]);
2315
2316	 inst->src[i].file = temp.file;
2317	 inst->src[i].reg = temp.reg;
2318	 inst->src[i].reg_offset = temp.reg_offset;
2319	 inst->src[i].reladdr = NULL;
2320      }
2321   }
2322
2323   /* Now there are no accesses of the UNIFORM file with a reladdr, so
2324    * no need to track them as larger-than-vec4 objects.  This will be
2325    * relied on in cutting out unused uniform vectors from push
2326    * constants.
2327    */
2328   split_uniform_registers();
2329}
2330
2331vec4_visitor::vec4_visitor(struct brw_vs_compile *c,
2332			   struct gl_shader_program *prog,
2333			   struct brw_shader *shader)
2334{
2335   this->c = c;
2336   this->p = &c->func;
2337   this->brw = p->brw;
2338   this->intel = &brw->intel;
2339   this->ctx = &intel->ctx;
2340   this->prog = prog;
2341   this->shader = shader;
2342
2343   this->mem_ctx = ralloc_context(NULL);
2344   this->failed = false;
2345
2346   this->base_ir = NULL;
2347   this->current_annotation = NULL;
2348
2349   this->c = c;
2350   this->vp = (struct gl_vertex_program *)
2351     prog->_LinkedShaders[MESA_SHADER_VERTEX]->Program;
2352   this->prog_data = &c->prog_data;
2353
2354   this->variable_ht = hash_table_ctor(0,
2355				       hash_table_pointer_hash,
2356				       hash_table_pointer_compare);
2357
2358   this->virtual_grf_def = NULL;
2359   this->virtual_grf_use = NULL;
2360   this->virtual_grf_sizes = NULL;
2361   this->virtual_grf_count = 0;
2362   this->virtual_grf_reg_map = NULL;
2363   this->virtual_grf_reg_count = 0;
2364   this->virtual_grf_array_size = 0;
2365   this->live_intervals_valid = false;
2366
2367   this->uniforms = 0;
2368
2369   this->variable_ht = hash_table_ctor(0,
2370				       hash_table_pointer_hash,
2371				       hash_table_pointer_compare);
2372}
2373
2374vec4_visitor::~vec4_visitor()
2375{
2376   ralloc_free(this->mem_ctx);
2377   hash_table_dtor(this->variable_ht);
2378}
2379
2380
2381void
2382vec4_visitor::fail(const char *format, ...)
2383{
2384   va_list va;
2385   char *msg;
2386
2387   if (failed)
2388      return;
2389
2390   failed = true;
2391
2392   va_start(va, format);
2393   msg = ralloc_vasprintf(mem_ctx, format, va);
2394   va_end(va);
2395   msg = ralloc_asprintf(mem_ctx, "VS compile failed: %s\n", msg);
2396
2397   this->fail_msg = msg;
2398
2399   if (INTEL_DEBUG & DEBUG_VS) {
2400      fprintf(stderr, "%s",  msg);
2401   }
2402}
2403
2404} /* namespace brw */
2405