st_glsl_to_tgsi.cpp revision abcdbdf9cce3c7520ee999fac3099d609960847d
1/*
2 * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
3 * Copyright (C) 2008  VMware, Inc.   All Rights Reserved.
4 * Copyright © 2010 Intel Corporation
5 * Copyright © 2011 Bryan Cain
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
16 * Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 */
26
27/**
28 * \file glsl_to_tgsi.cpp
29 *
30 * Translate GLSL IR to TGSI.
31 */
32
33#include <stdio.h>
34#include "main/compiler.h"
35#include "ir.h"
36#include "ir_visitor.h"
37#include "ir_print_visitor.h"
38#include "ir_expression_flattening.h"
39#include "glsl_types.h"
40#include "glsl_parser_extras.h"
41#include "../glsl/program.h"
42#include "ir_optimization.h"
43#include "ast.h"
44
45#include "main/mtypes.h"
46#include "main/shaderobj.h"
47#include "program/hash_table.h"
48
49extern "C" {
50#include "main/shaderapi.h"
51#include "main/uniforms.h"
52#include "program/prog_instruction.h"
53#include "program/prog_optimize.h"
54#include "program/prog_print.h"
55#include "program/program.h"
56#include "program/prog_parameter.h"
57#include "program/sampler.h"
58
59#include "pipe/p_compiler.h"
60#include "pipe/p_context.h"
61#include "pipe/p_screen.h"
62#include "pipe/p_shader_tokens.h"
63#include "pipe/p_state.h"
64#include "util/u_math.h"
65#include "tgsi/tgsi_ureg.h"
66#include "tgsi/tgsi_info.h"
67#include "st_context.h"
68#include "st_program.h"
69#include "st_glsl_to_tgsi.h"
70#include "st_mesa_to_tgsi.h"
71}
72
73#define PROGRAM_IMMEDIATE PROGRAM_FILE_MAX
74#define PROGRAM_ANY_CONST ((1 << PROGRAM_LOCAL_PARAM) |  \
75                           (1 << PROGRAM_ENV_PARAM) |    \
76                           (1 << PROGRAM_STATE_VAR) |    \
77                           (1 << PROGRAM_NAMED_PARAM) |  \
78                           (1 << PROGRAM_CONSTANT) |     \
79                           (1 << PROGRAM_UNIFORM))
80
81/**
82 * Maximum number of temporary registers.
83 *
84 * It is too big for stack allocated arrays -- it will cause stack overflow on
85 * Windows and likely Mac OS X.
86 */
87#define MAX_TEMPS         4096
88
89/* will be 4 for GLSL 4.00 */
90#define MAX_GLSL_TEXTURE_OFFSET 1
91
92class st_src_reg;
93class st_dst_reg;
94
95static int swizzle_for_size(int size);
96
97/**
98 * This struct is a corresponding struct to TGSI ureg_src.
99 */
100class st_src_reg {
101public:
102   st_src_reg(gl_register_file file, int index, const glsl_type *type)
103   {
104      this->file = file;
105      this->index = index;
106      if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
107         this->swizzle = swizzle_for_size(type->vector_elements);
108      else
109         this->swizzle = SWIZZLE_XYZW;
110      this->negate = 0;
111      this->type = type ? type->base_type : GLSL_TYPE_ERROR;
112      this->reladdr = NULL;
113   }
114
115   st_src_reg(gl_register_file file, int index, int type)
116   {
117      this->type = type;
118      this->file = file;
119      this->index = index;
120      this->swizzle = SWIZZLE_XYZW;
121      this->negate = 0;
122      this->reladdr = NULL;
123   }
124
125   st_src_reg()
126   {
127      this->type = GLSL_TYPE_ERROR;
128      this->file = PROGRAM_UNDEFINED;
129      this->index = 0;
130      this->swizzle = 0;
131      this->negate = 0;
132      this->reladdr = NULL;
133   }
134
135   explicit st_src_reg(st_dst_reg reg);
136
137   gl_register_file file; /**< PROGRAM_* from Mesa */
138   int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
139   GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
140   int negate; /**< NEGATE_XYZW mask from mesa */
141   int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
142   /** Register index should be offset by the integer in this reg. */
143   st_src_reg *reladdr;
144};
145
146class st_dst_reg {
147public:
148   st_dst_reg(gl_register_file file, int writemask, int type)
149   {
150      this->file = file;
151      this->index = 0;
152      this->writemask = writemask;
153      this->cond_mask = COND_TR;
154      this->reladdr = NULL;
155      this->type = type;
156   }
157
158   st_dst_reg()
159   {
160      this->type = GLSL_TYPE_ERROR;
161      this->file = PROGRAM_UNDEFINED;
162      this->index = 0;
163      this->writemask = 0;
164      this->cond_mask = COND_TR;
165      this->reladdr = NULL;
166   }
167
168   explicit st_dst_reg(st_src_reg reg);
169
170   gl_register_file file; /**< PROGRAM_* from Mesa */
171   int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
172   int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
173   GLuint cond_mask:4;
174   int type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
175   /** Register index should be offset by the integer in this reg. */
176   st_src_reg *reladdr;
177};
178
179st_src_reg::st_src_reg(st_dst_reg reg)
180{
181   this->type = reg.type;
182   this->file = reg.file;
183   this->index = reg.index;
184   this->swizzle = SWIZZLE_XYZW;
185   this->negate = 0;
186   this->reladdr = reg.reladdr;
187}
188
189st_dst_reg::st_dst_reg(st_src_reg reg)
190{
191   this->type = reg.type;
192   this->file = reg.file;
193   this->index = reg.index;
194   this->writemask = WRITEMASK_XYZW;
195   this->cond_mask = COND_TR;
196   this->reladdr = reg.reladdr;
197}
198
199class glsl_to_tgsi_instruction : public exec_node {
200public:
201   /* Callers of this ralloc-based new need not call delete. It's
202    * easier to just ralloc_free 'ctx' (or any of its ancestors). */
203   static void* operator new(size_t size, void *ctx)
204   {
205      void *node;
206
207      node = rzalloc_size(ctx, size);
208      assert(node != NULL);
209
210      return node;
211   }
212
213   unsigned op;
214   st_dst_reg dst;
215   st_src_reg src[3];
216   /** Pointer to the ir source this tree came from for debugging */
217   ir_instruction *ir;
218   GLboolean cond_update;
219   bool saturate;
220   int sampler; /**< sampler index */
221   int tex_target; /**< One of TEXTURE_*_INDEX */
222   GLboolean tex_shadow;
223   struct tgsi_texture_offset tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
224   unsigned tex_offset_num_offset;
225   int dead_mask; /**< Used in dead code elimination */
226
227   class function_entry *function; /* Set on TGSI_OPCODE_CAL or TGSI_OPCODE_BGNSUB */
228};
229
230class variable_storage : public exec_node {
231public:
232   variable_storage(ir_variable *var, gl_register_file file, int index)
233      : file(file), index(index), var(var)
234   {
235      /* empty */
236   }
237
238   gl_register_file file;
239   int index;
240   ir_variable *var; /* variable that maps to this, if any */
241};
242
243class immediate_storage : public exec_node {
244public:
245   immediate_storage(gl_constant_value *values, int size, int type)
246   {
247      memcpy(this->values, values, size * sizeof(gl_constant_value));
248      this->size = size;
249      this->type = type;
250   }
251
252   gl_constant_value values[4];
253   int size; /**< Number of components (1-4) */
254   int type; /**< GL_FLOAT, GL_INT, GL_BOOL, or GL_UNSIGNED_INT */
255};
256
257class function_entry : public exec_node {
258public:
259   ir_function_signature *sig;
260
261   /**
262    * identifier of this function signature used by the program.
263    *
264    * At the point that TGSI instructions for function calls are
265    * generated, we don't know the address of the first instruction of
266    * the function body.  So we make the BranchTarget that is called a
267    * small integer and rewrite them during set_branchtargets().
268    */
269   int sig_id;
270
271   /**
272    * Pointer to first instruction of the function body.
273    *
274    * Set during function body emits after main() is processed.
275    */
276   glsl_to_tgsi_instruction *bgn_inst;
277
278   /**
279    * Index of the first instruction of the function body in actual TGSI.
280    *
281    * Set after conversion from glsl_to_tgsi_instruction to TGSI.
282    */
283   int inst;
284
285   /** Storage for the return value. */
286   st_src_reg return_reg;
287};
288
289class glsl_to_tgsi_visitor : public ir_visitor {
290public:
291   glsl_to_tgsi_visitor();
292   ~glsl_to_tgsi_visitor();
293
294   function_entry *current_function;
295
296   struct gl_context *ctx;
297   struct gl_program *prog;
298   struct gl_shader_program *shader_program;
299   struct gl_shader_compiler_options *options;
300
301   int next_temp;
302
303   int num_address_regs;
304   int samplers_used;
305   bool indirect_addr_temps;
306   bool indirect_addr_consts;
307
308   int glsl_version;
309   bool native_integers;
310
311   variable_storage *find_variable_storage(ir_variable *var);
312
313   int add_constant(gl_register_file file, gl_constant_value values[4],
314                    int size, int datatype, GLuint *swizzle_out);
315
316   function_entry *get_function_signature(ir_function_signature *sig);
317
318   st_src_reg get_temp(const glsl_type *type);
319   void reladdr_to_temp(ir_instruction *ir, st_src_reg *reg, int *num_reladdr);
320
321   st_src_reg st_src_reg_for_float(float val);
322   st_src_reg st_src_reg_for_int(int val);
323   st_src_reg st_src_reg_for_type(int type, int val);
324
325   /**
326    * \name Visit methods
327    *
328    * As typical for the visitor pattern, there must be one \c visit method for
329    * each concrete subclass of \c ir_instruction.  Virtual base classes within
330    * the hierarchy should not have \c visit methods.
331    */
332   /*@{*/
333   virtual void visit(ir_variable *);
334   virtual void visit(ir_loop *);
335   virtual void visit(ir_loop_jump *);
336   virtual void visit(ir_function_signature *);
337   virtual void visit(ir_function *);
338   virtual void visit(ir_expression *);
339   virtual void visit(ir_swizzle *);
340   virtual void visit(ir_dereference_variable  *);
341   virtual void visit(ir_dereference_array *);
342   virtual void visit(ir_dereference_record *);
343   virtual void visit(ir_assignment *);
344   virtual void visit(ir_constant *);
345   virtual void visit(ir_call *);
346   virtual void visit(ir_return *);
347   virtual void visit(ir_discard *);
348   virtual void visit(ir_texture *);
349   virtual void visit(ir_if *);
350   /*@}*/
351
352   st_src_reg result;
353
354   /** List of variable_storage */
355   exec_list variables;
356
357   /** List of immediate_storage */
358   exec_list immediates;
359   unsigned num_immediates;
360
361   /** List of function_entry */
362   exec_list function_signatures;
363   int next_signature_id;
364
365   /** List of glsl_to_tgsi_instruction */
366   exec_list instructions;
367
368   glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op);
369
370   glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
371        		        st_dst_reg dst, st_src_reg src0);
372
373   glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
374        		        st_dst_reg dst, st_src_reg src0, st_src_reg src1);
375
376   glsl_to_tgsi_instruction *emit(ir_instruction *ir, unsigned op,
377        		        st_dst_reg dst,
378        		        st_src_reg src0, st_src_reg src1, st_src_reg src2);
379
380   unsigned get_opcode(ir_instruction *ir, unsigned op,
381                    st_dst_reg dst,
382                    st_src_reg src0, st_src_reg src1);
383
384   /**
385    * Emit the correct dot-product instruction for the type of arguments
386    */
387   glsl_to_tgsi_instruction *emit_dp(ir_instruction *ir,
388                                     st_dst_reg dst,
389                                     st_src_reg src0,
390                                     st_src_reg src1,
391                                     unsigned elements);
392
393   void emit_scalar(ir_instruction *ir, unsigned op,
394        	    st_dst_reg dst, st_src_reg src0);
395
396   void emit_scalar(ir_instruction *ir, unsigned op,
397        	    st_dst_reg dst, st_src_reg src0, st_src_reg src1);
398
399   void try_emit_float_set(ir_instruction *ir, unsigned op, st_dst_reg dst);
400
401   void emit_arl(ir_instruction *ir, st_dst_reg dst, st_src_reg src0);
402
403   void emit_scs(ir_instruction *ir, unsigned op,
404        	 st_dst_reg dst, const st_src_reg &src);
405
406   bool try_emit_mad(ir_expression *ir,
407              int mul_operand);
408   bool try_emit_mad_for_and_not(ir_expression *ir,
409              int mul_operand);
410   bool try_emit_sat(ir_expression *ir);
411
412   void emit_swz(ir_expression *ir);
413
414   bool process_move_condition(ir_rvalue *ir);
415
416   void simplify_cmp(void);
417
418   void rename_temp_register(int index, int new_index);
419   int get_first_temp_read(int index);
420   int get_first_temp_write(int index);
421   int get_last_temp_read(int index);
422   int get_last_temp_write(int index);
423
424   void copy_propagate(void);
425   void eliminate_dead_code(void);
426   int eliminate_dead_code_advanced(void);
427   void merge_registers(void);
428   void renumber_registers(void);
429
430   void *mem_ctx;
431};
432
433static st_src_reg undef_src = st_src_reg(PROGRAM_UNDEFINED, 0, GLSL_TYPE_ERROR);
434
435static st_dst_reg undef_dst = st_dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP, GLSL_TYPE_ERROR);
436
437static st_dst_reg address_reg = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT);
438
439static void
440fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
441
442static void
443fail_link(struct gl_shader_program *prog, const char *fmt, ...)
444{
445   va_list args;
446   va_start(args, fmt);
447   ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
448   va_end(args);
449
450   prog->LinkStatus = GL_FALSE;
451}
452
453static int
454swizzle_for_size(int size)
455{
456   int size_swizzles[4] = {
457      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
458      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
459      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
460      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
461   };
462
463   assert((size >= 1) && (size <= 4));
464   return size_swizzles[size - 1];
465}
466
467static bool
468is_tex_instruction(unsigned opcode)
469{
470   const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
471   return info->is_tex;
472}
473
474static unsigned
475num_inst_dst_regs(unsigned opcode)
476{
477   const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
478   return info->num_dst;
479}
480
481static unsigned
482num_inst_src_regs(unsigned opcode)
483{
484   const tgsi_opcode_info* info = tgsi_get_opcode_info(opcode);
485   return info->is_tex ? info->num_src - 1 : info->num_src;
486}
487
488glsl_to_tgsi_instruction *
489glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
490        		 st_dst_reg dst,
491        		 st_src_reg src0, st_src_reg src1, st_src_reg src2)
492{
493   glsl_to_tgsi_instruction *inst = new(mem_ctx) glsl_to_tgsi_instruction();
494   int num_reladdr = 0, i;
495
496   op = get_opcode(ir, op, dst, src0, src1);
497
498   /* If we have to do relative addressing, we want to load the ARL
499    * reg directly for one of the regs, and preload the other reladdr
500    * sources into temps.
501    */
502   num_reladdr += dst.reladdr != NULL;
503   num_reladdr += src0.reladdr != NULL;
504   num_reladdr += src1.reladdr != NULL;
505   num_reladdr += src2.reladdr != NULL;
506
507   reladdr_to_temp(ir, &src2, &num_reladdr);
508   reladdr_to_temp(ir, &src1, &num_reladdr);
509   reladdr_to_temp(ir, &src0, &num_reladdr);
510
511   if (dst.reladdr) {
512      emit_arl(ir, address_reg, *dst.reladdr);
513      num_reladdr--;
514   }
515   assert(num_reladdr == 0);
516
517   inst->op = op;
518   inst->dst = dst;
519   inst->src[0] = src0;
520   inst->src[1] = src1;
521   inst->src[2] = src2;
522   inst->ir = ir;
523   inst->dead_mask = 0;
524
525   inst->function = NULL;
526
527   if (op == TGSI_OPCODE_ARL || op == TGSI_OPCODE_UARL)
528      this->num_address_regs = 1;
529
530   /* Update indirect addressing status used by TGSI */
531   if (dst.reladdr) {
532      switch(dst.file) {
533      case PROGRAM_TEMPORARY:
534         this->indirect_addr_temps = true;
535         break;
536      case PROGRAM_LOCAL_PARAM:
537      case PROGRAM_ENV_PARAM:
538      case PROGRAM_STATE_VAR:
539      case PROGRAM_NAMED_PARAM:
540      case PROGRAM_CONSTANT:
541      case PROGRAM_UNIFORM:
542         this->indirect_addr_consts = true;
543         break;
544      case PROGRAM_IMMEDIATE:
545         assert(!"immediates should not have indirect addressing");
546         break;
547      default:
548         break;
549      }
550   }
551   else {
552      for (i=0; i<3; i++) {
553         if(inst->src[i].reladdr) {
554            switch(inst->src[i].file) {
555            case PROGRAM_TEMPORARY:
556               this->indirect_addr_temps = true;
557               break;
558            case PROGRAM_LOCAL_PARAM:
559            case PROGRAM_ENV_PARAM:
560            case PROGRAM_STATE_VAR:
561            case PROGRAM_NAMED_PARAM:
562            case PROGRAM_CONSTANT:
563            case PROGRAM_UNIFORM:
564               this->indirect_addr_consts = true;
565               break;
566            case PROGRAM_IMMEDIATE:
567               assert(!"immediates should not have indirect addressing");
568               break;
569            default:
570               break;
571            }
572         }
573      }
574   }
575
576   this->instructions.push_tail(inst);
577
578   if (native_integers)
579      try_emit_float_set(ir, op, dst);
580
581   return inst;
582}
583
584
585glsl_to_tgsi_instruction *
586glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
587        		 st_dst_reg dst, st_src_reg src0, st_src_reg src1)
588{
589   return emit(ir, op, dst, src0, src1, undef_src);
590}
591
592glsl_to_tgsi_instruction *
593glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op,
594        		 st_dst_reg dst, st_src_reg src0)
595{
596   assert(dst.writemask != 0);
597   return emit(ir, op, dst, src0, undef_src, undef_src);
598}
599
600glsl_to_tgsi_instruction *
601glsl_to_tgsi_visitor::emit(ir_instruction *ir, unsigned op)
602{
603   return emit(ir, op, undef_dst, undef_src, undef_src, undef_src);
604}
605
606 /**
607 * Emits the code to convert the result of float SET instructions to integers.
608 */
609void
610glsl_to_tgsi_visitor::try_emit_float_set(ir_instruction *ir, unsigned op,
611        		 st_dst_reg dst)
612{
613   if ((op == TGSI_OPCODE_SEQ ||
614        op == TGSI_OPCODE_SNE ||
615        op == TGSI_OPCODE_SGE ||
616        op == TGSI_OPCODE_SLT))
617   {
618      st_src_reg src = st_src_reg(dst);
619      src.negate = ~src.negate;
620      dst.type = GLSL_TYPE_FLOAT;
621      emit(ir, TGSI_OPCODE_F2I, dst, src);
622   }
623}
624
625/**
626 * Determines whether to use an integer, unsigned integer, or float opcode
627 * based on the operands and input opcode, then emits the result.
628 */
629unsigned
630glsl_to_tgsi_visitor::get_opcode(ir_instruction *ir, unsigned op,
631        		 st_dst_reg dst,
632        		 st_src_reg src0, st_src_reg src1)
633{
634   int type = GLSL_TYPE_FLOAT;
635
636   if (src0.type == GLSL_TYPE_FLOAT || src1.type == GLSL_TYPE_FLOAT)
637      type = GLSL_TYPE_FLOAT;
638   else if (native_integers)
639      type = src0.type == GLSL_TYPE_BOOL ? GLSL_TYPE_INT : src0.type;
640
641#define case4(c, f, i, u) \
642   case TGSI_OPCODE_##c: \
643      if (type == GLSL_TYPE_INT) op = TGSI_OPCODE_##i; \
644      else if (type == GLSL_TYPE_UINT) op = TGSI_OPCODE_##u; \
645      else op = TGSI_OPCODE_##f; \
646      break;
647#define case3(f, i, u)  case4(f, f, i, u)
648#define case2fi(f, i)   case4(f, f, i, i)
649#define case2iu(i, u)   case4(i, LAST, i, u)
650
651   switch(op) {
652      case2fi(ADD, UADD);
653      case2fi(MUL, UMUL);
654      case2fi(MAD, UMAD);
655      case3(DIV, IDIV, UDIV);
656      case3(MAX, IMAX, UMAX);
657      case3(MIN, IMIN, UMIN);
658      case2iu(MOD, UMOD);
659
660      case2fi(SEQ, USEQ);
661      case2fi(SNE, USNE);
662      case3(SGE, ISGE, USGE);
663      case3(SLT, ISLT, USLT);
664
665      case2iu(ISHR, USHR);
666
667      case2fi(SSG, ISSG);
668      case3(ABS, IABS, IABS);
669
670      default: break;
671   }
672
673   assert(op != TGSI_OPCODE_LAST);
674   return op;
675}
676
677glsl_to_tgsi_instruction *
678glsl_to_tgsi_visitor::emit_dp(ir_instruction *ir,
679        		    st_dst_reg dst, st_src_reg src0, st_src_reg src1,
680        		    unsigned elements)
681{
682   static const unsigned dot_opcodes[] = {
683      TGSI_OPCODE_DP2, TGSI_OPCODE_DP3, TGSI_OPCODE_DP4
684   };
685
686   return emit(ir, dot_opcodes[elements - 2], dst, src0, src1);
687}
688
689/**
690 * Emits TGSI scalar opcodes to produce unique answers across channels.
691 *
692 * Some TGSI opcodes are scalar-only, like ARB_fp/vp.  The src X
693 * channel determines the result across all channels.  So to do a vec4
694 * of this operation, we want to emit a scalar per source channel used
695 * to produce dest channels.
696 */
697void
698glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
699        		        st_dst_reg dst,
700        			st_src_reg orig_src0, st_src_reg orig_src1)
701{
702   int i, j;
703   int done_mask = ~dst.writemask;
704
705   /* TGSI RCP is a scalar operation splatting results to all channels,
706    * like ARB_fp/vp.  So emit as many RCPs as necessary to cover our
707    * dst channels.
708    */
709   for (i = 0; i < 4; i++) {
710      GLuint this_mask = (1 << i);
711      glsl_to_tgsi_instruction *inst;
712      st_src_reg src0 = orig_src0;
713      st_src_reg src1 = orig_src1;
714
715      if (done_mask & this_mask)
716         continue;
717
718      GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
719      GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
720      for (j = i + 1; j < 4; j++) {
721         /* If there is another enabled component in the destination that is
722          * derived from the same inputs, generate its value on this pass as
723          * well.
724          */
725         if (!(done_mask & (1 << j)) &&
726             GET_SWZ(src0.swizzle, j) == src0_swiz &&
727             GET_SWZ(src1.swizzle, j) == src1_swiz) {
728            this_mask |= (1 << j);
729         }
730      }
731      src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
732        			   src0_swiz, src0_swiz);
733      src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
734        			  src1_swiz, src1_swiz);
735
736      inst = emit(ir, op, dst, src0, src1);
737      inst->dst.writemask = this_mask;
738      done_mask |= this_mask;
739   }
740}
741
742void
743glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
744        		        st_dst_reg dst, st_src_reg src0)
745{
746   st_src_reg undef = undef_src;
747
748   undef.swizzle = SWIZZLE_XXXX;
749
750   emit_scalar(ir, op, dst, src0, undef);
751}
752
753void
754glsl_to_tgsi_visitor::emit_arl(ir_instruction *ir,
755        		        st_dst_reg dst, st_src_reg src0)
756{
757   int op = TGSI_OPCODE_ARL;
758
759   if (src0.type == GLSL_TYPE_INT || src0.type == GLSL_TYPE_UINT)
760      op = TGSI_OPCODE_UARL;
761
762   emit(NULL, op, dst, src0);
763}
764
765/**
766 * Emit an TGSI_OPCODE_SCS instruction
767 *
768 * The \c SCS opcode functions a bit differently than the other TGSI opcodes.
769 * Instead of splatting its result across all four components of the
770 * destination, it writes one value to the \c x component and another value to
771 * the \c y component.
772 *
773 * \param ir        IR instruction being processed
774 * \param op        Either \c TGSI_OPCODE_SIN or \c TGSI_OPCODE_COS depending
775 *                  on which value is desired.
776 * \param dst       Destination register
777 * \param src       Source register
778 */
779void
780glsl_to_tgsi_visitor::emit_scs(ir_instruction *ir, unsigned op,
781        		     st_dst_reg dst,
782        		     const st_src_reg &src)
783{
784   /* Vertex programs cannot use the SCS opcode.
785    */
786   if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
787      emit_scalar(ir, op, dst, src);
788      return;
789   }
790
791   const unsigned component = (op == TGSI_OPCODE_SIN) ? 0 : 1;
792   const unsigned scs_mask = (1U << component);
793   int done_mask = ~dst.writemask;
794   st_src_reg tmp;
795
796   assert(op == TGSI_OPCODE_SIN || op == TGSI_OPCODE_COS);
797
798   /* If there are compnents in the destination that differ from the component
799    * that will be written by the SCS instrution, we'll need a temporary.
800    */
801   if (scs_mask != unsigned(dst.writemask)) {
802      tmp = get_temp(glsl_type::vec4_type);
803   }
804
805   for (unsigned i = 0; i < 4; i++) {
806      unsigned this_mask = (1U << i);
807      st_src_reg src0 = src;
808
809      if ((done_mask & this_mask) != 0)
810         continue;
811
812      /* The source swizzle specified which component of the source generates
813       * sine / cosine for the current component in the destination.  The SCS
814       * instruction requires that this value be swizzle to the X component.
815       * Replace the current swizzle with a swizzle that puts the source in
816       * the X component.
817       */
818      unsigned src0_swiz = GET_SWZ(src.swizzle, i);
819
820      src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
821        			   src0_swiz, src0_swiz);
822      for (unsigned j = i + 1; j < 4; j++) {
823         /* If there is another enabled component in the destination that is
824          * derived from the same inputs, generate its value on this pass as
825          * well.
826          */
827         if (!(done_mask & (1 << j)) &&
828             GET_SWZ(src0.swizzle, j) == src0_swiz) {
829            this_mask |= (1 << j);
830         }
831      }
832
833      if (this_mask != scs_mask) {
834         glsl_to_tgsi_instruction *inst;
835         st_dst_reg tmp_dst = st_dst_reg(tmp);
836
837         /* Emit the SCS instruction.
838          */
839         inst = emit(ir, TGSI_OPCODE_SCS, tmp_dst, src0);
840         inst->dst.writemask = scs_mask;
841
842         /* Move the result of the SCS instruction to the desired location in
843          * the destination.
844          */
845         tmp.swizzle = MAKE_SWIZZLE4(component, component,
846        			     component, component);
847         inst = emit(ir, TGSI_OPCODE_SCS, dst, tmp);
848         inst->dst.writemask = this_mask;
849      } else {
850         /* Emit the SCS instruction to write directly to the destination.
851          */
852         glsl_to_tgsi_instruction *inst = emit(ir, TGSI_OPCODE_SCS, dst, src0);
853         inst->dst.writemask = scs_mask;
854      }
855
856      done_mask |= this_mask;
857   }
858}
859
860int
861glsl_to_tgsi_visitor::add_constant(gl_register_file file,
862        		     gl_constant_value values[4], int size, int datatype,
863        		     GLuint *swizzle_out)
864{
865   if (file == PROGRAM_CONSTANT) {
866      return _mesa_add_typed_unnamed_constant(this->prog->Parameters, values,
867                                              size, datatype, swizzle_out);
868   } else {
869      int index = 0;
870      immediate_storage *entry;
871      assert(file == PROGRAM_IMMEDIATE);
872
873      /* Search immediate storage to see if we already have an identical
874       * immediate that we can use instead of adding a duplicate entry.
875       */
876      foreach_iter(exec_list_iterator, iter, this->immediates) {
877         entry = (immediate_storage *)iter.get();
878
879         if (entry->size == size &&
880             entry->type == datatype &&
881             !memcmp(entry->values, values, size * sizeof(gl_constant_value))) {
882             return index;
883         }
884         index++;
885      }
886
887      /* Add this immediate to the list. */
888      entry = new(mem_ctx) immediate_storage(values, size, datatype);
889      this->immediates.push_tail(entry);
890      this->num_immediates++;
891      return index;
892   }
893}
894
895st_src_reg
896glsl_to_tgsi_visitor::st_src_reg_for_float(float val)
897{
898   st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_FLOAT);
899   union gl_constant_value uval;
900
901   uval.f = val;
902   src.index = add_constant(src.file, &uval, 1, GL_FLOAT, &src.swizzle);
903
904   return src;
905}
906
907st_src_reg
908glsl_to_tgsi_visitor::st_src_reg_for_int(int val)
909{
910   st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT);
911   union gl_constant_value uval;
912
913   assert(native_integers);
914
915   uval.i = val;
916   src.index = add_constant(src.file, &uval, 1, GL_INT, &src.swizzle);
917
918   return src;
919}
920
921st_src_reg
922glsl_to_tgsi_visitor::st_src_reg_for_type(int type, int val)
923{
924   if (native_integers)
925      return type == GLSL_TYPE_FLOAT ? st_src_reg_for_float(val) :
926                                       st_src_reg_for_int(val);
927   else
928      return st_src_reg_for_float(val);
929}
930
931static int
932type_size(const struct glsl_type *type)
933{
934   unsigned int i;
935   int size;
936
937   switch (type->base_type) {
938   case GLSL_TYPE_UINT:
939   case GLSL_TYPE_INT:
940   case GLSL_TYPE_FLOAT:
941   case GLSL_TYPE_BOOL:
942      if (type->is_matrix()) {
943         return type->matrix_columns;
944      } else {
945         /* Regardless of size of vector, it gets a vec4. This is bad
946          * packing for things like floats, but otherwise arrays become a
947          * mess.  Hopefully a later pass over the code can pack scalars
948          * down if appropriate.
949          */
950         return 1;
951      }
952   case GLSL_TYPE_ARRAY:
953      assert(type->length > 0);
954      return type_size(type->fields.array) * type->length;
955   case GLSL_TYPE_STRUCT:
956      size = 0;
957      for (i = 0; i < type->length; i++) {
958         size += type_size(type->fields.structure[i].type);
959      }
960      return size;
961   case GLSL_TYPE_SAMPLER:
962      /* Samplers take up one slot in UNIFORMS[], but they're baked in
963       * at link time.
964       */
965      return 1;
966   default:
967      assert(0);
968      return 0;
969   }
970}
971
972/**
973 * In the initial pass of codegen, we assign temporary numbers to
974 * intermediate results.  (not SSA -- variable assignments will reuse
975 * storage).
976 */
977st_src_reg
978glsl_to_tgsi_visitor::get_temp(const glsl_type *type)
979{
980   st_src_reg src;
981
982   src.type = native_integers ? type->base_type : GLSL_TYPE_FLOAT;
983   src.file = PROGRAM_TEMPORARY;
984   src.index = next_temp;
985   src.reladdr = NULL;
986   next_temp += type_size(type);
987
988   if (type->is_array() || type->is_record()) {
989      src.swizzle = SWIZZLE_NOOP;
990   } else {
991      src.swizzle = swizzle_for_size(type->vector_elements);
992   }
993   src.negate = 0;
994
995   return src;
996}
997
998variable_storage *
999glsl_to_tgsi_visitor::find_variable_storage(ir_variable *var)
1000{
1001
1002   variable_storage *entry;
1003
1004   foreach_iter(exec_list_iterator, iter, this->variables) {
1005      entry = (variable_storage *)iter.get();
1006
1007      if (entry->var == var)
1008         return entry;
1009   }
1010
1011   return NULL;
1012}
1013
1014void
1015glsl_to_tgsi_visitor::visit(ir_variable *ir)
1016{
1017   if (strcmp(ir->name, "gl_FragCoord") == 0) {
1018      struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
1019
1020      fp->OriginUpperLeft = ir->origin_upper_left;
1021      fp->PixelCenterInteger = ir->pixel_center_integer;
1022   }
1023
1024   if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
1025      unsigned int i;
1026      const ir_state_slot *const slots = ir->state_slots;
1027      assert(ir->state_slots != NULL);
1028
1029      /* Check if this statevar's setup in the STATE file exactly
1030       * matches how we'll want to reference it as a
1031       * struct/array/whatever.  If not, then we need to move it into
1032       * temporary storage and hope that it'll get copy-propagated
1033       * out.
1034       */
1035      for (i = 0; i < ir->num_state_slots; i++) {
1036         if (slots[i].swizzle != SWIZZLE_XYZW) {
1037            break;
1038         }
1039      }
1040
1041      variable_storage *storage;
1042      st_dst_reg dst;
1043      if (i == ir->num_state_slots) {
1044         /* We'll set the index later. */
1045         storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
1046         this->variables.push_tail(storage);
1047
1048         dst = undef_dst;
1049      } else {
1050         /* The variable_storage constructor allocates slots based on the size
1051          * of the type.  However, this had better match the number of state
1052          * elements that we're going to copy into the new temporary.
1053          */
1054         assert((int) ir->num_state_slots == type_size(ir->type));
1055
1056         storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
1057        					 this->next_temp);
1058         this->variables.push_tail(storage);
1059         this->next_temp += type_size(ir->type);
1060
1061         dst = st_dst_reg(st_src_reg(PROGRAM_TEMPORARY, storage->index,
1062               native_integers ? ir->type->base_type : GLSL_TYPE_FLOAT));
1063      }
1064
1065
1066      for (unsigned int i = 0; i < ir->num_state_slots; i++) {
1067         int index = _mesa_add_state_reference(this->prog->Parameters,
1068        				       (gl_state_index *)slots[i].tokens);
1069
1070         if (storage->file == PROGRAM_STATE_VAR) {
1071            if (storage->index == -1) {
1072               storage->index = index;
1073            } else {
1074               assert(index == storage->index + (int)i);
1075            }
1076         } else {
1077            st_src_reg src(PROGRAM_STATE_VAR, index,
1078                  native_integers ? ir->type->base_type : GLSL_TYPE_FLOAT);
1079            src.swizzle = slots[i].swizzle;
1080            emit(ir, TGSI_OPCODE_MOV, dst, src);
1081            /* even a float takes up a whole vec4 reg in a struct/array. */
1082            dst.index++;
1083         }
1084      }
1085
1086      if (storage->file == PROGRAM_TEMPORARY &&
1087          dst.index != storage->index + (int) ir->num_state_slots) {
1088         fail_link(this->shader_program,
1089        	   "failed to load builtin uniform `%s'  (%d/%d regs loaded)\n",
1090        	   ir->name, dst.index - storage->index,
1091        	   type_size(ir->type));
1092      }
1093   }
1094}
1095
1096void
1097glsl_to_tgsi_visitor::visit(ir_loop *ir)
1098{
1099   ir_dereference_variable *counter = NULL;
1100
1101   if (ir->counter != NULL)
1102      counter = new(ir) ir_dereference_variable(ir->counter);
1103
1104   if (ir->from != NULL) {
1105      assert(ir->counter != NULL);
1106
1107      ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
1108
1109      a->accept(this);
1110      delete a;
1111   }
1112
1113   emit(NULL, TGSI_OPCODE_BGNLOOP);
1114
1115   if (ir->to) {
1116      ir_expression *e =
1117         new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
1118        		       counter, ir->to);
1119      ir_if *if_stmt =  new(ir) ir_if(e);
1120
1121      ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
1122
1123      if_stmt->then_instructions.push_tail(brk);
1124
1125      if_stmt->accept(this);
1126
1127      delete if_stmt;
1128      delete e;
1129      delete brk;
1130   }
1131
1132   visit_exec_list(&ir->body_instructions, this);
1133
1134   if (ir->increment) {
1135      ir_expression *e =
1136         new(ir) ir_expression(ir_binop_add, counter->type,
1137        		       counter, ir->increment);
1138
1139      ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
1140
1141      a->accept(this);
1142      delete a;
1143      delete e;
1144   }
1145
1146   emit(NULL, TGSI_OPCODE_ENDLOOP);
1147}
1148
1149void
1150glsl_to_tgsi_visitor::visit(ir_loop_jump *ir)
1151{
1152   switch (ir->mode) {
1153   case ir_loop_jump::jump_break:
1154      emit(NULL, TGSI_OPCODE_BRK);
1155      break;
1156   case ir_loop_jump::jump_continue:
1157      emit(NULL, TGSI_OPCODE_CONT);
1158      break;
1159   }
1160}
1161
1162
1163void
1164glsl_to_tgsi_visitor::visit(ir_function_signature *ir)
1165{
1166   assert(0);
1167   (void)ir;
1168}
1169
1170void
1171glsl_to_tgsi_visitor::visit(ir_function *ir)
1172{
1173   /* Ignore function bodies other than main() -- we shouldn't see calls to
1174    * them since they should all be inlined before we get to glsl_to_tgsi.
1175    */
1176   if (strcmp(ir->name, "main") == 0) {
1177      const ir_function_signature *sig;
1178      exec_list empty;
1179
1180      sig = ir->matching_signature(&empty);
1181
1182      assert(sig);
1183
1184      foreach_iter(exec_list_iterator, iter, sig->body) {
1185         ir_instruction *ir = (ir_instruction *)iter.get();
1186
1187         ir->accept(this);
1188      }
1189   }
1190}
1191
1192bool
1193glsl_to_tgsi_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1194{
1195   int nonmul_operand = 1 - mul_operand;
1196   st_src_reg a, b, c;
1197   st_dst_reg result_dst;
1198
1199   ir_expression *expr = ir->operands[mul_operand]->as_expression();
1200   if (!expr || expr->operation != ir_binop_mul)
1201      return false;
1202
1203   expr->operands[0]->accept(this);
1204   a = this->result;
1205   expr->operands[1]->accept(this);
1206   b = this->result;
1207   ir->operands[nonmul_operand]->accept(this);
1208   c = this->result;
1209
1210   this->result = get_temp(ir->type);
1211   result_dst = st_dst_reg(this->result);
1212   result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1213   emit(ir, TGSI_OPCODE_MAD, result_dst, a, b, c);
1214
1215   return true;
1216}
1217
1218/**
1219 * Emit MAD(a, -b, a) instead of AND(a, NOT(b))
1220 *
1221 * The logic values are 1.0 for true and 0.0 for false.  Logical-and is
1222 * implemented using multiplication, and logical-or is implemented using
1223 * addition.  Logical-not can be implemented as (true - x), or (1.0 - x).
1224 * As result, the logical expression (a & !b) can be rewritten as:
1225 *
1226 *     - a * !b
1227 *     - a * (1 - b)
1228 *     - (a * 1) - (a * b)
1229 *     - a + -(a * b)
1230 *     - a + (a * -b)
1231 *
1232 * This final expression can be implemented as a single MAD(a, -b, a)
1233 * instruction.
1234 */
1235bool
1236glsl_to_tgsi_visitor::try_emit_mad_for_and_not(ir_expression *ir, int try_operand)
1237{
1238   const int other_operand = 1 - try_operand;
1239   st_src_reg a, b;
1240
1241   ir_expression *expr = ir->operands[try_operand]->as_expression();
1242   if (!expr || expr->operation != ir_unop_logic_not)
1243      return false;
1244
1245   ir->operands[other_operand]->accept(this);
1246   a = this->result;
1247   expr->operands[0]->accept(this);
1248   b = this->result;
1249
1250   b.negate = ~b.negate;
1251
1252   this->result = get_temp(ir->type);
1253   emit(ir, TGSI_OPCODE_MAD, st_dst_reg(this->result), a, b, a);
1254
1255   return true;
1256}
1257
1258bool
1259glsl_to_tgsi_visitor::try_emit_sat(ir_expression *ir)
1260{
1261   /* Saturates were only introduced to vertex programs in
1262    * NV_vertex_program3, so don't give them to drivers in the VP.
1263    */
1264   if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
1265      return false;
1266
1267   ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
1268   if (!sat_src)
1269      return false;
1270
1271   sat_src->accept(this);
1272   st_src_reg src = this->result;
1273
1274   /* If we generated an expression instruction into a temporary in
1275    * processing the saturate's operand, apply the saturate to that
1276    * instruction.  Otherwise, generate a MOV to do the saturate.
1277    *
1278    * Note that we have to be careful to only do this optimization if
1279    * the instruction in question was what generated src->result.  For
1280    * example, ir_dereference_array might generate a MUL instruction
1281    * to create the reladdr, and return us a src reg using that
1282    * reladdr.  That MUL result is not the value we're trying to
1283    * saturate.
1284    */
1285   ir_expression *sat_src_expr = sat_src->as_expression();
1286   if (sat_src_expr && (sat_src_expr->operation == ir_binop_mul ||
1287			sat_src_expr->operation == ir_binop_add ||
1288			sat_src_expr->operation == ir_binop_dot)) {
1289      glsl_to_tgsi_instruction *new_inst;
1290      new_inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
1291      new_inst->saturate = true;
1292   } else {
1293      this->result = get_temp(ir->type);
1294      st_dst_reg result_dst = st_dst_reg(this->result);
1295      result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1296      glsl_to_tgsi_instruction *inst;
1297      inst = emit(ir, TGSI_OPCODE_MOV, result_dst, src);
1298      inst->saturate = true;
1299   }
1300
1301   return true;
1302}
1303
1304void
1305glsl_to_tgsi_visitor::reladdr_to_temp(ir_instruction *ir,
1306        			    st_src_reg *reg, int *num_reladdr)
1307{
1308   if (!reg->reladdr)
1309      return;
1310
1311   emit_arl(ir, address_reg, *reg->reladdr);
1312
1313   if (*num_reladdr != 1) {
1314      st_src_reg temp = get_temp(glsl_type::vec4_type);
1315
1316      emit(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), *reg);
1317      *reg = temp;
1318   }
1319
1320   (*num_reladdr)--;
1321}
1322
1323void
1324glsl_to_tgsi_visitor::visit(ir_expression *ir)
1325{
1326   unsigned int operand;
1327   st_src_reg op[Elements(ir->operands)];
1328   st_src_reg result_src;
1329   st_dst_reg result_dst;
1330
1331   /* Quick peephole: Emit MAD(a, b, c) instead of ADD(MUL(a, b), c)
1332    */
1333   if (ir->operation == ir_binop_add) {
1334      if (try_emit_mad(ir, 1))
1335         return;
1336      if (try_emit_mad(ir, 0))
1337         return;
1338   }
1339
1340   /* Quick peephole: Emit OPCODE_MAD(-a, -b, a) instead of AND(a, NOT(b))
1341    */
1342   if (ir->operation == ir_binop_logic_and) {
1343      if (try_emit_mad_for_and_not(ir, 1))
1344	 return;
1345      if (try_emit_mad_for_and_not(ir, 0))
1346	 return;
1347   }
1348
1349   if (try_emit_sat(ir))
1350      return;
1351
1352   if (ir->operation == ir_quadop_vector)
1353      assert(!"ir_quadop_vector should have been lowered");
1354
1355   for (operand = 0; operand < ir->get_num_operands(); operand++) {
1356      this->result.file = PROGRAM_UNDEFINED;
1357      ir->operands[operand]->accept(this);
1358      if (this->result.file == PROGRAM_UNDEFINED) {
1359         ir_print_visitor v;
1360         printf("Failed to get tree for expression operand:\n");
1361         ir->operands[operand]->accept(&v);
1362         exit(1);
1363      }
1364      op[operand] = this->result;
1365
1366      /* Matrix expression operands should have been broken down to vector
1367       * operations already.
1368       */
1369      assert(!ir->operands[operand]->type->is_matrix());
1370   }
1371
1372   int vector_elements = ir->operands[0]->type->vector_elements;
1373   if (ir->operands[1]) {
1374      vector_elements = MAX2(vector_elements,
1375        		     ir->operands[1]->type->vector_elements);
1376   }
1377
1378   this->result.file = PROGRAM_UNDEFINED;
1379
1380   /* Storage for our result.  Ideally for an assignment we'd be using
1381    * the actual storage for the result here, instead.
1382    */
1383   result_src = get_temp(ir->type);
1384   /* convenience for the emit functions below. */
1385   result_dst = st_dst_reg(result_src);
1386   /* Limit writes to the channels that will be used by result_src later.
1387    * This does limit this temp's use as a temporary for multi-instruction
1388    * sequences.
1389    */
1390   result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1391
1392   switch (ir->operation) {
1393   case ir_unop_logic_not:
1394      if (result_dst.type != GLSL_TYPE_FLOAT)
1395         emit(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1396      else {
1397         /* Previously 'SEQ dst, src, 0.0' was used for this.  However, many
1398          * older GPUs implement SEQ using multiple instructions (i915 uses two
1399          * SGE instructions and a MUL instruction).  Since our logic values are
1400          * 0.0 and 1.0, 1-x also implements !x.
1401          */
1402         op[0].negate = ~op[0].negate;
1403         emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], st_src_reg_for_float(1.0));
1404      }
1405      break;
1406   case ir_unop_neg:
1407      if (result_dst.type == GLSL_TYPE_INT || result_dst.type == GLSL_TYPE_UINT)
1408         emit(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1409      else {
1410         op[0].negate = ~op[0].negate;
1411         result_src = op[0];
1412      }
1413      break;
1414   case ir_unop_abs:
1415      emit(ir, TGSI_OPCODE_ABS, result_dst, op[0]);
1416      break;
1417   case ir_unop_sign:
1418      emit(ir, TGSI_OPCODE_SSG, result_dst, op[0]);
1419      break;
1420   case ir_unop_rcp:
1421      emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, op[0]);
1422      break;
1423
1424   case ir_unop_exp2:
1425      emit_scalar(ir, TGSI_OPCODE_EX2, result_dst, op[0]);
1426      break;
1427   case ir_unop_exp:
1428   case ir_unop_log:
1429      assert(!"not reached: should be handled by ir_explog_to_explog2");
1430      break;
1431   case ir_unop_log2:
1432      emit_scalar(ir, TGSI_OPCODE_LG2, result_dst, op[0]);
1433      break;
1434   case ir_unop_sin:
1435      emit_scalar(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1436      break;
1437   case ir_unop_cos:
1438      emit_scalar(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1439      break;
1440   case ir_unop_sin_reduced:
1441      emit_scs(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1442      break;
1443   case ir_unop_cos_reduced:
1444      emit_scs(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1445      break;
1446
1447   case ir_unop_dFdx:
1448      emit(ir, TGSI_OPCODE_DDX, result_dst, op[0]);
1449      break;
1450   case ir_unop_dFdy:
1451      op[0].negate = ~op[0].negate;
1452      emit(ir, TGSI_OPCODE_DDY, result_dst, op[0]);
1453      break;
1454
1455   case ir_unop_noise: {
1456      /* At some point, a motivated person could add a better
1457       * implementation of noise.  Currently not even the nvidia
1458       * binary drivers do anything more than this.  In any case, the
1459       * place to do this is in the GL state tracker, not the poor
1460       * driver.
1461       */
1462      emit(ir, TGSI_OPCODE_MOV, result_dst, st_src_reg_for_float(0.5));
1463      break;
1464   }
1465
1466   case ir_binop_add:
1467      emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1468      break;
1469   case ir_binop_sub:
1470      emit(ir, TGSI_OPCODE_SUB, result_dst, op[0], op[1]);
1471      break;
1472
1473   case ir_binop_mul:
1474      emit(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1475      break;
1476   case ir_binop_div:
1477      if (result_dst.type == GLSL_TYPE_FLOAT)
1478         assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1479      else
1480         emit(ir, TGSI_OPCODE_DIV, result_dst, op[0], op[1]);
1481      break;
1482   case ir_binop_mod:
1483      if (result_dst.type == GLSL_TYPE_FLOAT)
1484         assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1485      else
1486         emit(ir, TGSI_OPCODE_MOD, result_dst, op[0], op[1]);
1487      break;
1488
1489   case ir_binop_less:
1490      emit(ir, TGSI_OPCODE_SLT, result_dst, op[0], op[1]);
1491      break;
1492   case ir_binop_greater:
1493      emit(ir, TGSI_OPCODE_SLT, result_dst, op[1], op[0]);
1494      break;
1495   case ir_binop_lequal:
1496      emit(ir, TGSI_OPCODE_SGE, result_dst, op[1], op[0]);
1497      break;
1498   case ir_binop_gequal:
1499      emit(ir, TGSI_OPCODE_SGE, result_dst, op[0], op[1]);
1500      break;
1501   case ir_binop_equal:
1502      emit(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1503      break;
1504   case ir_binop_nequal:
1505      emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1506      break;
1507   case ir_binop_all_equal:
1508      /* "==" operator producing a scalar boolean. */
1509      if (ir->operands[0]->type->is_vector() ||
1510          ir->operands[1]->type->is_vector()) {
1511         st_src_reg temp = get_temp(native_integers ?
1512               glsl_type::get_instance(ir->operands[0]->type->base_type, 4, 1) :
1513               glsl_type::vec4_type);
1514
1515         if (native_integers) {
1516            st_dst_reg temp_dst = st_dst_reg(temp);
1517            st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1518
1519            emit(ir, TGSI_OPCODE_SEQ, st_dst_reg(temp), op[0], op[1]);
1520
1521            /* Emit 1-3 AND operations to combine the SEQ results. */
1522            switch (ir->operands[0]->type->vector_elements) {
1523            case 2:
1524               break;
1525            case 3:
1526               temp_dst.writemask = WRITEMASK_Y;
1527               temp1.swizzle = SWIZZLE_YYYY;
1528               temp2.swizzle = SWIZZLE_ZZZZ;
1529               emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1530               break;
1531            case 4:
1532               temp_dst.writemask = WRITEMASK_X;
1533               temp1.swizzle = SWIZZLE_XXXX;
1534               temp2.swizzle = SWIZZLE_YYYY;
1535               emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1536               temp_dst.writemask = WRITEMASK_Y;
1537               temp1.swizzle = SWIZZLE_ZZZZ;
1538               temp2.swizzle = SWIZZLE_WWWW;
1539               emit(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1540            }
1541
1542            temp1.swizzle = SWIZZLE_XXXX;
1543            temp2.swizzle = SWIZZLE_YYYY;
1544            emit(ir, TGSI_OPCODE_AND, result_dst, temp1, temp2);
1545         } else {
1546            emit(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1547
1548            /* After the dot-product, the value will be an integer on the
1549             * range [0,4].  Zero becomes 1.0, and positive values become zero.
1550             */
1551            emit_dp(ir, result_dst, temp, temp, vector_elements);
1552
1553            /* Negating the result of the dot-product gives values on the range
1554             * [-4, 0].  Zero becomes 1.0, and negative values become zero.
1555             * This is achieved using SGE.
1556             */
1557            st_src_reg sge_src = result_src;
1558            sge_src.negate = ~sge_src.negate;
1559            emit(ir, TGSI_OPCODE_SGE, result_dst, sge_src, st_src_reg_for_float(0.0));
1560         }
1561      } else {
1562         emit(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1563      }
1564      break;
1565   case ir_binop_any_nequal:
1566      /* "!=" operator producing a scalar boolean. */
1567      if (ir->operands[0]->type->is_vector() ||
1568          ir->operands[1]->type->is_vector()) {
1569         st_src_reg temp = get_temp(native_integers ?
1570               glsl_type::get_instance(ir->operands[0]->type->base_type, 4, 1) :
1571               glsl_type::vec4_type);
1572         emit(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1573
1574         if (native_integers) {
1575            st_dst_reg temp_dst = st_dst_reg(temp);
1576            st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1577
1578            /* Emit 1-3 OR operations to combine the SNE results. */
1579            switch (ir->operands[0]->type->vector_elements) {
1580            case 2:
1581               break;
1582            case 3:
1583               temp_dst.writemask = WRITEMASK_Y;
1584               temp1.swizzle = SWIZZLE_YYYY;
1585               temp2.swizzle = SWIZZLE_ZZZZ;
1586               emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1587               break;
1588            case 4:
1589               temp_dst.writemask = WRITEMASK_X;
1590               temp1.swizzle = SWIZZLE_XXXX;
1591               temp2.swizzle = SWIZZLE_YYYY;
1592               emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1593               temp_dst.writemask = WRITEMASK_Y;
1594               temp1.swizzle = SWIZZLE_ZZZZ;
1595               temp2.swizzle = SWIZZLE_WWWW;
1596               emit(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1597            }
1598
1599            temp1.swizzle = SWIZZLE_XXXX;
1600            temp2.swizzle = SWIZZLE_YYYY;
1601            emit(ir, TGSI_OPCODE_OR, result_dst, temp1, temp2);
1602         } else {
1603            /* After the dot-product, the value will be an integer on the
1604             * range [0,4].  Zero stays zero, and positive values become 1.0.
1605             */
1606            glsl_to_tgsi_instruction *const dp =
1607                  emit_dp(ir, result_dst, temp, temp, vector_elements);
1608            if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1609               /* The clamping to [0,1] can be done for free in the fragment
1610                * shader with a saturate.
1611                */
1612               dp->saturate = true;
1613            } else {
1614               /* Negating the result of the dot-product gives values on the range
1615                * [-4, 0].  Zero stays zero, and negative values become 1.0.  This
1616                * achieved using SLT.
1617                */
1618               st_src_reg slt_src = result_src;
1619               slt_src.negate = ~slt_src.negate;
1620               emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1621            }
1622         }
1623      } else {
1624         emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1625      }
1626      break;
1627
1628   case ir_unop_any: {
1629      assert(ir->operands[0]->type->is_vector());
1630
1631      /* After the dot-product, the value will be an integer on the
1632       * range [0,4].  Zero stays zero, and positive values become 1.0.
1633       */
1634      glsl_to_tgsi_instruction *const dp =
1635         emit_dp(ir, result_dst, op[0], op[0],
1636                 ir->operands[0]->type->vector_elements);
1637      if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
1638          result_dst.type == GLSL_TYPE_FLOAT) {
1639	      /* The clamping to [0,1] can be done for free in the fragment
1640	       * shader with a saturate.
1641	       */
1642	      dp->saturate = true;
1643      } else if (result_dst.type == GLSL_TYPE_FLOAT) {
1644	      /* Negating the result of the dot-product gives values on the range
1645	       * [-4, 0].  Zero stays zero, and negative values become 1.0.  This
1646	       * is achieved using SLT.
1647	       */
1648	      st_src_reg slt_src = result_src;
1649	      slt_src.negate = ~slt_src.negate;
1650	      emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1651      }
1652      else {
1653         /* Use SNE 0 if integers are being used as boolean values. */
1654         emit(ir, TGSI_OPCODE_SNE, result_dst, result_src, st_src_reg_for_int(0));
1655      }
1656      break;
1657   }
1658
1659   case ir_binop_logic_xor:
1660      if (native_integers)
1661         emit(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1662      else
1663         emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1664      break;
1665
1666   case ir_binop_logic_or: {
1667      if (native_integers) {
1668         /* If integers are used as booleans, we can use an actual "or"
1669          * instruction.
1670          */
1671         assert(native_integers);
1672         emit(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1673      } else {
1674         /* After the addition, the value will be an integer on the
1675          * range [0,2].  Zero stays zero, and positive values become 1.0.
1676          */
1677         glsl_to_tgsi_instruction *add =
1678            emit(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1679         if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1680            /* The clamping to [0,1] can be done for free in the fragment
1681             * shader with a saturate if floats are being used as boolean values.
1682             */
1683            add->saturate = true;
1684         } else {
1685            /* Negating the result of the addition gives values on the range
1686             * [-2, 0].  Zero stays zero, and negative values become 1.0.  This
1687             * is achieved using SLT.
1688             */
1689            st_src_reg slt_src = result_src;
1690            slt_src.negate = ~slt_src.negate;
1691            emit(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1692         }
1693      }
1694      break;
1695   }
1696
1697   case ir_binop_logic_and:
1698      /* If native integers are disabled, the bool args are stored as float 0.0
1699       * or 1.0, so "mul" gives us "and".  If they're enabled, just use the
1700       * actual AND opcode.
1701       */
1702      if (native_integers)
1703         emit(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1704      else
1705         emit(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1706      break;
1707
1708   case ir_binop_dot:
1709      assert(ir->operands[0]->type->is_vector());
1710      assert(ir->operands[0]->type == ir->operands[1]->type);
1711      emit_dp(ir, result_dst, op[0], op[1],
1712              ir->operands[0]->type->vector_elements);
1713      break;
1714
1715   case ir_unop_sqrt:
1716      /* sqrt(x) = x * rsq(x). */
1717      emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1718      emit(ir, TGSI_OPCODE_MUL, result_dst, result_src, op[0]);
1719      /* For incoming channels <= 0, set the result to 0. */
1720      op[0].negate = ~op[0].negate;
1721      emit(ir, TGSI_OPCODE_CMP, result_dst,
1722        		  op[0], result_src, st_src_reg_for_float(0.0));
1723      break;
1724   case ir_unop_rsq:
1725      emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1726      break;
1727   case ir_unop_i2f:
1728      if (native_integers) {
1729         emit(ir, TGSI_OPCODE_I2F, result_dst, op[0]);
1730         break;
1731      }
1732      /* fallthrough to next case otherwise */
1733   case ir_unop_b2f:
1734      if (native_integers) {
1735         emit(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_float(1.0));
1736         break;
1737      }
1738      /* fallthrough to next case otherwise */
1739   case ir_unop_i2u:
1740   case ir_unop_u2i:
1741      /* Converting between signed and unsigned integers is a no-op. */
1742      result_src = op[0];
1743      break;
1744   case ir_unop_b2i:
1745      if (native_integers) {
1746         /* Booleans are stored as integers using ~0 for true and 0 for false.
1747          * GLSL requires that int(bool) return 1 for true and 0 for false.
1748          * This conversion is done with AND, but it could be done with NEG.
1749          */
1750         emit(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_int(1));
1751      } else {
1752         /* Booleans and integers are both stored as floats when native
1753          * integers are disabled.
1754          */
1755         result_src = op[0];
1756      }
1757      break;
1758   case ir_unop_f2i:
1759      if (native_integers)
1760         emit(ir, TGSI_OPCODE_F2I, result_dst, op[0]);
1761      else
1762         emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1763      break;
1764   case ir_unop_f2u:
1765      if (native_integers)
1766         emit(ir, TGSI_OPCODE_F2U, result_dst, op[0]);
1767      else
1768         emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1769      break;
1770   case ir_unop_bitcast_f2i:
1771   case ir_unop_bitcast_f2u:
1772   case ir_unop_bitcast_i2f:
1773   case ir_unop_bitcast_u2f:
1774      result_src = op[0];
1775      break;
1776   case ir_unop_f2b:
1777      emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1778      break;
1779   case ir_unop_i2b:
1780      if (native_integers)
1781         emit(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1782      else
1783         emit(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1784      break;
1785   case ir_unop_trunc:
1786      emit(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1787      break;
1788   case ir_unop_ceil:
1789      emit(ir, TGSI_OPCODE_CEIL, result_dst, op[0]);
1790      break;
1791   case ir_unop_floor:
1792      emit(ir, TGSI_OPCODE_FLR, result_dst, op[0]);
1793      break;
1794   case ir_unop_round_even:
1795      emit(ir, TGSI_OPCODE_ROUND, result_dst, op[0]);
1796      break;
1797   case ir_unop_fract:
1798      emit(ir, TGSI_OPCODE_FRC, result_dst, op[0]);
1799      break;
1800
1801   case ir_binop_min:
1802      emit(ir, TGSI_OPCODE_MIN, result_dst, op[0], op[1]);
1803      break;
1804   case ir_binop_max:
1805      emit(ir, TGSI_OPCODE_MAX, result_dst, op[0], op[1]);
1806      break;
1807   case ir_binop_pow:
1808      emit_scalar(ir, TGSI_OPCODE_POW, result_dst, op[0], op[1]);
1809      break;
1810
1811   case ir_unop_bit_not:
1812      if (native_integers) {
1813         emit(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1814         break;
1815      }
1816   case ir_unop_u2f:
1817      if (native_integers) {
1818         emit(ir, TGSI_OPCODE_U2F, result_dst, op[0]);
1819         break;
1820      }
1821   case ir_binop_lshift:
1822      if (native_integers) {
1823         emit(ir, TGSI_OPCODE_SHL, result_dst, op[0], op[1]);
1824         break;
1825      }
1826   case ir_binop_rshift:
1827      if (native_integers) {
1828         emit(ir, TGSI_OPCODE_ISHR, result_dst, op[0], op[1]);
1829         break;
1830      }
1831   case ir_binop_bit_and:
1832      if (native_integers) {
1833         emit(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1834         break;
1835      }
1836   case ir_binop_bit_xor:
1837      if (native_integers) {
1838         emit(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1839         break;
1840      }
1841   case ir_binop_bit_or:
1842      if (native_integers) {
1843         emit(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1844         break;
1845      }
1846
1847      assert(!"GLSL 1.30 features unsupported");
1848      break;
1849
1850   case ir_quadop_vector:
1851      /* This operation should have already been handled.
1852       */
1853      assert(!"Should not get here.");
1854      break;
1855   }
1856
1857   this->result = result_src;
1858}
1859
1860
1861void
1862glsl_to_tgsi_visitor::visit(ir_swizzle *ir)
1863{
1864   st_src_reg src;
1865   int i;
1866   int swizzle[4];
1867
1868   /* Note that this is only swizzles in expressions, not those on the left
1869    * hand side of an assignment, which do write masking.  See ir_assignment
1870    * for that.
1871    */
1872
1873   ir->val->accept(this);
1874   src = this->result;
1875   assert(src.file != PROGRAM_UNDEFINED);
1876
1877   for (i = 0; i < 4; i++) {
1878      if (i < ir->type->vector_elements) {
1879         switch (i) {
1880         case 0:
1881            swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
1882            break;
1883         case 1:
1884            swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
1885            break;
1886         case 2:
1887            swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
1888            break;
1889         case 3:
1890            swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
1891            break;
1892         }
1893      } else {
1894         /* If the type is smaller than a vec4, replicate the last
1895          * channel out.
1896          */
1897         swizzle[i] = swizzle[ir->type->vector_elements - 1];
1898      }
1899   }
1900
1901   src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
1902
1903   this->result = src;
1904}
1905
1906void
1907glsl_to_tgsi_visitor::visit(ir_dereference_variable *ir)
1908{
1909   variable_storage *entry = find_variable_storage(ir->var);
1910   ir_variable *var = ir->var;
1911
1912   if (!entry) {
1913      switch (var->mode) {
1914      case ir_var_uniform:
1915         entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
1916        				       var->location);
1917         this->variables.push_tail(entry);
1918         break;
1919      case ir_var_in:
1920      case ir_var_inout:
1921         /* The linker assigns locations for varyings and attributes,
1922          * including deprecated builtins (like gl_Color), user-assign
1923          * generic attributes (glBindVertexLocation), and
1924          * user-defined varyings.
1925          *
1926          * FINISHME: We would hit this path for function arguments.  Fix!
1927          */
1928         assert(var->location != -1);
1929         entry = new(mem_ctx) variable_storage(var,
1930                                               PROGRAM_INPUT,
1931                                               var->location);
1932         break;
1933      case ir_var_out:
1934         assert(var->location != -1);
1935         entry = new(mem_ctx) variable_storage(var,
1936                                               PROGRAM_OUTPUT,
1937                                               var->location + var->index);
1938         break;
1939      case ir_var_system_value:
1940         entry = new(mem_ctx) variable_storage(var,
1941                                               PROGRAM_SYSTEM_VALUE,
1942                                               var->location);
1943         break;
1944      case ir_var_auto:
1945      case ir_var_temporary:
1946         entry = new(mem_ctx) variable_storage(var, PROGRAM_TEMPORARY,
1947        				       this->next_temp);
1948         this->variables.push_tail(entry);
1949
1950         next_temp += type_size(var->type);
1951         break;
1952      }
1953
1954      if (!entry) {
1955         printf("Failed to make storage for %s\n", var->name);
1956         exit(1);
1957      }
1958   }
1959
1960   this->result = st_src_reg(entry->file, entry->index, var->type);
1961   if (!native_integers)
1962      this->result.type = GLSL_TYPE_FLOAT;
1963}
1964
1965void
1966glsl_to_tgsi_visitor::visit(ir_dereference_array *ir)
1967{
1968   ir_constant *index;
1969   st_src_reg src;
1970   int element_size = type_size(ir->type);
1971
1972   index = ir->array_index->constant_expression_value();
1973
1974   ir->array->accept(this);
1975   src = this->result;
1976
1977   if (index) {
1978      src.index += index->value.i[0] * element_size;
1979   } else {
1980      /* Variable index array dereference.  It eats the "vec4" of the
1981       * base of the array and an index that offsets the TGSI register
1982       * index.
1983       */
1984      ir->array_index->accept(this);
1985
1986      st_src_reg index_reg;
1987
1988      if (element_size == 1) {
1989         index_reg = this->result;
1990      } else {
1991         index_reg = get_temp(native_integers ?
1992                              glsl_type::int_type : glsl_type::float_type);
1993
1994         emit(ir, TGSI_OPCODE_MUL, st_dst_reg(index_reg),
1995              this->result, st_src_reg_for_type(index_reg.type, element_size));
1996      }
1997
1998      /* If there was already a relative address register involved, add the
1999       * new and the old together to get the new offset.
2000       */
2001      if (src.reladdr != NULL) {
2002         st_src_reg accum_reg = get_temp(native_integers ?
2003                                glsl_type::int_type : glsl_type::float_type);
2004
2005         emit(ir, TGSI_OPCODE_ADD, st_dst_reg(accum_reg),
2006              index_reg, *src.reladdr);
2007
2008         index_reg = accum_reg;
2009      }
2010
2011      src.reladdr = ralloc(mem_ctx, st_src_reg);
2012      memcpy(src.reladdr, &index_reg, sizeof(index_reg));
2013   }
2014
2015   /* If the type is smaller than a vec4, replicate the last channel out. */
2016   if (ir->type->is_scalar() || ir->type->is_vector())
2017      src.swizzle = swizzle_for_size(ir->type->vector_elements);
2018   else
2019      src.swizzle = SWIZZLE_NOOP;
2020
2021   this->result = src;
2022}
2023
2024void
2025glsl_to_tgsi_visitor::visit(ir_dereference_record *ir)
2026{
2027   unsigned int i;
2028   const glsl_type *struct_type = ir->record->type;
2029   int offset = 0;
2030
2031   ir->record->accept(this);
2032
2033   for (i = 0; i < struct_type->length; i++) {
2034      if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
2035         break;
2036      offset += type_size(struct_type->fields.structure[i].type);
2037   }
2038
2039   /* If the type is smaller than a vec4, replicate the last channel out. */
2040   if (ir->type->is_scalar() || ir->type->is_vector())
2041      this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
2042   else
2043      this->result.swizzle = SWIZZLE_NOOP;
2044
2045   this->result.index += offset;
2046}
2047
2048/**
2049 * We want to be careful in assignment setup to hit the actual storage
2050 * instead of potentially using a temporary like we might with the
2051 * ir_dereference handler.
2052 */
2053static st_dst_reg
2054get_assignment_lhs(ir_dereference *ir, glsl_to_tgsi_visitor *v)
2055{
2056   /* The LHS must be a dereference.  If the LHS is a variable indexed array
2057    * access of a vector, it must be separated into a series conditional moves
2058    * before reaching this point (see ir_vec_index_to_cond_assign).
2059    */
2060   assert(ir->as_dereference());
2061   ir_dereference_array *deref_array = ir->as_dereference_array();
2062   if (deref_array) {
2063      assert(!deref_array->array->type->is_vector());
2064   }
2065
2066   /* Use the rvalue deref handler for the most part.  We'll ignore
2067    * swizzles in it and write swizzles using writemask, though.
2068    */
2069   ir->accept(v);
2070   return st_dst_reg(v->result);
2071}
2072
2073/**
2074 * Process the condition of a conditional assignment
2075 *
2076 * Examines the condition of a conditional assignment to generate the optimal
2077 * first operand of a \c CMP instruction.  If the condition is a relational
2078 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
2079 * used as the source for the \c CMP instruction.  Otherwise the comparison
2080 * is processed to a boolean result, and the boolean result is used as the
2081 * operand to the CMP instruction.
2082 */
2083bool
2084glsl_to_tgsi_visitor::process_move_condition(ir_rvalue *ir)
2085{
2086   ir_rvalue *src_ir = ir;
2087   bool negate = true;
2088   bool switch_order = false;
2089
2090   ir_expression *const expr = ir->as_expression();
2091   if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2092      bool zero_on_left = false;
2093
2094      if (expr->operands[0]->is_zero()) {
2095         src_ir = expr->operands[1];
2096         zero_on_left = true;
2097      } else if (expr->operands[1]->is_zero()) {
2098         src_ir = expr->operands[0];
2099         zero_on_left = false;
2100      }
2101
2102      /*      a is -  0  +            -  0  +
2103       * (a <  0)  T  F  F  ( a < 0)  T  F  F
2104       * (0 <  a)  F  F  T  (-a < 0)  F  F  T
2105       * (a <= 0)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
2106       * (0 <= a)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
2107       * (a >  0)  F  F  T  (-a < 0)  F  F  T
2108       * (0 >  a)  T  F  F  ( a < 0)  T  F  F
2109       * (a >= 0)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
2110       * (0 >= a)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
2111       *
2112       * Note that exchanging the order of 0 and 'a' in the comparison simply
2113       * means that the value of 'a' should be negated.
2114       */
2115      if (src_ir != ir) {
2116         switch (expr->operation) {
2117         case ir_binop_less:
2118            switch_order = false;
2119            negate = zero_on_left;
2120            break;
2121
2122         case ir_binop_greater:
2123            switch_order = false;
2124            negate = !zero_on_left;
2125            break;
2126
2127         case ir_binop_lequal:
2128            switch_order = true;
2129            negate = !zero_on_left;
2130            break;
2131
2132         case ir_binop_gequal:
2133            switch_order = true;
2134            negate = zero_on_left;
2135            break;
2136
2137         default:
2138            /* This isn't the right kind of comparison afterall, so make sure
2139             * the whole condition is visited.
2140             */
2141            src_ir = ir;
2142            break;
2143         }
2144      }
2145   }
2146
2147   src_ir->accept(this);
2148
2149   /* We use the TGSI_OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
2150    * condition we produced is 0.0 or 1.0.  By flipping the sign, we can
2151    * choose which value TGSI_OPCODE_CMP produces without an extra instruction
2152    * computing the condition.
2153    */
2154   if (negate)
2155      this->result.negate = ~this->result.negate;
2156
2157   return switch_order;
2158}
2159
2160void
2161glsl_to_tgsi_visitor::visit(ir_assignment *ir)
2162{
2163   st_dst_reg l;
2164   st_src_reg r;
2165   int i;
2166
2167   ir->rhs->accept(this);
2168   r = this->result;
2169
2170   l = get_assignment_lhs(ir->lhs, this);
2171
2172   /* FINISHME: This should really set to the correct maximal writemask for each
2173    * FINISHME: component written (in the loops below).  This case can only
2174    * FINISHME: occur for matrices, arrays, and structures.
2175    */
2176   if (ir->write_mask == 0) {
2177      assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
2178      l.writemask = WRITEMASK_XYZW;
2179   } else if (ir->lhs->type->is_scalar() &&
2180              ir->lhs->variable_referenced()->mode == ir_var_out) {
2181      /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
2182       * FINISHME: W component of fragment shader output zero, work correctly.
2183       */
2184      l.writemask = WRITEMASK_XYZW;
2185   } else {
2186      int swizzles[4];
2187      int first_enabled_chan = 0;
2188      int rhs_chan = 0;
2189
2190      l.writemask = ir->write_mask;
2191
2192      for (int i = 0; i < 4; i++) {
2193         if (l.writemask & (1 << i)) {
2194            first_enabled_chan = GET_SWZ(r.swizzle, i);
2195            break;
2196         }
2197      }
2198
2199      /* Swizzle a small RHS vector into the channels being written.
2200       *
2201       * glsl ir treats write_mask as dictating how many channels are
2202       * present on the RHS while TGSI treats write_mask as just
2203       * showing which channels of the vec4 RHS get written.
2204       */
2205      for (int i = 0; i < 4; i++) {
2206         if (l.writemask & (1 << i))
2207            swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
2208         else
2209            swizzles[i] = first_enabled_chan;
2210      }
2211      r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
2212        			swizzles[2], swizzles[3]);
2213   }
2214
2215   assert(l.file != PROGRAM_UNDEFINED);
2216   assert(r.file != PROGRAM_UNDEFINED);
2217
2218   if (ir->condition) {
2219      const bool switch_order = this->process_move_condition(ir->condition);
2220      st_src_reg condition = this->result;
2221
2222      for (i = 0; i < type_size(ir->lhs->type); i++) {
2223         st_src_reg l_src = st_src_reg(l);
2224         st_src_reg condition_temp = condition;
2225         l_src.swizzle = swizzle_for_size(ir->lhs->type->vector_elements);
2226
2227         if (native_integers) {
2228            /* This is necessary because TGSI's CMP instruction expects the
2229             * condition to be a float, and we store booleans as integers.
2230             * If TGSI had a UCMP instruction or similar, this extra
2231             * instruction would not be necessary.
2232             */
2233            condition_temp = get_temp(glsl_type::vec4_type);
2234            condition.negate = 0;
2235            emit(ir, TGSI_OPCODE_I2F, st_dst_reg(condition_temp), condition);
2236            condition_temp.swizzle = condition.swizzle;
2237         }
2238
2239         if (switch_order) {
2240            emit(ir, TGSI_OPCODE_CMP, l, condition_temp, l_src, r);
2241         } else {
2242            emit(ir, TGSI_OPCODE_CMP, l, condition_temp, r, l_src);
2243         }
2244
2245         l.index++;
2246         r.index++;
2247      }
2248   } else if (ir->rhs->as_expression() &&
2249              this->instructions.get_tail() &&
2250              ir->rhs == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->ir &&
2251              type_size(ir->lhs->type) == 1 &&
2252              l.writemask == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->dst.writemask) {
2253      /* To avoid emitting an extra MOV when assigning an expression to a
2254       * variable, emit the last instruction of the expression again, but
2255       * replace the destination register with the target of the assignment.
2256       * Dead code elimination will remove the original instruction.
2257       */
2258      glsl_to_tgsi_instruction *inst, *new_inst;
2259      inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2260      new_inst = emit(ir, inst->op, l, inst->src[0], inst->src[1], inst->src[2]);
2261      new_inst->saturate = inst->saturate;
2262      inst->dead_mask = inst->dst.writemask;
2263   } else {
2264      for (i = 0; i < type_size(ir->lhs->type); i++) {
2265         emit(ir, TGSI_OPCODE_MOV, l, r);
2266         l.index++;
2267         r.index++;
2268      }
2269   }
2270}
2271
2272
2273void
2274glsl_to_tgsi_visitor::visit(ir_constant *ir)
2275{
2276   st_src_reg src;
2277   GLfloat stack_vals[4] = { 0 };
2278   gl_constant_value *values = (gl_constant_value *) stack_vals;
2279   GLenum gl_type = GL_NONE;
2280   unsigned int i;
2281   static int in_array = 0;
2282   gl_register_file file = in_array ? PROGRAM_CONSTANT : PROGRAM_IMMEDIATE;
2283
2284   /* Unfortunately, 4 floats is all we can get into
2285    * _mesa_add_typed_unnamed_constant.  So, make a temp to store an
2286    * aggregate constant and move each constant value into it.  If we
2287    * get lucky, copy propagation will eliminate the extra moves.
2288    */
2289   if (ir->type->base_type == GLSL_TYPE_STRUCT) {
2290      st_src_reg temp_base = get_temp(ir->type);
2291      st_dst_reg temp = st_dst_reg(temp_base);
2292
2293      foreach_iter(exec_list_iterator, iter, ir->components) {
2294         ir_constant *field_value = (ir_constant *)iter.get();
2295         int size = type_size(field_value->type);
2296
2297         assert(size > 0);
2298
2299         field_value->accept(this);
2300         src = this->result;
2301
2302         for (i = 0; i < (unsigned int)size; i++) {
2303            emit(ir, TGSI_OPCODE_MOV, temp, src);
2304
2305            src.index++;
2306            temp.index++;
2307         }
2308      }
2309      this->result = temp_base;
2310      return;
2311   }
2312
2313   if (ir->type->is_array()) {
2314      st_src_reg temp_base = get_temp(ir->type);
2315      st_dst_reg temp = st_dst_reg(temp_base);
2316      int size = type_size(ir->type->fields.array);
2317
2318      assert(size > 0);
2319      in_array++;
2320
2321      for (i = 0; i < ir->type->length; i++) {
2322         ir->array_elements[i]->accept(this);
2323         src = this->result;
2324         for (int j = 0; j < size; j++) {
2325            emit(ir, TGSI_OPCODE_MOV, temp, src);
2326
2327            src.index++;
2328            temp.index++;
2329         }
2330      }
2331      this->result = temp_base;
2332      in_array--;
2333      return;
2334   }
2335
2336   if (ir->type->is_matrix()) {
2337      st_src_reg mat = get_temp(ir->type);
2338      st_dst_reg mat_column = st_dst_reg(mat);
2339
2340      for (i = 0; i < ir->type->matrix_columns; i++) {
2341         assert(ir->type->base_type == GLSL_TYPE_FLOAT);
2342         values = (gl_constant_value *) &ir->value.f[i * ir->type->vector_elements];
2343
2344         src = st_src_reg(file, -1, ir->type->base_type);
2345         src.index = add_constant(file,
2346                                  values,
2347                                  ir->type->vector_elements,
2348                                  GL_FLOAT,
2349                                  &src.swizzle);
2350         emit(ir, TGSI_OPCODE_MOV, mat_column, src);
2351
2352         mat_column.index++;
2353      }
2354
2355      this->result = mat;
2356      return;
2357   }
2358
2359   switch (ir->type->base_type) {
2360   case GLSL_TYPE_FLOAT:
2361      gl_type = GL_FLOAT;
2362      for (i = 0; i < ir->type->vector_elements; i++) {
2363         values[i].f = ir->value.f[i];
2364      }
2365      break;
2366   case GLSL_TYPE_UINT:
2367      gl_type = native_integers ? GL_UNSIGNED_INT : GL_FLOAT;
2368      for (i = 0; i < ir->type->vector_elements; i++) {
2369         if (native_integers)
2370            values[i].u = ir->value.u[i];
2371         else
2372            values[i].f = ir->value.u[i];
2373      }
2374      break;
2375   case GLSL_TYPE_INT:
2376      gl_type = native_integers ? GL_INT : GL_FLOAT;
2377      for (i = 0; i < ir->type->vector_elements; i++) {
2378         if (native_integers)
2379            values[i].i = ir->value.i[i];
2380         else
2381            values[i].f = ir->value.i[i];
2382      }
2383      break;
2384   case GLSL_TYPE_BOOL:
2385      gl_type = native_integers ? GL_BOOL : GL_FLOAT;
2386      for (i = 0; i < ir->type->vector_elements; i++) {
2387         if (native_integers)
2388            values[i].u = ir->value.b[i] ? ~0 : 0;
2389         else
2390            values[i].f = ir->value.b[i];
2391      }
2392      break;
2393   default:
2394      assert(!"Non-float/uint/int/bool constant");
2395   }
2396
2397   this->result = st_src_reg(file, -1, ir->type);
2398   this->result.index = add_constant(file,
2399                                     values,
2400                                     ir->type->vector_elements,
2401                                     gl_type,
2402                                     &this->result.swizzle);
2403}
2404
2405function_entry *
2406glsl_to_tgsi_visitor::get_function_signature(ir_function_signature *sig)
2407{
2408   function_entry *entry;
2409
2410   foreach_iter(exec_list_iterator, iter, this->function_signatures) {
2411      entry = (function_entry *)iter.get();
2412
2413      if (entry->sig == sig)
2414         return entry;
2415   }
2416
2417   entry = ralloc(mem_ctx, function_entry);
2418   entry->sig = sig;
2419   entry->sig_id = this->next_signature_id++;
2420   entry->bgn_inst = NULL;
2421
2422   /* Allocate storage for all the parameters. */
2423   foreach_iter(exec_list_iterator, iter, sig->parameters) {
2424      ir_variable *param = (ir_variable *)iter.get();
2425      variable_storage *storage;
2426
2427      storage = find_variable_storage(param);
2428      assert(!storage);
2429
2430      storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
2431        				      this->next_temp);
2432      this->variables.push_tail(storage);
2433
2434      this->next_temp += type_size(param->type);
2435   }
2436
2437   if (!sig->return_type->is_void()) {
2438      entry->return_reg = get_temp(sig->return_type);
2439   } else {
2440      entry->return_reg = undef_src;
2441   }
2442
2443   this->function_signatures.push_tail(entry);
2444   return entry;
2445}
2446
2447void
2448glsl_to_tgsi_visitor::visit(ir_call *ir)
2449{
2450   glsl_to_tgsi_instruction *call_inst;
2451   ir_function_signature *sig = ir->callee;
2452   function_entry *entry = get_function_signature(sig);
2453   int i;
2454
2455   /* Process in parameters. */
2456   exec_list_iterator sig_iter = sig->parameters.iterator();
2457   foreach_iter(exec_list_iterator, iter, *ir) {
2458      ir_rvalue *param_rval = (ir_rvalue *)iter.get();
2459      ir_variable *param = (ir_variable *)sig_iter.get();
2460
2461      if (param->mode == ir_var_in ||
2462          param->mode == ir_var_inout) {
2463         variable_storage *storage = find_variable_storage(param);
2464         assert(storage);
2465
2466         param_rval->accept(this);
2467         st_src_reg r = this->result;
2468
2469         st_dst_reg l;
2470         l.file = storage->file;
2471         l.index = storage->index;
2472         l.reladdr = NULL;
2473         l.writemask = WRITEMASK_XYZW;
2474         l.cond_mask = COND_TR;
2475
2476         for (i = 0; i < type_size(param->type); i++) {
2477            emit(ir, TGSI_OPCODE_MOV, l, r);
2478            l.index++;
2479            r.index++;
2480         }
2481      }
2482
2483      sig_iter.next();
2484   }
2485   assert(!sig_iter.has_next());
2486
2487   /* Emit call instruction */
2488   call_inst = emit(ir, TGSI_OPCODE_CAL);
2489   call_inst->function = entry;
2490
2491   /* Process out parameters. */
2492   sig_iter = sig->parameters.iterator();
2493   foreach_iter(exec_list_iterator, iter, *ir) {
2494      ir_rvalue *param_rval = (ir_rvalue *)iter.get();
2495      ir_variable *param = (ir_variable *)sig_iter.get();
2496
2497      if (param->mode == ir_var_out ||
2498          param->mode == ir_var_inout) {
2499         variable_storage *storage = find_variable_storage(param);
2500         assert(storage);
2501
2502         st_src_reg r;
2503         r.file = storage->file;
2504         r.index = storage->index;
2505         r.reladdr = NULL;
2506         r.swizzle = SWIZZLE_NOOP;
2507         r.negate = 0;
2508
2509         param_rval->accept(this);
2510         st_dst_reg l = st_dst_reg(this->result);
2511
2512         for (i = 0; i < type_size(param->type); i++) {
2513            emit(ir, TGSI_OPCODE_MOV, l, r);
2514            l.index++;
2515            r.index++;
2516         }
2517      }
2518
2519      sig_iter.next();
2520   }
2521   assert(!sig_iter.has_next());
2522
2523   /* Process return value. */
2524   this->result = entry->return_reg;
2525}
2526
2527void
2528glsl_to_tgsi_visitor::visit(ir_texture *ir)
2529{
2530   st_src_reg result_src, coord, lod_info, projector, dx, dy, offset;
2531   st_dst_reg result_dst, coord_dst;
2532   glsl_to_tgsi_instruction *inst = NULL;
2533   unsigned opcode = TGSI_OPCODE_NOP;
2534
2535   if (ir->coordinate) {
2536      ir->coordinate->accept(this);
2537
2538      /* Put our coords in a temp.  We'll need to modify them for shadow,
2539       * projection, or LOD, so the only case we'd use it as is is if
2540       * we're doing plain old texturing.  The optimization passes on
2541       * glsl_to_tgsi_visitor should handle cleaning up our mess in that case.
2542       */
2543      coord = get_temp(glsl_type::vec4_type);
2544      coord_dst = st_dst_reg(coord);
2545      emit(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
2546   }
2547
2548   if (ir->projector) {
2549      ir->projector->accept(this);
2550      projector = this->result;
2551   }
2552
2553   /* Storage for our result.  Ideally for an assignment we'd be using
2554    * the actual storage for the result here, instead.
2555    */
2556   result_src = get_temp(glsl_type::vec4_type);
2557   result_dst = st_dst_reg(result_src);
2558
2559   switch (ir->op) {
2560   case ir_tex:
2561      opcode = TGSI_OPCODE_TEX;
2562      break;
2563   case ir_txb:
2564      opcode = TGSI_OPCODE_TXB;
2565      ir->lod_info.bias->accept(this);
2566      lod_info = this->result;
2567      break;
2568   case ir_txl:
2569      opcode = TGSI_OPCODE_TXL;
2570      ir->lod_info.lod->accept(this);
2571      lod_info = this->result;
2572      break;
2573   case ir_txd:
2574      opcode = TGSI_OPCODE_TXD;
2575      ir->lod_info.grad.dPdx->accept(this);
2576      dx = this->result;
2577      ir->lod_info.grad.dPdy->accept(this);
2578      dy = this->result;
2579      break;
2580   case ir_txs:
2581      opcode = TGSI_OPCODE_TXQ;
2582      ir->lod_info.lod->accept(this);
2583      lod_info = this->result;
2584      break;
2585   case ir_txf:
2586      opcode = TGSI_OPCODE_TXF;
2587      ir->lod_info.lod->accept(this);
2588      lod_info = this->result;
2589      if (ir->offset) {
2590	 ir->offset->accept(this);
2591	 offset = this->result;
2592      }
2593      break;
2594   }
2595
2596   const glsl_type *sampler_type = ir->sampler->type;
2597
2598   if (ir->projector) {
2599      if (opcode == TGSI_OPCODE_TEX) {
2600         /* Slot the projector in as the last component of the coord. */
2601         coord_dst.writemask = WRITEMASK_W;
2602         emit(ir, TGSI_OPCODE_MOV, coord_dst, projector);
2603         coord_dst.writemask = WRITEMASK_XYZW;
2604         opcode = TGSI_OPCODE_TXP;
2605      } else {
2606         st_src_reg coord_w = coord;
2607         coord_w.swizzle = SWIZZLE_WWWW;
2608
2609         /* For the other TEX opcodes there's no projective version
2610          * since the last slot is taken up by LOD info.  Do the
2611          * projective divide now.
2612          */
2613         coord_dst.writemask = WRITEMASK_W;
2614         emit(ir, TGSI_OPCODE_RCP, coord_dst, projector);
2615
2616         /* In the case where we have to project the coordinates "by hand,"
2617          * the shadow comparator value must also be projected.
2618          */
2619         st_src_reg tmp_src = coord;
2620         if (ir->shadow_comparitor) {
2621            /* Slot the shadow value in as the second to last component of the
2622             * coord.
2623             */
2624            ir->shadow_comparitor->accept(this);
2625
2626            tmp_src = get_temp(glsl_type::vec4_type);
2627            st_dst_reg tmp_dst = st_dst_reg(tmp_src);
2628
2629	    /* Projective division not allowed for array samplers. */
2630	    assert(!sampler_type->sampler_array);
2631
2632            tmp_dst.writemask = WRITEMASK_Z;
2633            emit(ir, TGSI_OPCODE_MOV, tmp_dst, this->result);
2634
2635            tmp_dst.writemask = WRITEMASK_XY;
2636            emit(ir, TGSI_OPCODE_MOV, tmp_dst, coord);
2637         }
2638
2639         coord_dst.writemask = WRITEMASK_XYZ;
2640         emit(ir, TGSI_OPCODE_MUL, coord_dst, tmp_src, coord_w);
2641
2642         coord_dst.writemask = WRITEMASK_XYZW;
2643         coord.swizzle = SWIZZLE_XYZW;
2644      }
2645   }
2646
2647   /* If projection is done and the opcode is not TGSI_OPCODE_TXP, then the shadow
2648    * comparator was put in the correct place (and projected) by the code,
2649    * above, that handles by-hand projection.
2650    */
2651   if (ir->shadow_comparitor && (!ir->projector || opcode == TGSI_OPCODE_TXP)) {
2652      /* Slot the shadow value in as the second to last component of the
2653       * coord.
2654       */
2655      ir->shadow_comparitor->accept(this);
2656
2657      /* XXX This will need to be updated for cubemap array samplers. */
2658      if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_2D &&
2659	   sampler_type->sampler_array) ||
2660	  sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
2661         coord_dst.writemask = WRITEMASK_W;
2662      } else {
2663         coord_dst.writemask = WRITEMASK_Z;
2664      }
2665
2666      emit(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
2667      coord_dst.writemask = WRITEMASK_XYZW;
2668   }
2669
2670   if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXB ||
2671       opcode == TGSI_OPCODE_TXF) {
2672      /* TGSI stores LOD or LOD bias in the last channel of the coords. */
2673      coord_dst.writemask = WRITEMASK_W;
2674      emit(ir, TGSI_OPCODE_MOV, coord_dst, lod_info);
2675      coord_dst.writemask = WRITEMASK_XYZW;
2676   }
2677
2678   if (opcode == TGSI_OPCODE_TXD)
2679      inst = emit(ir, opcode, result_dst, coord, dx, dy);
2680   else if (opcode == TGSI_OPCODE_TXQ)
2681      inst = emit(ir, opcode, result_dst, lod_info);
2682   else if (opcode == TGSI_OPCODE_TXF) {
2683      inst = emit(ir, opcode, result_dst, coord);
2684   } else
2685      inst = emit(ir, opcode, result_dst, coord);
2686
2687   if (ir->shadow_comparitor)
2688      inst->tex_shadow = GL_TRUE;
2689
2690   inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2691        					   this->shader_program,
2692        					   this->prog);
2693
2694   if (ir->offset) {
2695       inst->tex_offset_num_offset = 1;
2696       inst->tex_offsets[0].Index = offset.index;
2697       inst->tex_offsets[0].File = offset.file;
2698       inst->tex_offsets[0].SwizzleX = GET_SWZ(offset.swizzle, 0);
2699       inst->tex_offsets[0].SwizzleY = GET_SWZ(offset.swizzle, 1);
2700       inst->tex_offsets[0].SwizzleZ = GET_SWZ(offset.swizzle, 2);
2701   }
2702
2703   switch (sampler_type->sampler_dimensionality) {
2704   case GLSL_SAMPLER_DIM_1D:
2705      inst->tex_target = (sampler_type->sampler_array)
2706         ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2707      break;
2708   case GLSL_SAMPLER_DIM_2D:
2709      inst->tex_target = (sampler_type->sampler_array)
2710         ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2711      break;
2712   case GLSL_SAMPLER_DIM_3D:
2713      inst->tex_target = TEXTURE_3D_INDEX;
2714      break;
2715   case GLSL_SAMPLER_DIM_CUBE:
2716      inst->tex_target = TEXTURE_CUBE_INDEX;
2717      break;
2718   case GLSL_SAMPLER_DIM_RECT:
2719      inst->tex_target = TEXTURE_RECT_INDEX;
2720      break;
2721   case GLSL_SAMPLER_DIM_BUF:
2722      assert(!"FINISHME: Implement ARB_texture_buffer_object");
2723      break;
2724   case GLSL_SAMPLER_DIM_EXTERNAL:
2725      inst->tex_target = TEXTURE_EXTERNAL_INDEX;
2726      break;
2727   default:
2728      assert(!"Should not get here.");
2729   }
2730
2731   this->result = result_src;
2732}
2733
2734void
2735glsl_to_tgsi_visitor::visit(ir_return *ir)
2736{
2737   if (ir->get_value()) {
2738      st_dst_reg l;
2739      int i;
2740
2741      assert(current_function);
2742
2743      ir->get_value()->accept(this);
2744      st_src_reg r = this->result;
2745
2746      l = st_dst_reg(current_function->return_reg);
2747
2748      for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2749         emit(ir, TGSI_OPCODE_MOV, l, r);
2750         l.index++;
2751         r.index++;
2752      }
2753   }
2754
2755   emit(ir, TGSI_OPCODE_RET);
2756}
2757
2758void
2759glsl_to_tgsi_visitor::visit(ir_discard *ir)
2760{
2761   if (ir->condition) {
2762      ir->condition->accept(this);
2763      this->result.negate = ~this->result.negate;
2764      emit(ir, TGSI_OPCODE_KIL, undef_dst, this->result);
2765   } else {
2766      emit(ir, TGSI_OPCODE_KILP);
2767   }
2768}
2769
2770void
2771glsl_to_tgsi_visitor::visit(ir_if *ir)
2772{
2773   glsl_to_tgsi_instruction *cond_inst, *if_inst;
2774   glsl_to_tgsi_instruction *prev_inst;
2775
2776   prev_inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2777
2778   ir->condition->accept(this);
2779   assert(this->result.file != PROGRAM_UNDEFINED);
2780
2781   if (this->options->EmitCondCodes) {
2782      cond_inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2783
2784      /* See if we actually generated any instruction for generating
2785       * the condition.  If not, then cook up a move to a temp so we
2786       * have something to set cond_update on.
2787       */
2788      if (cond_inst == prev_inst) {
2789         st_src_reg temp = get_temp(glsl_type::bool_type);
2790         cond_inst = emit(ir->condition, TGSI_OPCODE_MOV, st_dst_reg(temp), result);
2791      }
2792      cond_inst->cond_update = GL_TRUE;
2793
2794      if_inst = emit(ir->condition, TGSI_OPCODE_IF);
2795      if_inst->dst.cond_mask = COND_NE;
2796   } else {
2797      if_inst = emit(ir->condition, TGSI_OPCODE_IF, undef_dst, this->result);
2798   }
2799
2800   this->instructions.push_tail(if_inst);
2801
2802   visit_exec_list(&ir->then_instructions, this);
2803
2804   if (!ir->else_instructions.is_empty()) {
2805      emit(ir->condition, TGSI_OPCODE_ELSE);
2806      visit_exec_list(&ir->else_instructions, this);
2807   }
2808
2809   if_inst = emit(ir->condition, TGSI_OPCODE_ENDIF);
2810}
2811
2812glsl_to_tgsi_visitor::glsl_to_tgsi_visitor()
2813{
2814   result.file = PROGRAM_UNDEFINED;
2815   next_temp = 1;
2816   next_signature_id = 1;
2817   num_immediates = 0;
2818   current_function = NULL;
2819   num_address_regs = 0;
2820   samplers_used = 0;
2821   indirect_addr_temps = false;
2822   indirect_addr_consts = false;
2823   glsl_version = 0;
2824   native_integers = false;
2825   mem_ctx = ralloc_context(NULL);
2826   ctx = NULL;
2827   prog = NULL;
2828   shader_program = NULL;
2829   options = NULL;
2830}
2831
2832glsl_to_tgsi_visitor::~glsl_to_tgsi_visitor()
2833{
2834   ralloc_free(mem_ctx);
2835}
2836
2837extern "C" void free_glsl_to_tgsi_visitor(glsl_to_tgsi_visitor *v)
2838{
2839   delete v;
2840}
2841
2842
2843/**
2844 * Count resources used by the given gpu program (number of texture
2845 * samplers, etc).
2846 */
2847static void
2848count_resources(glsl_to_tgsi_visitor *v, gl_program *prog)
2849{
2850   v->samplers_used = 0;
2851
2852   foreach_iter(exec_list_iterator, iter, v->instructions) {
2853      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
2854
2855      if (is_tex_instruction(inst->op)) {
2856         v->samplers_used |= 1 << inst->sampler;
2857
2858         if (inst->tex_shadow) {
2859            prog->ShadowSamplers |= 1 << inst->sampler;
2860         }
2861      }
2862   }
2863
2864   prog->SamplersUsed = v->samplers_used;
2865
2866   if (v->shader_program != NULL)
2867      _mesa_update_shader_textures_used(v->shader_program, prog);
2868}
2869
2870static void
2871set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
2872        		struct gl_shader_program *shader_program,
2873        		const char *name, const glsl_type *type,
2874        		ir_constant *val)
2875{
2876   if (type->is_record()) {
2877      ir_constant *field_constant;
2878
2879      field_constant = (ir_constant *)val->components.get_head();
2880
2881      for (unsigned int i = 0; i < type->length; i++) {
2882         const glsl_type *field_type = type->fields.structure[i].type;
2883         const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
2884        				    type->fields.structure[i].name);
2885         set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2886        			 field_type, field_constant);
2887         field_constant = (ir_constant *)field_constant->next;
2888      }
2889      return;
2890   }
2891
2892   unsigned offset;
2893   unsigned index = _mesa_get_uniform_location(ctx, shader_program, name,
2894					       &offset);
2895   if (offset == GL_INVALID_INDEX) {
2896      fail_link(shader_program,
2897        	"Couldn't find uniform for initializer %s\n", name);
2898      return;
2899   }
2900   int loc = _mesa_uniform_merge_location_offset(index, offset);
2901
2902   for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2903      ir_constant *element;
2904      const glsl_type *element_type;
2905      if (type->is_array()) {
2906         element = val->array_elements[i];
2907         element_type = type->fields.array;
2908      } else {
2909         element = val;
2910         element_type = type;
2911      }
2912
2913      void *values;
2914
2915      if (element_type->base_type == GLSL_TYPE_BOOL) {
2916         int *conv = ralloc_array(mem_ctx, int, element_type->components());
2917         for (unsigned int j = 0; j < element_type->components(); j++) {
2918            conv[j] = element->value.b[j];
2919         }
2920         values = (void *)conv;
2921         element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2922        					element_type->vector_elements,
2923        					1);
2924      } else {
2925         values = &element->value;
2926      }
2927
2928      if (element_type->is_matrix()) {
2929         _mesa_uniform_matrix(ctx, shader_program,
2930        		      element_type->matrix_columns,
2931        		      element_type->vector_elements,
2932        		      loc, 1, GL_FALSE, (GLfloat *)values);
2933      } else {
2934         _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2935        	       values, element_type->gl_type);
2936      }
2937
2938      loc++;
2939   }
2940}
2941
2942/**
2943 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
2944 * are read from the given src in this instruction
2945 */
2946static int
2947get_src_arg_mask(st_dst_reg dst, st_src_reg src)
2948{
2949   int read_mask = 0, comp;
2950
2951   /* Now, given the src swizzle and the written channels, find which
2952    * components are actually read
2953    */
2954   for (comp = 0; comp < 4; ++comp) {
2955      const unsigned coord = GET_SWZ(src.swizzle, comp);
2956      ASSERT(coord < 4);
2957      if (dst.writemask & (1 << comp) && coord <= SWIZZLE_W)
2958         read_mask |= 1 << coord;
2959   }
2960
2961   return read_mask;
2962}
2963
2964/**
2965 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
2966 * instruction is the first instruction to write to register T0.  There are
2967 * several lowering passes done in GLSL IR (e.g. branches and
2968 * relative addressing) that create a large number of conditional assignments
2969 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
2970 *
2971 * Here is why this conversion is safe:
2972 * CMP T0, T1 T2 T0 can be expanded to:
2973 * if (T1 < 0.0)
2974 * 	MOV T0, T2;
2975 * else
2976 * 	MOV T0, T0;
2977 *
2978 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
2979 * as the original program.  If (T1 < 0.0) evaluates to false, executing
2980 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
2981 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
2982 * because any instruction that was going to read from T0 after this was going
2983 * to read a garbage value anyway.
2984 */
2985void
2986glsl_to_tgsi_visitor::simplify_cmp(void)
2987{
2988   unsigned *tempWrites;
2989   unsigned outputWrites[MAX_PROGRAM_OUTPUTS];
2990
2991   tempWrites = new unsigned[MAX_TEMPS];
2992   if (!tempWrites) {
2993      return;
2994   }
2995   memset(tempWrites, 0, sizeof(unsigned) * MAX_TEMPS);
2996   memset(outputWrites, 0, sizeof(outputWrites));
2997
2998   foreach_iter(exec_list_iterator, iter, this->instructions) {
2999      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3000      unsigned prevWriteMask = 0;
3001
3002      /* Give up if we encounter relative addressing or flow control. */
3003      if (inst->dst.reladdr ||
3004          tgsi_get_opcode_info(inst->op)->is_branch ||
3005          inst->op == TGSI_OPCODE_BGNSUB ||
3006          inst->op == TGSI_OPCODE_CONT ||
3007          inst->op == TGSI_OPCODE_END ||
3008          inst->op == TGSI_OPCODE_ENDSUB ||
3009          inst->op == TGSI_OPCODE_RET) {
3010         break;
3011      }
3012
3013      if (inst->dst.file == PROGRAM_OUTPUT) {
3014         assert(inst->dst.index < MAX_PROGRAM_OUTPUTS);
3015         prevWriteMask = outputWrites[inst->dst.index];
3016         outputWrites[inst->dst.index] |= inst->dst.writemask;
3017      } else if (inst->dst.file == PROGRAM_TEMPORARY) {
3018         assert(inst->dst.index < MAX_TEMPS);
3019         prevWriteMask = tempWrites[inst->dst.index];
3020         tempWrites[inst->dst.index] |= inst->dst.writemask;
3021      }
3022
3023      /* For a CMP to be considered a conditional write, the destination
3024       * register and source register two must be the same. */
3025      if (inst->op == TGSI_OPCODE_CMP
3026          && !(inst->dst.writemask & prevWriteMask)
3027          && inst->src[2].file == inst->dst.file
3028          && inst->src[2].index == inst->dst.index
3029          && inst->dst.writemask == get_src_arg_mask(inst->dst, inst->src[2])) {
3030
3031         inst->op = TGSI_OPCODE_MOV;
3032         inst->src[0] = inst->src[1];
3033      }
3034   }
3035
3036   delete [] tempWrites;
3037}
3038
3039/* Replaces all references to a temporary register index with another index. */
3040void
3041glsl_to_tgsi_visitor::rename_temp_register(int index, int new_index)
3042{
3043   foreach_iter(exec_list_iterator, iter, this->instructions) {
3044      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3045      unsigned j;
3046
3047      for (j=0; j < num_inst_src_regs(inst->op); j++) {
3048         if (inst->src[j].file == PROGRAM_TEMPORARY &&
3049             inst->src[j].index == index) {
3050            inst->src[j].index = new_index;
3051         }
3052      }
3053
3054      if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index) {
3055         inst->dst.index = new_index;
3056      }
3057   }
3058}
3059
3060int
3061glsl_to_tgsi_visitor::get_first_temp_read(int index)
3062{
3063   int depth = 0; /* loop depth */
3064   int loop_start = -1; /* index of the first active BGNLOOP (if any) */
3065   unsigned i = 0, j;
3066
3067   foreach_iter(exec_list_iterator, iter, this->instructions) {
3068      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3069
3070      for (j=0; j < num_inst_src_regs(inst->op); j++) {
3071         if (inst->src[j].file == PROGRAM_TEMPORARY &&
3072             inst->src[j].index == index) {
3073            return (depth == 0) ? i : loop_start;
3074         }
3075      }
3076
3077      if (inst->op == TGSI_OPCODE_BGNLOOP) {
3078         if(depth++ == 0)
3079            loop_start = i;
3080      } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
3081         if (--depth == 0)
3082            loop_start = -1;
3083      }
3084      assert(depth >= 0);
3085
3086      i++;
3087   }
3088
3089   return -1;
3090}
3091
3092int
3093glsl_to_tgsi_visitor::get_first_temp_write(int index)
3094{
3095   int depth = 0; /* loop depth */
3096   int loop_start = -1; /* index of the first active BGNLOOP (if any) */
3097   int i = 0;
3098
3099   foreach_iter(exec_list_iterator, iter, this->instructions) {
3100      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3101
3102      if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index) {
3103         return (depth == 0) ? i : loop_start;
3104      }
3105
3106      if (inst->op == TGSI_OPCODE_BGNLOOP) {
3107         if(depth++ == 0)
3108            loop_start = i;
3109      } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
3110         if (--depth == 0)
3111            loop_start = -1;
3112      }
3113      assert(depth >= 0);
3114
3115      i++;
3116   }
3117
3118   return -1;
3119}
3120
3121int
3122glsl_to_tgsi_visitor::get_last_temp_read(int index)
3123{
3124   int depth = 0; /* loop depth */
3125   int last = -1; /* index of last instruction that reads the temporary */
3126   unsigned i = 0, j;
3127
3128   foreach_iter(exec_list_iterator, iter, this->instructions) {
3129      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3130
3131      for (j=0; j < num_inst_src_regs(inst->op); j++) {
3132         if (inst->src[j].file == PROGRAM_TEMPORARY &&
3133             inst->src[j].index == index) {
3134            last = (depth == 0) ? i : -2;
3135         }
3136      }
3137
3138      if (inst->op == TGSI_OPCODE_BGNLOOP)
3139         depth++;
3140      else if (inst->op == TGSI_OPCODE_ENDLOOP)
3141         if (--depth == 0 && last == -2)
3142            last = i;
3143      assert(depth >= 0);
3144
3145      i++;
3146   }
3147
3148   assert(last >= -1);
3149   return last;
3150}
3151
3152int
3153glsl_to_tgsi_visitor::get_last_temp_write(int index)
3154{
3155   int depth = 0; /* loop depth */
3156   int last = -1; /* index of last instruction that writes to the temporary */
3157   int i = 0;
3158
3159   foreach_iter(exec_list_iterator, iter, this->instructions) {
3160      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3161
3162      if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == index)
3163         last = (depth == 0) ? i : -2;
3164
3165      if (inst->op == TGSI_OPCODE_BGNLOOP)
3166         depth++;
3167      else if (inst->op == TGSI_OPCODE_ENDLOOP)
3168         if (--depth == 0 && last == -2)
3169            last = i;
3170      assert(depth >= 0);
3171
3172      i++;
3173   }
3174
3175   assert(last >= -1);
3176   return last;
3177}
3178
3179/*
3180 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
3181 * channels for copy propagation and updates following instructions to
3182 * use the original versions.
3183 *
3184 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3185 * will occur.  As an example, a TXP production before this pass:
3186 *
3187 * 0: MOV TEMP[1], INPUT[4].xyyy;
3188 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3189 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
3190 *
3191 * and after:
3192 *
3193 * 0: MOV TEMP[1], INPUT[4].xyyy;
3194 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3195 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3196 *
3197 * which allows for dead code elimination on TEMP[1]'s writes.
3198 */
3199void
3200glsl_to_tgsi_visitor::copy_propagate(void)
3201{
3202   glsl_to_tgsi_instruction **acp = rzalloc_array(mem_ctx,
3203        					    glsl_to_tgsi_instruction *,
3204        					    this->next_temp * 4);
3205   int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
3206   int level = 0;
3207
3208   foreach_iter(exec_list_iterator, iter, this->instructions) {
3209      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3210
3211      assert(inst->dst.file != PROGRAM_TEMPORARY
3212             || inst->dst.index < this->next_temp);
3213
3214      /* First, do any copy propagation possible into the src regs. */
3215      for (int r = 0; r < 3; r++) {
3216         glsl_to_tgsi_instruction *first = NULL;
3217         bool good = true;
3218         int acp_base = inst->src[r].index * 4;
3219
3220         if (inst->src[r].file != PROGRAM_TEMPORARY ||
3221             inst->src[r].reladdr)
3222            continue;
3223
3224         /* See if we can find entries in the ACP consisting of MOVs
3225          * from the same src register for all the swizzled channels
3226          * of this src register reference.
3227          */
3228         for (int i = 0; i < 4; i++) {
3229            int src_chan = GET_SWZ(inst->src[r].swizzle, i);
3230            glsl_to_tgsi_instruction *copy_chan = acp[acp_base + src_chan];
3231
3232            if (!copy_chan) {
3233               good = false;
3234               break;
3235            }
3236
3237            assert(acp_level[acp_base + src_chan] <= level);
3238
3239            if (!first) {
3240               first = copy_chan;
3241            } else {
3242               if (first->src[0].file != copy_chan->src[0].file ||
3243        	   first->src[0].index != copy_chan->src[0].index) {
3244        	  good = false;
3245        	  break;
3246               }
3247            }
3248         }
3249
3250         if (good) {
3251            /* We've now validated that we can copy-propagate to
3252             * replace this src register reference.  Do it.
3253             */
3254            inst->src[r].file = first->src[0].file;
3255            inst->src[r].index = first->src[0].index;
3256
3257            int swizzle = 0;
3258            for (int i = 0; i < 4; i++) {
3259               int src_chan = GET_SWZ(inst->src[r].swizzle, i);
3260               glsl_to_tgsi_instruction *copy_inst = acp[acp_base + src_chan];
3261               swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) <<
3262        		   (3 * i));
3263            }
3264            inst->src[r].swizzle = swizzle;
3265         }
3266      }
3267
3268      switch (inst->op) {
3269      case TGSI_OPCODE_BGNLOOP:
3270      case TGSI_OPCODE_ENDLOOP:
3271         /* End of a basic block, clear the ACP entirely. */
3272         memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
3273         break;
3274
3275      case TGSI_OPCODE_IF:
3276         ++level;
3277         break;
3278
3279      case TGSI_OPCODE_ENDIF:
3280      case TGSI_OPCODE_ELSE:
3281         /* Clear all channels written inside the block from the ACP, but
3282          * leaving those that were not touched.
3283          */
3284         for (int r = 0; r < this->next_temp; r++) {
3285            for (int c = 0; c < 4; c++) {
3286               if (!acp[4 * r + c])
3287        	  continue;
3288
3289               if (acp_level[4 * r + c] >= level)
3290        	  acp[4 * r + c] = NULL;
3291            }
3292         }
3293         if (inst->op == TGSI_OPCODE_ENDIF)
3294            --level;
3295         break;
3296
3297      default:
3298         /* Continuing the block, clear any written channels from
3299          * the ACP.
3300          */
3301         if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.reladdr) {
3302            /* Any temporary might be written, so no copy propagation
3303             * across this instruction.
3304             */
3305            memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
3306         } else if (inst->dst.file == PROGRAM_OUTPUT &&
3307        	    inst->dst.reladdr) {
3308            /* Any output might be written, so no copy propagation
3309             * from outputs across this instruction.
3310             */
3311            for (int r = 0; r < this->next_temp; r++) {
3312               for (int c = 0; c < 4; c++) {
3313        	  if (!acp[4 * r + c])
3314        	     continue;
3315
3316        	  if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
3317        	     acp[4 * r + c] = NULL;
3318               }
3319            }
3320         } else if (inst->dst.file == PROGRAM_TEMPORARY ||
3321        	    inst->dst.file == PROGRAM_OUTPUT) {
3322            /* Clear where it's used as dst. */
3323            if (inst->dst.file == PROGRAM_TEMPORARY) {
3324               for (int c = 0; c < 4; c++) {
3325        	  if (inst->dst.writemask & (1 << c)) {
3326        	     acp[4 * inst->dst.index + c] = NULL;
3327        	  }
3328               }
3329            }
3330
3331            /* Clear where it's used as src. */
3332            for (int r = 0; r < this->next_temp; r++) {
3333               for (int c = 0; c < 4; c++) {
3334        	  if (!acp[4 * r + c])
3335        	     continue;
3336
3337        	  int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
3338
3339        	  if (acp[4 * r + c]->src[0].file == inst->dst.file &&
3340        	      acp[4 * r + c]->src[0].index == inst->dst.index &&
3341        	      inst->dst.writemask & (1 << src_chan))
3342        	  {
3343        	     acp[4 * r + c] = NULL;
3344        	  }
3345               }
3346            }
3347         }
3348         break;
3349      }
3350
3351      /* If this is a copy, add it to the ACP. */
3352      if (inst->op == TGSI_OPCODE_MOV &&
3353          inst->dst.file == PROGRAM_TEMPORARY &&
3354          !inst->dst.reladdr &&
3355          !inst->saturate &&
3356          !inst->src[0].reladdr &&
3357          !inst->src[0].negate) {
3358         for (int i = 0; i < 4; i++) {
3359            if (inst->dst.writemask & (1 << i)) {
3360               acp[4 * inst->dst.index + i] = inst;
3361               acp_level[4 * inst->dst.index + i] = level;
3362            }
3363         }
3364      }
3365   }
3366
3367   ralloc_free(acp_level);
3368   ralloc_free(acp);
3369}
3370
3371/*
3372 * Tracks available PROGRAM_TEMPORARY registers for dead code elimination.
3373 *
3374 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3375 * will occur.  As an example, a TXP production after copy propagation but
3376 * before this pass:
3377 *
3378 * 0: MOV TEMP[1], INPUT[4].xyyy;
3379 * 1: MOV TEMP[1].w, INPUT[4].wwww;
3380 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3381 *
3382 * and after this pass:
3383 *
3384 * 0: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
3385 *
3386 * FIXME: assumes that all functions are inlined (no support for BGNSUB/ENDSUB)
3387 * FIXME: doesn't eliminate all dead code inside of loops; it steps around them
3388 */
3389void
3390glsl_to_tgsi_visitor::eliminate_dead_code(void)
3391{
3392   int i;
3393
3394   for (i=0; i < this->next_temp; i++) {
3395      int last_read = get_last_temp_read(i);
3396      int j = 0;
3397
3398      foreach_iter(exec_list_iterator, iter, this->instructions) {
3399         glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3400
3401         if (inst->dst.file == PROGRAM_TEMPORARY && inst->dst.index == i &&
3402             j > last_read)
3403         {
3404            iter.remove();
3405            delete inst;
3406         }
3407
3408         j++;
3409      }
3410   }
3411}
3412
3413/*
3414 * On a basic block basis, tracks available PROGRAM_TEMPORARY registers for dead
3415 * code elimination.  This is less primitive than eliminate_dead_code(), as it
3416 * is per-channel and can detect consecutive writes without a read between them
3417 * as dead code.  However, there is some dead code that can be eliminated by
3418 * eliminate_dead_code() but not this function - for example, this function
3419 * cannot eliminate an instruction writing to a register that is never read and
3420 * is the only instruction writing to that register.
3421 *
3422 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
3423 * will occur.
3424 */
3425int
3426glsl_to_tgsi_visitor::eliminate_dead_code_advanced(void)
3427{
3428   glsl_to_tgsi_instruction **writes = rzalloc_array(mem_ctx,
3429                                                     glsl_to_tgsi_instruction *,
3430                                                     this->next_temp * 4);
3431   int *write_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
3432   int level = 0;
3433   int removed = 0;
3434
3435   foreach_iter(exec_list_iterator, iter, this->instructions) {
3436      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3437
3438      assert(inst->dst.file != PROGRAM_TEMPORARY
3439             || inst->dst.index < this->next_temp);
3440
3441      switch (inst->op) {
3442      case TGSI_OPCODE_BGNLOOP:
3443      case TGSI_OPCODE_ENDLOOP:
3444      case TGSI_OPCODE_CONT:
3445      case TGSI_OPCODE_BRK:
3446         /* End of a basic block, clear the write array entirely.
3447          *
3448          * This keeps us from killing dead code when the writes are
3449          * on either side of a loop, even when the register isn't touched
3450          * inside the loop.  However, glsl_to_tgsi_visitor doesn't seem to emit
3451          * dead code of this type, so it shouldn't make a difference as long as
3452          * the dead code elimination pass in the GLSL compiler does its job.
3453          */
3454         memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
3455         break;
3456
3457      case TGSI_OPCODE_ENDIF:
3458      case TGSI_OPCODE_ELSE:
3459         /* Promote the recorded level of all channels written inside the
3460          * preceding if or else block to the level above the if/else block.
3461          */
3462         for (int r = 0; r < this->next_temp; r++) {
3463            for (int c = 0; c < 4; c++) {
3464               if (!writes[4 * r + c])
3465        	         continue;
3466
3467               if (write_level[4 * r + c] == level)
3468        	         write_level[4 * r + c] = level-1;
3469            }
3470         }
3471
3472         if(inst->op == TGSI_OPCODE_ENDIF)
3473            --level;
3474
3475         break;
3476
3477      case TGSI_OPCODE_IF:
3478         ++level;
3479         /* fallthrough to default case to mark the condition as read */
3480
3481      default:
3482         /* Continuing the block, clear any channels from the write array that
3483          * are read by this instruction.
3484          */
3485         for (unsigned i = 0; i < Elements(inst->src); i++) {
3486            if (inst->src[i].file == PROGRAM_TEMPORARY && inst->src[i].reladdr){
3487               /* Any temporary might be read, so no dead code elimination
3488                * across this instruction.
3489                */
3490               memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
3491            } else if (inst->src[i].file == PROGRAM_TEMPORARY) {
3492               /* Clear where it's used as src. */
3493               int src_chans = 1 << GET_SWZ(inst->src[i].swizzle, 0);
3494               src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 1);
3495               src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 2);
3496               src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 3);
3497
3498               for (int c = 0; c < 4; c++) {
3499              	   if (src_chans & (1 << c)) {
3500              	      writes[4 * inst->src[i].index + c] = NULL;
3501              	   }
3502               }
3503            }
3504         }
3505         break;
3506      }
3507
3508      /* If this instruction writes to a temporary, add it to the write array.
3509       * If there is already an instruction in the write array for one or more
3510       * of the channels, flag that channel write as dead.
3511       */
3512      if (inst->dst.file == PROGRAM_TEMPORARY &&
3513          !inst->dst.reladdr &&
3514          !inst->saturate) {
3515         for (int c = 0; c < 4; c++) {
3516            if (inst->dst.writemask & (1 << c)) {
3517               if (writes[4 * inst->dst.index + c]) {
3518                  if (write_level[4 * inst->dst.index + c] < level)
3519                     continue;
3520                  else
3521                     writes[4 * inst->dst.index + c]->dead_mask |= (1 << c);
3522               }
3523               writes[4 * inst->dst.index + c] = inst;
3524               write_level[4 * inst->dst.index + c] = level;
3525            }
3526         }
3527      }
3528   }
3529
3530   /* Anything still in the write array at this point is dead code. */
3531   for (int r = 0; r < this->next_temp; r++) {
3532      for (int c = 0; c < 4; c++) {
3533         glsl_to_tgsi_instruction *inst = writes[4 * r + c];
3534         if (inst)
3535            inst->dead_mask |= (1 << c);
3536      }
3537   }
3538
3539   /* Now actually remove the instructions that are completely dead and update
3540    * the writemask of other instructions with dead channels.
3541    */
3542   foreach_iter(exec_list_iterator, iter, this->instructions) {
3543      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3544
3545      if (!inst->dead_mask || !inst->dst.writemask)
3546         continue;
3547      else if ((inst->dst.writemask & ~inst->dead_mask) == 0) {
3548         iter.remove();
3549         delete inst;
3550         removed++;
3551      } else
3552         inst->dst.writemask &= ~(inst->dead_mask);
3553   }
3554
3555   ralloc_free(write_level);
3556   ralloc_free(writes);
3557
3558   return removed;
3559}
3560
3561/* Merges temporary registers together where possible to reduce the number of
3562 * registers needed to run a program.
3563 *
3564 * Produces optimal code only after copy propagation and dead code elimination
3565 * have been run. */
3566void
3567glsl_to_tgsi_visitor::merge_registers(void)
3568{
3569   int *last_reads = rzalloc_array(mem_ctx, int, this->next_temp);
3570   int *first_writes = rzalloc_array(mem_ctx, int, this->next_temp);
3571   int i, j;
3572
3573   /* Read the indices of the last read and first write to each temp register
3574    * into an array so that we don't have to traverse the instruction list as
3575    * much. */
3576   for (i=0; i < this->next_temp; i++) {
3577      last_reads[i] = get_last_temp_read(i);
3578      first_writes[i] = get_first_temp_write(i);
3579   }
3580
3581   /* Start looking for registers with non-overlapping usages that can be
3582    * merged together. */
3583   for (i=0; i < this->next_temp; i++) {
3584      /* Don't touch unused registers. */
3585      if (last_reads[i] < 0 || first_writes[i] < 0) continue;
3586
3587      for (j=0; j < this->next_temp; j++) {
3588         /* Don't touch unused registers. */
3589         if (last_reads[j] < 0 || first_writes[j] < 0) continue;
3590
3591         /* We can merge the two registers if the first write to j is after or
3592          * in the same instruction as the last read from i.  Note that the
3593          * register at index i will always be used earlier or at the same time
3594          * as the register at index j. */
3595         if (first_writes[i] <= first_writes[j] &&
3596             last_reads[i] <= first_writes[j])
3597         {
3598            rename_temp_register(j, i); /* Replace all references to j with i.*/
3599
3600            /* Update the first_writes and last_reads arrays with the new
3601             * values for the merged register index, and mark the newly unused
3602             * register index as such. */
3603            last_reads[i] = last_reads[j];
3604            first_writes[j] = -1;
3605            last_reads[j] = -1;
3606         }
3607      }
3608   }
3609
3610   ralloc_free(last_reads);
3611   ralloc_free(first_writes);
3612}
3613
3614/* Reassign indices to temporary registers by reusing unused indices created
3615 * by optimization passes. */
3616void
3617glsl_to_tgsi_visitor::renumber_registers(void)
3618{
3619   int i = 0;
3620   int new_index = 0;
3621
3622   for (i=0; i < this->next_temp; i++) {
3623      if (get_first_temp_read(i) < 0) continue;
3624      if (i != new_index)
3625         rename_temp_register(i, new_index);
3626      new_index++;
3627   }
3628
3629   this->next_temp = new_index;
3630}
3631
3632/**
3633 * Returns a fragment program which implements the current pixel transfer ops.
3634 * Based on get_pixel_transfer_program in st_atom_pixeltransfer.c.
3635 */
3636extern "C" void
3637get_pixel_transfer_visitor(struct st_fragment_program *fp,
3638                           glsl_to_tgsi_visitor *original,
3639                           int scale_and_bias, int pixel_maps)
3640{
3641   glsl_to_tgsi_visitor *v = new glsl_to_tgsi_visitor();
3642   struct st_context *st = st_context(original->ctx);
3643   struct gl_program *prog = &fp->Base.Base;
3644   struct gl_program_parameter_list *params = _mesa_new_parameter_list();
3645   st_src_reg coord, src0;
3646   st_dst_reg dst0;
3647   glsl_to_tgsi_instruction *inst;
3648
3649   /* Copy attributes of the glsl_to_tgsi_visitor in the original shader. */
3650   v->ctx = original->ctx;
3651   v->prog = prog;
3652   v->shader_program = NULL;
3653   v->glsl_version = original->glsl_version;
3654   v->native_integers = original->native_integers;
3655   v->options = original->options;
3656   v->next_temp = original->next_temp;
3657   v->num_address_regs = original->num_address_regs;
3658   v->samplers_used = prog->SamplersUsed = original->samplers_used;
3659   v->indirect_addr_temps = original->indirect_addr_temps;
3660   v->indirect_addr_consts = original->indirect_addr_consts;
3661   memcpy(&v->immediates, &original->immediates, sizeof(v->immediates));
3662   v->num_immediates = original->num_immediates;
3663
3664   /*
3665    * Get initial pixel color from the texture.
3666    * TEX colorTemp, fragment.texcoord[0], texture[0], 2D;
3667    */
3668   coord = st_src_reg(PROGRAM_INPUT, FRAG_ATTRIB_TEX0, glsl_type::vec2_type);
3669   src0 = v->get_temp(glsl_type::vec4_type);
3670   dst0 = st_dst_reg(src0);
3671   inst = v->emit(NULL, TGSI_OPCODE_TEX, dst0, coord);
3672   inst->sampler = 0;
3673   inst->tex_target = TEXTURE_2D_INDEX;
3674
3675   prog->InputsRead |= FRAG_BIT_TEX0;
3676   prog->SamplersUsed |= (1 << 0); /* mark sampler 0 as used */
3677   v->samplers_used |= (1 << 0);
3678
3679   if (scale_and_bias) {
3680      static const gl_state_index scale_state[STATE_LENGTH] =
3681         { STATE_INTERNAL, STATE_PT_SCALE,
3682           (gl_state_index) 0, (gl_state_index) 0, (gl_state_index) 0 };
3683      static const gl_state_index bias_state[STATE_LENGTH] =
3684         { STATE_INTERNAL, STATE_PT_BIAS,
3685           (gl_state_index) 0, (gl_state_index) 0, (gl_state_index) 0 };
3686      GLint scale_p, bias_p;
3687      st_src_reg scale, bias;
3688
3689      scale_p = _mesa_add_state_reference(params, scale_state);
3690      bias_p = _mesa_add_state_reference(params, bias_state);
3691
3692      /* MAD colorTemp, colorTemp, scale, bias; */
3693      scale = st_src_reg(PROGRAM_STATE_VAR, scale_p, GLSL_TYPE_FLOAT);
3694      bias = st_src_reg(PROGRAM_STATE_VAR, bias_p, GLSL_TYPE_FLOAT);
3695      inst = v->emit(NULL, TGSI_OPCODE_MAD, dst0, src0, scale, bias);
3696   }
3697
3698   if (pixel_maps) {
3699      st_src_reg temp = v->get_temp(glsl_type::vec4_type);
3700      st_dst_reg temp_dst = st_dst_reg(temp);
3701
3702      assert(st->pixel_xfer.pixelmap_texture);
3703
3704      /* With a little effort, we can do four pixel map look-ups with
3705       * two TEX instructions:
3706       */
3707
3708      /* TEX temp.rg, colorTemp.rgba, texture[1], 2D; */
3709      temp_dst.writemask = WRITEMASK_XY; /* write R,G */
3710      inst = v->emit(NULL, TGSI_OPCODE_TEX, temp_dst, src0);
3711      inst->sampler = 1;
3712      inst->tex_target = TEXTURE_2D_INDEX;
3713
3714      /* TEX temp.ba, colorTemp.baba, texture[1], 2D; */
3715      src0.swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W);
3716      temp_dst.writemask = WRITEMASK_ZW; /* write B,A */
3717      inst = v->emit(NULL, TGSI_OPCODE_TEX, temp_dst, src0);
3718      inst->sampler = 1;
3719      inst->tex_target = TEXTURE_2D_INDEX;
3720
3721      prog->SamplersUsed |= (1 << 1); /* mark sampler 1 as used */
3722      v->samplers_used |= (1 << 1);
3723
3724      /* MOV colorTemp, temp; */
3725      inst = v->emit(NULL, TGSI_OPCODE_MOV, dst0, temp);
3726   }
3727
3728   /* Now copy the instructions from the original glsl_to_tgsi_visitor into the
3729    * new visitor. */
3730   foreach_iter(exec_list_iterator, iter, original->instructions) {
3731      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3732      glsl_to_tgsi_instruction *newinst;
3733      st_src_reg src_regs[3];
3734
3735      if (inst->dst.file == PROGRAM_OUTPUT)
3736         prog->OutputsWritten |= BITFIELD64_BIT(inst->dst.index);
3737
3738      for (int i=0; i<3; i++) {
3739         src_regs[i] = inst->src[i];
3740         if (src_regs[i].file == PROGRAM_INPUT &&
3741             src_regs[i].index == FRAG_ATTRIB_COL0)
3742         {
3743            src_regs[i].file = PROGRAM_TEMPORARY;
3744            src_regs[i].index = src0.index;
3745         }
3746         else if (src_regs[i].file == PROGRAM_INPUT)
3747            prog->InputsRead |= BITFIELD64_BIT(src_regs[i].index);
3748      }
3749
3750      newinst = v->emit(NULL, inst->op, inst->dst, src_regs[0], src_regs[1], src_regs[2]);
3751      newinst->tex_target = inst->tex_target;
3752   }
3753
3754   /* Make modifications to fragment program info. */
3755   prog->Parameters = _mesa_combine_parameter_lists(params,
3756                                                    original->prog->Parameters);
3757   _mesa_free_parameter_list(params);
3758   count_resources(v, prog);
3759   fp->glsl_to_tgsi = v;
3760}
3761
3762/**
3763 * Make fragment program for glBitmap:
3764 *   Sample the texture and kill the fragment if the bit is 0.
3765 * This program will be combined with the user's fragment program.
3766 *
3767 * Based on make_bitmap_fragment_program in st_cb_bitmap.c.
3768 */
3769extern "C" void
3770get_bitmap_visitor(struct st_fragment_program *fp,
3771                   glsl_to_tgsi_visitor *original, int samplerIndex)
3772{
3773   glsl_to_tgsi_visitor *v = new glsl_to_tgsi_visitor();
3774   struct st_context *st = st_context(original->ctx);
3775   struct gl_program *prog = &fp->Base.Base;
3776   st_src_reg coord, src0;
3777   st_dst_reg dst0;
3778   glsl_to_tgsi_instruction *inst;
3779
3780   /* Copy attributes of the glsl_to_tgsi_visitor in the original shader. */
3781   v->ctx = original->ctx;
3782   v->prog = prog;
3783   v->shader_program = NULL;
3784   v->glsl_version = original->glsl_version;
3785   v->native_integers = original->native_integers;
3786   v->options = original->options;
3787   v->next_temp = original->next_temp;
3788   v->num_address_regs = original->num_address_regs;
3789   v->samplers_used = prog->SamplersUsed = original->samplers_used;
3790   v->indirect_addr_temps = original->indirect_addr_temps;
3791   v->indirect_addr_consts = original->indirect_addr_consts;
3792   memcpy(&v->immediates, &original->immediates, sizeof(v->immediates));
3793   v->num_immediates = original->num_immediates;
3794
3795   /* TEX tmp0, fragment.texcoord[0], texture[0], 2D; */
3796   coord = st_src_reg(PROGRAM_INPUT, FRAG_ATTRIB_TEX0, glsl_type::vec2_type);
3797   src0 = v->get_temp(glsl_type::vec4_type);
3798   dst0 = st_dst_reg(src0);
3799   inst = v->emit(NULL, TGSI_OPCODE_TEX, dst0, coord);
3800   inst->sampler = samplerIndex;
3801   inst->tex_target = TEXTURE_2D_INDEX;
3802
3803   prog->InputsRead |= FRAG_BIT_TEX0;
3804   prog->SamplersUsed |= (1 << samplerIndex); /* mark sampler as used */
3805   v->samplers_used |= (1 << samplerIndex);
3806
3807   /* KIL if -tmp0 < 0 # texel=0 -> keep / texel=0 -> discard */
3808   src0.negate = NEGATE_XYZW;
3809   if (st->bitmap.tex_format == PIPE_FORMAT_L8_UNORM)
3810      src0.swizzle = SWIZZLE_XXXX;
3811   inst = v->emit(NULL, TGSI_OPCODE_KIL, undef_dst, src0);
3812
3813   /* Now copy the instructions from the original glsl_to_tgsi_visitor into the
3814    * new visitor. */
3815   foreach_iter(exec_list_iterator, iter, original->instructions) {
3816      glsl_to_tgsi_instruction *inst = (glsl_to_tgsi_instruction *)iter.get();
3817      glsl_to_tgsi_instruction *newinst;
3818      st_src_reg src_regs[3];
3819
3820      if (inst->dst.file == PROGRAM_OUTPUT)
3821         prog->OutputsWritten |= BITFIELD64_BIT(inst->dst.index);
3822
3823      for (int i=0; i<3; i++) {
3824         src_regs[i] = inst->src[i];
3825         if (src_regs[i].file == PROGRAM_INPUT)
3826            prog->InputsRead |= BITFIELD64_BIT(src_regs[i].index);
3827      }
3828
3829      newinst = v->emit(NULL, inst->op, inst->dst, src_regs[0], src_regs[1], src_regs[2]);
3830      newinst->tex_target = inst->tex_target;
3831   }
3832
3833   /* Make modifications to fragment program info. */
3834   prog->Parameters = _mesa_clone_parameter_list(original->prog->Parameters);
3835   count_resources(v, prog);
3836   fp->glsl_to_tgsi = v;
3837}
3838
3839/* ------------------------- TGSI conversion stuff -------------------------- */
3840struct label {
3841   unsigned branch_target;
3842   unsigned token;
3843};
3844
3845/**
3846 * Intermediate state used during shader translation.
3847 */
3848struct st_translate {
3849   struct ureg_program *ureg;
3850
3851   struct ureg_dst temps[MAX_TEMPS];
3852   struct ureg_src *constants;
3853   struct ureg_src *immediates;
3854   struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
3855   struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
3856   struct ureg_dst address[1];
3857   struct ureg_src samplers[PIPE_MAX_SAMPLERS];
3858   struct ureg_src systemValues[SYSTEM_VALUE_MAX];
3859
3860   const GLuint *inputMapping;
3861   const GLuint *outputMapping;
3862
3863   /* For every instruction that contains a label (eg CALL), keep
3864    * details so that we can go back afterwards and emit the correct
3865    * tgsi instruction number for each label.
3866    */
3867   struct label *labels;
3868   unsigned labels_size;
3869   unsigned labels_count;
3870
3871   /* Keep a record of the tgsi instruction number that each mesa
3872    * instruction starts at, will be used to fix up labels after
3873    * translation.
3874    */
3875   unsigned *insn;
3876   unsigned insn_size;
3877   unsigned insn_count;
3878
3879   unsigned procType;  /**< TGSI_PROCESSOR_VERTEX/FRAGMENT */
3880
3881   boolean error;
3882};
3883
3884/** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
3885static unsigned mesa_sysval_to_semantic[SYSTEM_VALUE_MAX] = {
3886   TGSI_SEMANTIC_FACE,
3887   TGSI_SEMANTIC_VERTEXID,
3888   TGSI_SEMANTIC_INSTANCEID
3889};
3890
3891/**
3892 * Make note of a branch to a label in the TGSI code.
3893 * After we've emitted all instructions, we'll go over the list
3894 * of labels built here and patch the TGSI code with the actual
3895 * location of each label.
3896 */
3897static unsigned *get_label(struct st_translate *t, unsigned branch_target)
3898{
3899   unsigned i;
3900
3901   if (t->labels_count + 1 >= t->labels_size) {
3902      t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
3903      t->labels = (struct label *)realloc(t->labels,
3904                                          t->labels_size * sizeof(struct label));
3905      if (t->labels == NULL) {
3906         static unsigned dummy;
3907         t->error = TRUE;
3908         return &dummy;
3909      }
3910   }
3911
3912   i = t->labels_count++;
3913   t->labels[i].branch_target = branch_target;
3914   return &t->labels[i].token;
3915}
3916
3917/**
3918 * Called prior to emitting the TGSI code for each instruction.
3919 * Allocate additional space for instructions if needed.
3920 * Update the insn[] array so the next glsl_to_tgsi_instruction points to
3921 * the next TGSI instruction.
3922 */
3923static void set_insn_start(struct st_translate *t, unsigned start)
3924{
3925   if (t->insn_count + 1 >= t->insn_size) {
3926      t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
3927      t->insn = (unsigned *)realloc(t->insn, t->insn_size * sizeof(t->insn[0]));
3928      if (t->insn == NULL) {
3929         t->error = TRUE;
3930         return;
3931      }
3932   }
3933
3934   t->insn[t->insn_count++] = start;
3935}
3936
3937/**
3938 * Map a glsl_to_tgsi constant/immediate to a TGSI immediate.
3939 */
3940static struct ureg_src
3941emit_immediate(struct st_translate *t,
3942               gl_constant_value values[4],
3943               int type, int size)
3944{
3945   struct ureg_program *ureg = t->ureg;
3946
3947   switch(type)
3948   {
3949   case GL_FLOAT:
3950      return ureg_DECL_immediate(ureg, &values[0].f, size);
3951   case GL_INT:
3952      return ureg_DECL_immediate_int(ureg, &values[0].i, size);
3953   case GL_UNSIGNED_INT:
3954   case GL_BOOL:
3955      return ureg_DECL_immediate_uint(ureg, &values[0].u, size);
3956   default:
3957      assert(!"should not get here - type must be float, int, uint, or bool");
3958      return ureg_src_undef();
3959   }
3960}
3961
3962/**
3963 * Map a glsl_to_tgsi dst register to a TGSI ureg_dst register.
3964 */
3965static struct ureg_dst
3966dst_register(struct st_translate *t,
3967             gl_register_file file,
3968             GLuint index)
3969{
3970   switch(file) {
3971   case PROGRAM_UNDEFINED:
3972      return ureg_dst_undef();
3973
3974   case PROGRAM_TEMPORARY:
3975      if (ureg_dst_is_undef(t->temps[index]))
3976         t->temps[index] = ureg_DECL_local_temporary(t->ureg);
3977
3978      return t->temps[index];
3979
3980   case PROGRAM_OUTPUT:
3981      if (t->procType == TGSI_PROCESSOR_VERTEX)
3982         assert(index < VERT_RESULT_MAX);
3983      else if (t->procType == TGSI_PROCESSOR_FRAGMENT)
3984         assert(index < FRAG_RESULT_MAX);
3985      else
3986         assert(index < GEOM_RESULT_MAX);
3987
3988      assert(t->outputMapping[index] < Elements(t->outputs));
3989
3990      return t->outputs[t->outputMapping[index]];
3991
3992   case PROGRAM_ADDRESS:
3993      return t->address[index];
3994
3995   default:
3996      assert(!"unknown dst register file");
3997      return ureg_dst_undef();
3998   }
3999}
4000
4001/**
4002 * Map a glsl_to_tgsi src register to a TGSI ureg_src register.
4003 */
4004static struct ureg_src
4005src_register(struct st_translate *t,
4006             gl_register_file file,
4007             GLuint index)
4008{
4009   switch(file) {
4010   case PROGRAM_UNDEFINED:
4011      return ureg_src_undef();
4012
4013   case PROGRAM_TEMPORARY:
4014      assert(index >= 0);
4015      assert(index < Elements(t->temps));
4016      if (ureg_dst_is_undef(t->temps[index]))
4017         t->temps[index] = ureg_DECL_local_temporary(t->ureg);
4018      return ureg_src(t->temps[index]);
4019
4020   case PROGRAM_NAMED_PARAM:
4021   case PROGRAM_ENV_PARAM:
4022   case PROGRAM_LOCAL_PARAM:
4023   case PROGRAM_UNIFORM:
4024      assert(index >= 0);
4025      return t->constants[index];
4026   case PROGRAM_STATE_VAR:
4027   case PROGRAM_CONSTANT:       /* ie, immediate */
4028      if (index < 0)
4029         return ureg_DECL_constant(t->ureg, 0);
4030      else
4031         return t->constants[index];
4032
4033   case PROGRAM_IMMEDIATE:
4034      return t->immediates[index];
4035
4036   case PROGRAM_INPUT:
4037      assert(t->inputMapping[index] < Elements(t->inputs));
4038      return t->inputs[t->inputMapping[index]];
4039
4040   case PROGRAM_OUTPUT:
4041      assert(t->outputMapping[index] < Elements(t->outputs));
4042      return ureg_src(t->outputs[t->outputMapping[index]]); /* not needed? */
4043
4044   case PROGRAM_ADDRESS:
4045      return ureg_src(t->address[index]);
4046
4047   case PROGRAM_SYSTEM_VALUE:
4048      assert(index < Elements(t->systemValues));
4049      return t->systemValues[index];
4050
4051   default:
4052      assert(!"unknown src register file");
4053      return ureg_src_undef();
4054   }
4055}
4056
4057/**
4058 * Create a TGSI ureg_dst register from an st_dst_reg.
4059 */
4060static struct ureg_dst
4061translate_dst(struct st_translate *t,
4062              const st_dst_reg *dst_reg,
4063              bool saturate, bool clamp_color)
4064{
4065   struct ureg_dst dst = dst_register(t,
4066                                      dst_reg->file,
4067                                      dst_reg->index);
4068
4069   dst = ureg_writemask(dst, dst_reg->writemask);
4070
4071   if (saturate)
4072      dst = ureg_saturate(dst);
4073   else if (clamp_color && dst_reg->file == PROGRAM_OUTPUT) {
4074      /* Clamp colors for ARB_color_buffer_float. */
4075      switch (t->procType) {
4076      case TGSI_PROCESSOR_VERTEX:
4077         /* XXX if the geometry shader is present, this must be done there
4078          * instead of here. */
4079         if (dst_reg->index == VERT_RESULT_COL0 ||
4080             dst_reg->index == VERT_RESULT_COL1 ||
4081             dst_reg->index == VERT_RESULT_BFC0 ||
4082             dst_reg->index == VERT_RESULT_BFC1) {
4083            dst = ureg_saturate(dst);
4084         }
4085         break;
4086
4087      case TGSI_PROCESSOR_FRAGMENT:
4088         if (dst_reg->index >= FRAG_RESULT_COLOR) {
4089            dst = ureg_saturate(dst);
4090         }
4091         break;
4092      }
4093   }
4094
4095   if (dst_reg->reladdr != NULL)
4096      dst = ureg_dst_indirect(dst, ureg_src(t->address[0]));
4097
4098   return dst;
4099}
4100
4101/**
4102 * Create a TGSI ureg_src register from an st_src_reg.
4103 */
4104static struct ureg_src
4105translate_src(struct st_translate *t, const st_src_reg *src_reg)
4106{
4107   struct ureg_src src = src_register(t, src_reg->file, src_reg->index);
4108
4109   src = ureg_swizzle(src,
4110                      GET_SWZ(src_reg->swizzle, 0) & 0x3,
4111                      GET_SWZ(src_reg->swizzle, 1) & 0x3,
4112                      GET_SWZ(src_reg->swizzle, 2) & 0x3,
4113                      GET_SWZ(src_reg->swizzle, 3) & 0x3);
4114
4115   if ((src_reg->negate & 0xf) == NEGATE_XYZW)
4116      src = ureg_negate(src);
4117
4118   if (src_reg->reladdr != NULL) {
4119      /* Normally ureg_src_indirect() would be used here, but a stupid compiler
4120       * bug in g++ makes ureg_src_indirect (an inline C function) erroneously
4121       * set the bit for src.Negate.  So we have to do the operation manually
4122       * here to work around the compiler's problems. */
4123      /*src = ureg_src_indirect(src, ureg_src(t->address[0]));*/
4124      struct ureg_src addr = ureg_src(t->address[0]);
4125      src.Indirect = 1;
4126      src.IndirectFile = addr.File;
4127      src.IndirectIndex = addr.Index;
4128      src.IndirectSwizzle = addr.SwizzleX;
4129
4130      if (src_reg->file != PROGRAM_INPUT &&
4131          src_reg->file != PROGRAM_OUTPUT) {
4132         /* If src_reg->index was negative, it was set to zero in
4133          * src_register().  Reassign it now.  But don't do this
4134          * for input/output regs since they get remapped while
4135          * const buffers don't.
4136          */
4137         src.Index = src_reg->index;
4138      }
4139   }
4140
4141   return src;
4142}
4143
4144static struct tgsi_texture_offset
4145translate_tex_offset(struct st_translate *t,
4146                     const struct tgsi_texture_offset *in_offset)
4147{
4148   struct tgsi_texture_offset offset;
4149
4150   assert(in_offset->File == PROGRAM_IMMEDIATE);
4151
4152   offset.File = TGSI_FILE_IMMEDIATE;
4153   offset.Index = in_offset->Index;
4154   offset.SwizzleX = in_offset->SwizzleX;
4155   offset.SwizzleY = in_offset->SwizzleY;
4156   offset.SwizzleZ = in_offset->SwizzleZ;
4157
4158   return offset;
4159}
4160
4161static void
4162compile_tgsi_instruction(struct st_translate *t,
4163                         const glsl_to_tgsi_instruction *inst,
4164                         bool clamp_dst_color_output)
4165{
4166   struct ureg_program *ureg = t->ureg;
4167   GLuint i;
4168   struct ureg_dst dst[1];
4169   struct ureg_src src[4];
4170   struct tgsi_texture_offset texoffsets[MAX_GLSL_TEXTURE_OFFSET];
4171
4172   unsigned num_dst;
4173   unsigned num_src;
4174
4175   num_dst = num_inst_dst_regs(inst->op);
4176   num_src = num_inst_src_regs(inst->op);
4177
4178   if (num_dst)
4179      dst[0] = translate_dst(t,
4180                             &inst->dst,
4181                             inst->saturate,
4182                             clamp_dst_color_output);
4183
4184   for (i = 0; i < num_src; i++)
4185      src[i] = translate_src(t, &inst->src[i]);
4186
4187   switch(inst->op) {
4188   case TGSI_OPCODE_BGNLOOP:
4189   case TGSI_OPCODE_CAL:
4190   case TGSI_OPCODE_ELSE:
4191   case TGSI_OPCODE_ENDLOOP:
4192   case TGSI_OPCODE_IF:
4193      assert(num_dst == 0);
4194      ureg_label_insn(ureg,
4195                      inst->op,
4196                      src, num_src,
4197                      get_label(t,
4198                                inst->op == TGSI_OPCODE_CAL ? inst->function->sig_id : 0));
4199      return;
4200
4201   case TGSI_OPCODE_TEX:
4202   case TGSI_OPCODE_TXB:
4203   case TGSI_OPCODE_TXD:
4204   case TGSI_OPCODE_TXL:
4205   case TGSI_OPCODE_TXP:
4206   case TGSI_OPCODE_TXQ:
4207   case TGSI_OPCODE_TXF:
4208      src[num_src++] = t->samplers[inst->sampler];
4209      for (i = 0; i < inst->tex_offset_num_offset; i++) {
4210         texoffsets[i] = translate_tex_offset(t, &inst->tex_offsets[i]);
4211      }
4212      ureg_tex_insn(ureg,
4213                    inst->op,
4214                    dst, num_dst,
4215                    st_translate_texture_target(inst->tex_target, inst->tex_shadow),
4216                    texoffsets, inst->tex_offset_num_offset,
4217                    src, num_src);
4218      return;
4219
4220   case TGSI_OPCODE_SCS:
4221      dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY);
4222      ureg_insn(ureg, inst->op, dst, num_dst, src, num_src);
4223      break;
4224
4225   default:
4226      ureg_insn(ureg,
4227                inst->op,
4228                dst, num_dst,
4229                src, num_src);
4230      break;
4231   }
4232}
4233
4234/**
4235 * Emit the TGSI instructions for inverting and adjusting WPOS.
4236 * This code is unavoidable because it also depends on whether
4237 * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
4238 */
4239static void
4240emit_wpos_adjustment( struct st_translate *t,
4241                      const struct gl_program *program,
4242                      boolean invert,
4243                      GLfloat adjX, GLfloat adjY[2])
4244{
4245   struct ureg_program *ureg = t->ureg;
4246
4247   /* Fragment program uses fragment position input.
4248    * Need to replace instances of INPUT[WPOS] with temp T
4249    * where T = INPUT[WPOS] by y is inverted.
4250    */
4251   static const gl_state_index wposTransformState[STATE_LENGTH]
4252      = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM,
4253          (gl_state_index)0, (gl_state_index)0, (gl_state_index)0 };
4254
4255   /* XXX: note we are modifying the incoming shader here!  Need to
4256    * do this before emitting the constant decls below, or this
4257    * will be missed:
4258    */
4259   unsigned wposTransConst = _mesa_add_state_reference(program->Parameters,
4260                                                       wposTransformState);
4261
4262   struct ureg_src wpostrans = ureg_DECL_constant( ureg, wposTransConst );
4263   struct ureg_dst wpos_temp = ureg_DECL_temporary( ureg );
4264   struct ureg_src wpos_input = t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]];
4265
4266   /* First, apply the coordinate shift: */
4267   if (adjX || adjY[0] || adjY[1]) {
4268      if (adjY[0] != adjY[1]) {
4269         /* Adjust the y coordinate by adjY[1] or adjY[0] respectively
4270          * depending on whether inversion is actually going to be applied
4271          * or not, which is determined by testing against the inversion
4272          * state variable used below, which will be either +1 or -1.
4273          */
4274         struct ureg_dst adj_temp = ureg_DECL_local_temporary(ureg);
4275
4276         ureg_CMP(ureg, adj_temp,
4277                  ureg_scalar(wpostrans, invert ? 2 : 0),
4278                  ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f),
4279                  ureg_imm4f(ureg, adjX, adjY[1], 0.0f, 0.0f));
4280         ureg_ADD(ureg, wpos_temp, wpos_input, ureg_src(adj_temp));
4281      } else {
4282         ureg_ADD(ureg, wpos_temp, wpos_input,
4283                  ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f));
4284      }
4285      wpos_input = ureg_src(wpos_temp);
4286   } else {
4287      /* MOV wpos_temp, input[wpos]
4288       */
4289      ureg_MOV( ureg, wpos_temp, wpos_input );
4290   }
4291
4292   /* Now the conditional y flip: STATE_FB_WPOS_Y_TRANSFORM.xy/zw will be
4293    * inversion/identity, or the other way around if we're drawing to an FBO.
4294    */
4295   if (invert) {
4296      /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
4297       */
4298      ureg_MAD( ureg,
4299                ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
4300                wpos_input,
4301                ureg_scalar(wpostrans, 0),
4302                ureg_scalar(wpostrans, 1));
4303   } else {
4304      /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
4305       */
4306      ureg_MAD( ureg,
4307                ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
4308                wpos_input,
4309                ureg_scalar(wpostrans, 2),
4310                ureg_scalar(wpostrans, 3));
4311   }
4312
4313   /* Use wpos_temp as position input from here on:
4314    */
4315   t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]] = ureg_src(wpos_temp);
4316}
4317
4318
4319/**
4320 * Emit fragment position/ooordinate code.
4321 */
4322static void
4323emit_wpos(struct st_context *st,
4324          struct st_translate *t,
4325          const struct gl_program *program,
4326          struct ureg_program *ureg)
4327{
4328   const struct gl_fragment_program *fp =
4329      (const struct gl_fragment_program *) program;
4330   struct pipe_screen *pscreen = st->pipe->screen;
4331   GLfloat adjX = 0.0f;
4332   GLfloat adjY[2] = { 0.0f, 0.0f };
4333   boolean invert = FALSE;
4334
4335   /* Query the pixel center conventions supported by the pipe driver and set
4336    * adjX, adjY to help out if it cannot handle the requested one internally.
4337    *
4338    * The bias of the y-coordinate depends on whether y-inversion takes place
4339    * (adjY[1]) or not (adjY[0]), which is in turn dependent on whether we are
4340    * drawing to an FBO (causes additional inversion), and whether the the pipe
4341    * driver origin and the requested origin differ (the latter condition is
4342    * stored in the 'invert' variable).
4343    *
4344    * For height = 100 (i = integer, h = half-integer, l = lower, u = upper):
4345    *
4346    * center shift only:
4347    * i -> h: +0.5
4348    * h -> i: -0.5
4349    *
4350    * inversion only:
4351    * l,i -> u,i: ( 0.0 + 1.0) * -1 + 100 = 99
4352    * l,h -> u,h: ( 0.5 + 0.0) * -1 + 100 = 99.5
4353    * u,i -> l,i: (99.0 + 1.0) * -1 + 100 = 0
4354    * u,h -> l,h: (99.5 + 0.0) * -1 + 100 = 0.5
4355    *
4356    * inversion and center shift:
4357    * l,i -> u,h: ( 0.0 + 0.5) * -1 + 100 = 99.5
4358    * l,h -> u,i: ( 0.5 + 0.5) * -1 + 100 = 99
4359    * u,i -> l,h: (99.0 + 0.5) * -1 + 100 = 0.5
4360    * u,h -> l,i: (99.5 + 0.5) * -1 + 100 = 0
4361    */
4362   if (fp->OriginUpperLeft) {
4363      /* Fragment shader wants origin in upper-left */
4364      if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
4365         /* the driver supports upper-left origin */
4366      }
4367      else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
4368         /* the driver supports lower-left origin, need to invert Y */
4369         ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
4370         invert = TRUE;
4371      }
4372      else
4373         assert(0);
4374   }
4375   else {
4376      /* Fragment shader wants origin in lower-left */
4377      if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
4378         /* the driver supports lower-left origin */
4379         ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
4380      else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
4381         /* the driver supports upper-left origin, need to invert Y */
4382         invert = TRUE;
4383      else
4384         assert(0);
4385   }
4386
4387   if (fp->PixelCenterInteger) {
4388      /* Fragment shader wants pixel center integer */
4389      if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
4390         /* the driver supports pixel center integer */
4391         adjY[1] = 1.0f;
4392         ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
4393      }
4394      else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
4395         /* the driver supports pixel center half integer, need to bias X,Y */
4396         adjX = -0.5f;
4397         adjY[0] = -0.5f;
4398         adjY[1] = 0.5f;
4399      }
4400      else
4401         assert(0);
4402   }
4403   else {
4404      /* Fragment shader wants pixel center half integer */
4405      if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
4406         /* the driver supports pixel center half integer */
4407      }
4408      else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
4409         /* the driver supports pixel center integer, need to bias X,Y */
4410         adjX = adjY[0] = adjY[1] = 0.5f;
4411         ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
4412      }
4413      else
4414         assert(0);
4415   }
4416
4417   /* we invert after adjustment so that we avoid the MOV to temporary,
4418    * and reuse the adjustment ADD instead */
4419   emit_wpos_adjustment(t, program, invert, adjX, adjY);
4420}
4421
4422/**
4423 * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
4424 * TGSI uses +1 for front, -1 for back.
4425 * This function converts the TGSI value to the GL value.  Simply clamping/
4426 * saturating the value to [0,1] does the job.
4427 */
4428static void
4429emit_face_var(struct st_translate *t)
4430{
4431   struct ureg_program *ureg = t->ureg;
4432   struct ureg_dst face_temp = ureg_DECL_temporary(ureg);
4433   struct ureg_src face_input = t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]];
4434
4435   /* MOV_SAT face_temp, input[face] */
4436   face_temp = ureg_saturate(face_temp);
4437   ureg_MOV(ureg, face_temp, face_input);
4438
4439   /* Use face_temp as face input from here on: */
4440   t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]] = ureg_src(face_temp);
4441}
4442
4443static void
4444emit_edgeflags(struct st_translate *t)
4445{
4446   struct ureg_program *ureg = t->ureg;
4447   struct ureg_dst edge_dst = t->outputs[t->outputMapping[VERT_RESULT_EDGE]];
4448   struct ureg_src edge_src = t->inputs[t->inputMapping[VERT_ATTRIB_EDGEFLAG]];
4449
4450   ureg_MOV(ureg, edge_dst, edge_src);
4451}
4452
4453/**
4454 * Translate intermediate IR (glsl_to_tgsi_instruction) to TGSI format.
4455 * \param program  the program to translate
4456 * \param numInputs  number of input registers used
4457 * \param inputMapping  maps Mesa fragment program inputs to TGSI generic
4458 *                      input indexes
4459 * \param inputSemanticName  the TGSI_SEMANTIC flag for each input
4460 * \param inputSemanticIndex  the semantic index (ex: which texcoord) for
4461 *                            each input
4462 * \param interpMode  the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
4463 * \param numOutputs  number of output registers used
4464 * \param outputMapping  maps Mesa fragment program outputs to TGSI
4465 *                       generic outputs
4466 * \param outputSemanticName  the TGSI_SEMANTIC flag for each output
4467 * \param outputSemanticIndex  the semantic index (ex: which texcoord) for
4468 *                             each output
4469 *
4470 * \return  PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
4471 */
4472extern "C" enum pipe_error
4473st_translate_program(
4474   struct gl_context *ctx,
4475   uint procType,
4476   struct ureg_program *ureg,
4477   glsl_to_tgsi_visitor *program,
4478   const struct gl_program *proginfo,
4479   GLuint numInputs,
4480   const GLuint inputMapping[],
4481   const ubyte inputSemanticName[],
4482   const ubyte inputSemanticIndex[],
4483   const GLuint interpMode[],
4484   GLuint numOutputs,
4485   const GLuint outputMapping[],
4486   const ubyte outputSemanticName[],
4487   const ubyte outputSemanticIndex[],
4488   boolean passthrough_edgeflags,
4489   boolean clamp_color)
4490{
4491   struct st_translate *t;
4492   unsigned i;
4493   enum pipe_error ret = PIPE_OK;
4494
4495   assert(numInputs <= Elements(t->inputs));
4496   assert(numOutputs <= Elements(t->outputs));
4497
4498   t = CALLOC_STRUCT(st_translate);
4499   if (!t) {
4500      ret = PIPE_ERROR_OUT_OF_MEMORY;
4501      goto out;
4502   }
4503
4504   memset(t, 0, sizeof *t);
4505
4506   t->procType = procType;
4507   t->inputMapping = inputMapping;
4508   t->outputMapping = outputMapping;
4509   t->ureg = ureg;
4510
4511   if (program->shader_program) {
4512      for (i = 0; i < program->shader_program->NumUserUniformStorage; i++) {
4513         struct gl_uniform_storage *const storage =
4514               &program->shader_program->UniformStorage[i];
4515
4516         _mesa_uniform_detach_all_driver_storage(storage);
4517      }
4518   }
4519
4520   /*
4521    * Declare input attributes.
4522    */
4523   if (procType == TGSI_PROCESSOR_FRAGMENT) {
4524      for (i = 0; i < numInputs; i++) {
4525         t->inputs[i] = ureg_DECL_fs_input(ureg,
4526                                           inputSemanticName[i],
4527                                           inputSemanticIndex[i],
4528                                           interpMode[i]);
4529      }
4530
4531      if (proginfo->InputsRead & FRAG_BIT_WPOS) {
4532         /* Must do this after setting up t->inputs, and before
4533          * emitting constant references, below:
4534          */
4535          emit_wpos(st_context(ctx), t, proginfo, ureg);
4536      }
4537
4538      if (proginfo->InputsRead & FRAG_BIT_FACE)
4539         emit_face_var(t);
4540
4541      /*
4542       * Declare output attributes.
4543       */
4544      for (i = 0; i < numOutputs; i++) {
4545         switch (outputSemanticName[i]) {
4546         case TGSI_SEMANTIC_POSITION:
4547            t->outputs[i] = ureg_DECL_output(ureg,
4548                                             TGSI_SEMANTIC_POSITION, /* Z/Depth */
4549                                             outputSemanticIndex[i]);
4550            t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Z);
4551            break;
4552         case TGSI_SEMANTIC_STENCIL:
4553            t->outputs[i] = ureg_DECL_output(ureg,
4554                                             TGSI_SEMANTIC_STENCIL, /* Stencil */
4555                                             outputSemanticIndex[i]);
4556            t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Y);
4557            break;
4558         case TGSI_SEMANTIC_COLOR:
4559            t->outputs[i] = ureg_DECL_output(ureg,
4560                                             TGSI_SEMANTIC_COLOR,
4561                                             outputSemanticIndex[i]);
4562            break;
4563         default:
4564            assert(!"fragment shader outputs must be POSITION/STENCIL/COLOR");
4565            ret = PIPE_ERROR_BAD_INPUT;
4566            goto out;
4567         }
4568      }
4569   }
4570   else if (procType == TGSI_PROCESSOR_GEOMETRY) {
4571      for (i = 0; i < numInputs; i++) {
4572         t->inputs[i] = ureg_DECL_gs_input(ureg,
4573                                           i,
4574                                           inputSemanticName[i],
4575                                           inputSemanticIndex[i]);
4576      }
4577
4578      for (i = 0; i < numOutputs; i++) {
4579         t->outputs[i] = ureg_DECL_output(ureg,
4580                                          outputSemanticName[i],
4581                                          outputSemanticIndex[i]);
4582      }
4583   }
4584   else {
4585      assert(procType == TGSI_PROCESSOR_VERTEX);
4586
4587      for (i = 0; i < numInputs; i++) {
4588         t->inputs[i] = ureg_DECL_vs_input(ureg, i);
4589      }
4590
4591      for (i = 0; i < numOutputs; i++) {
4592         t->outputs[i] = ureg_DECL_output(ureg,
4593                                          outputSemanticName[i],
4594                                          outputSemanticIndex[i]);
4595      }
4596      if (passthrough_edgeflags)
4597         emit_edgeflags(t);
4598   }
4599
4600   /* Declare address register.
4601    */
4602   if (program->num_address_regs > 0) {
4603      assert(program->num_address_regs == 1);
4604      t->address[0] = ureg_DECL_address(ureg);
4605   }
4606
4607   /* Declare misc input registers
4608    */
4609   {
4610      GLbitfield sysInputs = proginfo->SystemValuesRead;
4611      unsigned numSys = 0;
4612      for (i = 0; sysInputs; i++) {
4613         if (sysInputs & (1 << i)) {
4614            unsigned semName = mesa_sysval_to_semantic[i];
4615            t->systemValues[i] = ureg_DECL_system_value(ureg, numSys, semName, 0);
4616            if (semName == TGSI_SEMANTIC_INSTANCEID ||
4617                semName == TGSI_SEMANTIC_VERTEXID) {
4618               /* From Gallium perspective, these system values are always
4619                * integer, and require native integer support.  However, if
4620                * native integer is supported on the vertex stage but not the
4621                * pixel stage (e.g, i915g + draw), Mesa will generate IR that
4622                * assumes these system values are floats. To resolve the
4623                * inconsistency, we insert a U2F.
4624                */
4625               struct st_context *st = st_context(ctx);
4626               struct pipe_screen *pscreen = st->pipe->screen;
4627               assert(procType == TGSI_PROCESSOR_VERTEX);
4628               assert(pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS));
4629               if (!ctx->Const.NativeIntegers) {
4630                  struct ureg_dst temp = ureg_DECL_local_temporary(t->ureg);
4631                  ureg_U2F( t->ureg, ureg_writemask(temp, TGSI_WRITEMASK_X), t->systemValues[i]);
4632                  t->systemValues[i] = ureg_scalar(ureg_src(temp), 0);
4633               }
4634            }
4635            numSys++;
4636            sysInputs &= ~(1 << i);
4637         }
4638      }
4639   }
4640
4641   if (program->indirect_addr_temps) {
4642      /* If temps are accessed with indirect addressing, declare temporaries
4643       * in sequential order.  Else, we declare them on demand elsewhere.
4644       * (Note: the number of temporaries is equal to program->next_temp)
4645       */
4646      for (i = 0; i < (unsigned)program->next_temp; i++) {
4647         /* XXX use TGSI_FILE_TEMPORARY_ARRAY when it's supported by ureg */
4648         t->temps[i] = ureg_DECL_local_temporary(t->ureg);
4649      }
4650   }
4651
4652   /* Emit constants and uniforms.  TGSI uses a single index space for these,
4653    * so we put all the translated regs in t->constants.
4654    */
4655   if (proginfo->Parameters) {
4656      t->constants = (struct ureg_src *)CALLOC(proginfo->Parameters->NumParameters * sizeof(t->constants[0]));
4657      if (t->constants == NULL) {
4658         ret = PIPE_ERROR_OUT_OF_MEMORY;
4659         goto out;
4660      }
4661
4662      for (i = 0; i < proginfo->Parameters->NumParameters; i++) {
4663         switch (proginfo->Parameters->Parameters[i].Type) {
4664         case PROGRAM_ENV_PARAM:
4665         case PROGRAM_LOCAL_PARAM:
4666         case PROGRAM_STATE_VAR:
4667         case PROGRAM_NAMED_PARAM:
4668         case PROGRAM_UNIFORM:
4669            t->constants[i] = ureg_DECL_constant(ureg, i);
4670            break;
4671
4672         /* Emit immediates for PROGRAM_CONSTANT only when there's no indirect
4673          * addressing of the const buffer.
4674          * FIXME: Be smarter and recognize param arrays:
4675          * indirect addressing is only valid within the referenced
4676          * array.
4677          */
4678         case PROGRAM_CONSTANT:
4679            if (program->indirect_addr_consts)
4680               t->constants[i] = ureg_DECL_constant(ureg, i);
4681            else
4682               t->constants[i] = emit_immediate(t,
4683                                                proginfo->Parameters->ParameterValues[i],
4684                                                proginfo->Parameters->Parameters[i].DataType,
4685                                                4);
4686            break;
4687         default:
4688            break;
4689         }
4690      }
4691   }
4692
4693   /* Emit immediate values.
4694    */
4695   t->immediates = (struct ureg_src *)CALLOC(program->num_immediates * sizeof(struct ureg_src));
4696   if (t->immediates == NULL) {
4697      ret = PIPE_ERROR_OUT_OF_MEMORY;
4698      goto out;
4699   }
4700   i = 0;
4701   foreach_iter(exec_list_iterator, iter, program->immediates) {
4702      immediate_storage *imm = (immediate_storage *)iter.get();
4703      assert(i < program->num_immediates);
4704      t->immediates[i++] = emit_immediate(t, imm->values, imm->type, imm->size);
4705   }
4706   assert(i == program->num_immediates);
4707
4708   /* texture samplers */
4709   for (i = 0; i < ctx->Const.MaxTextureImageUnits; i++) {
4710      if (program->samplers_used & (1 << i)) {
4711         t->samplers[i] = ureg_DECL_sampler(ureg, i);
4712      }
4713   }
4714
4715   /* Emit each instruction in turn:
4716    */
4717   foreach_iter(exec_list_iterator, iter, program->instructions) {
4718      set_insn_start(t, ureg_get_instruction_number(ureg));
4719      compile_tgsi_instruction(t, (glsl_to_tgsi_instruction *)iter.get(),
4720                               clamp_color);
4721   }
4722
4723   /* Fix up all emitted labels:
4724    */
4725   for (i = 0; i < t->labels_count; i++) {
4726      ureg_fixup_label(ureg, t->labels[i].token,
4727                       t->insn[t->labels[i].branch_target]);
4728   }
4729
4730   if (program->shader_program) {
4731      /* This has to be done last.  Any operation the can cause
4732       * prog->ParameterValues to get reallocated (e.g., anything that adds a
4733       * program constant) has to happen before creating this linkage.
4734       */
4735      for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
4736         if (program->shader_program->_LinkedShaders[i] == NULL)
4737            continue;
4738
4739         _mesa_associate_uniform_storage(ctx, program->shader_program,
4740               program->shader_program->_LinkedShaders[i]->Program->Parameters);
4741      }
4742   }
4743
4744out:
4745   if (t) {
4746      FREE(t->insn);
4747      FREE(t->labels);
4748      FREE(t->constants);
4749      FREE(t->immediates);
4750
4751      if (t->error) {
4752         debug_printf("%s: translate error flag set\n", __FUNCTION__);
4753      }
4754
4755      FREE(t);
4756   }
4757
4758   return ret;
4759}
4760/* ----------------------------- End TGSI code ------------------------------ */
4761
4762/**
4763 * Convert a shader's GLSL IR into a Mesa gl_program, although without
4764 * generating Mesa IR.
4765 */
4766static struct gl_program *
4767get_mesa_program(struct gl_context *ctx,
4768                 struct gl_shader_program *shader_program,
4769                 struct gl_shader *shader)
4770{
4771   glsl_to_tgsi_visitor* v = new glsl_to_tgsi_visitor();
4772   struct gl_program *prog;
4773   GLenum target;
4774   const char *target_string;
4775   bool progress;
4776   struct gl_shader_compiler_options *options =
4777         &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
4778
4779   switch (shader->Type) {
4780   case GL_VERTEX_SHADER:
4781      target = GL_VERTEX_PROGRAM_ARB;
4782      target_string = "vertex";
4783      break;
4784   case GL_FRAGMENT_SHADER:
4785      target = GL_FRAGMENT_PROGRAM_ARB;
4786      target_string = "fragment";
4787      break;
4788   case GL_GEOMETRY_SHADER:
4789      target = GL_GEOMETRY_PROGRAM_NV;
4790      target_string = "geometry";
4791      break;
4792   default:
4793      assert(!"should not be reached");
4794      return NULL;
4795   }
4796
4797   validate_ir_tree(shader->ir);
4798
4799   prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
4800   if (!prog)
4801      return NULL;
4802   prog->Parameters = _mesa_new_parameter_list();
4803   v->ctx = ctx;
4804   v->prog = prog;
4805   v->shader_program = shader_program;
4806   v->options = options;
4807   v->glsl_version = ctx->Const.GLSLVersion;
4808   v->native_integers = ctx->Const.NativeIntegers;
4809
4810   _mesa_generate_parameters_list_for_uniforms(shader_program, shader,
4811					       prog->Parameters);
4812
4813   /* Remove reads from output registers. */
4814   lower_output_reads(shader->ir);
4815
4816   /* Emit intermediate IR for main(). */
4817   visit_exec_list(shader->ir, v);
4818
4819   /* Now emit bodies for any functions that were used. */
4820   do {
4821      progress = GL_FALSE;
4822
4823      foreach_iter(exec_list_iterator, iter, v->function_signatures) {
4824         function_entry *entry = (function_entry *)iter.get();
4825
4826         if (!entry->bgn_inst) {
4827            v->current_function = entry;
4828
4829            entry->bgn_inst = v->emit(NULL, TGSI_OPCODE_BGNSUB);
4830            entry->bgn_inst->function = entry;
4831
4832            visit_exec_list(&entry->sig->body, v);
4833
4834            glsl_to_tgsi_instruction *last;
4835            last = (glsl_to_tgsi_instruction *)v->instructions.get_tail();
4836            if (last->op != TGSI_OPCODE_RET)
4837               v->emit(NULL, TGSI_OPCODE_RET);
4838
4839            glsl_to_tgsi_instruction *end;
4840            end = v->emit(NULL, TGSI_OPCODE_ENDSUB);
4841            end->function = entry;
4842
4843            progress = GL_TRUE;
4844         }
4845      }
4846   } while (progress);
4847
4848#if 0
4849   /* Print out some information (for debugging purposes) used by the
4850    * optimization passes. */
4851   for (i=0; i < v->next_temp; i++) {
4852      int fr = v->get_first_temp_read(i);
4853      int fw = v->get_first_temp_write(i);
4854      int lr = v->get_last_temp_read(i);
4855      int lw = v->get_last_temp_write(i);
4856
4857      printf("Temp %d: FR=%3d FW=%3d LR=%3d LW=%3d\n", i, fr, fw, lr, lw);
4858      assert(fw <= fr);
4859   }
4860#endif
4861
4862   /* Perform optimizations on the instructions in the glsl_to_tgsi_visitor. */
4863   v->simplify_cmp();
4864   v->copy_propagate();
4865   while (v->eliminate_dead_code_advanced());
4866
4867   /* FIXME: These passes to optimize temporary registers don't work when there
4868    * is indirect addressing of the temporary register space.  We need proper
4869    * array support so that we don't have to give up these passes in every
4870    * shader that uses arrays.
4871    */
4872   if (!v->indirect_addr_temps) {
4873      v->eliminate_dead_code();
4874      v->merge_registers();
4875      v->renumber_registers();
4876   }
4877
4878   /* Write the END instruction. */
4879   v->emit(NULL, TGSI_OPCODE_END);
4880
4881   if (ctx->Shader.Flags & GLSL_DUMP) {
4882      printf("\n");
4883      printf("GLSL IR for linked %s program %d:\n", target_string,
4884             shader_program->Name);
4885      _mesa_print_ir(shader->ir, NULL);
4886      printf("\n");
4887      printf("\n");
4888      fflush(stdout);
4889   }
4890
4891   prog->Instructions = NULL;
4892   prog->NumInstructions = 0;
4893
4894   do_set_program_inouts(shader->ir, prog, shader->Type == GL_FRAGMENT_SHADER);
4895   count_resources(v, prog);
4896
4897   _mesa_reference_program(ctx, &shader->Program, prog);
4898
4899   /* This has to be done last.  Any operation the can cause
4900    * prog->ParameterValues to get reallocated (e.g., anything that adds a
4901    * program constant) has to happen before creating this linkage.
4902    */
4903   _mesa_associate_uniform_storage(ctx, shader_program, prog->Parameters);
4904   if (!shader_program->LinkStatus) {
4905      return NULL;
4906   }
4907
4908   struct st_vertex_program *stvp;
4909   struct st_fragment_program *stfp;
4910   struct st_geometry_program *stgp;
4911
4912   switch (shader->Type) {
4913   case GL_VERTEX_SHADER:
4914      stvp = (struct st_vertex_program *)prog;
4915      stvp->glsl_to_tgsi = v;
4916      break;
4917   case GL_FRAGMENT_SHADER:
4918      stfp = (struct st_fragment_program *)prog;
4919      stfp->glsl_to_tgsi = v;
4920      break;
4921   case GL_GEOMETRY_SHADER:
4922      stgp = (struct st_geometry_program *)prog;
4923      stgp->glsl_to_tgsi = v;
4924      break;
4925   default:
4926      assert(!"should not be reached");
4927      return NULL;
4928   }
4929
4930   return prog;
4931}
4932
4933extern "C" {
4934
4935struct gl_shader *
4936st_new_shader(struct gl_context *ctx, GLuint name, GLuint type)
4937{
4938   struct gl_shader *shader;
4939   assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER ||
4940          type == GL_GEOMETRY_SHADER_ARB);
4941   shader = rzalloc(NULL, struct gl_shader);
4942   if (shader) {
4943      shader->Type = type;
4944      shader->Name = name;
4945      _mesa_init_shader(ctx, shader);
4946   }
4947   return shader;
4948}
4949
4950struct gl_shader_program *
4951st_new_shader_program(struct gl_context *ctx, GLuint name)
4952{
4953   struct gl_shader_program *shProg;
4954   shProg = rzalloc(NULL, struct gl_shader_program);
4955   if (shProg) {
4956      shProg->Name = name;
4957      _mesa_init_shader_program(ctx, shProg);
4958   }
4959   return shProg;
4960}
4961
4962/**
4963 * Link a shader.
4964 * Called via ctx->Driver.LinkShader()
4965 * This actually involves converting GLSL IR into an intermediate TGSI-like IR
4966 * with code lowering and other optimizations.
4967 */
4968GLboolean
4969st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
4970{
4971   assert(prog->LinkStatus);
4972
4973   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
4974      if (prog->_LinkedShaders[i] == NULL)
4975         continue;
4976
4977      bool progress;
4978      exec_list *ir = prog->_LinkedShaders[i]->ir;
4979      const struct gl_shader_compiler_options *options =
4980            &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
4981
4982      do {
4983         unsigned what_to_lower = MOD_TO_FRACT | DIV_TO_MUL_RCP |
4984            EXP_TO_EXP2 | LOG_TO_LOG2;
4985         if (options->EmitNoPow)
4986            what_to_lower |= POW_TO_EXP2;
4987         if (!ctx->Const.NativeIntegers)
4988            what_to_lower |= INT_DIV_TO_MUL_RCP;
4989
4990         progress = false;
4991
4992         /* Lowering */
4993         do_mat_op_to_vec(ir);
4994         lower_instructions(ir, what_to_lower);
4995
4996         progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
4997
4998         progress = do_common_optimization(ir, true, true,
4999					   options->MaxUnrollIterations)
5000	   || progress;
5001
5002         progress = lower_quadop_vector(ir, false) || progress;
5003
5004         if (options->MaxIfDepth == 0)
5005            progress = lower_discard(ir) || progress;
5006
5007         progress = lower_if_to_cond_assign(ir, options->MaxIfDepth) || progress;
5008
5009         if (options->EmitNoNoise)
5010            progress = lower_noise(ir) || progress;
5011
5012         /* If there are forms of indirect addressing that the driver
5013          * cannot handle, perform the lowering pass.
5014          */
5015         if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
5016             || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
5017           progress =
5018             lower_variable_index_to_cond_assign(ir,
5019        					 options->EmitNoIndirectInput,
5020        					 options->EmitNoIndirectOutput,
5021        					 options->EmitNoIndirectTemp,
5022        					 options->EmitNoIndirectUniform)
5023             || progress;
5024
5025         progress = do_vec_index_to_cond_assign(ir) || progress;
5026      } while (progress);
5027
5028      validate_ir_tree(ir);
5029   }
5030
5031   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
5032      struct gl_program *linked_prog;
5033
5034      if (prog->_LinkedShaders[i] == NULL)
5035         continue;
5036
5037      linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
5038
5039      if (linked_prog) {
5040	 static const GLenum targets[] = {
5041	    GL_VERTEX_PROGRAM_ARB,
5042	    GL_FRAGMENT_PROGRAM_ARB,
5043	    GL_GEOMETRY_PROGRAM_NV
5044	 };
5045
5046	 _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
5047				 linked_prog);
5048         if (!ctx->Driver.ProgramStringNotify(ctx, targets[i], linked_prog)) {
5049	    _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
5050				    NULL);
5051            _mesa_reference_program(ctx, &linked_prog, NULL);
5052            return GL_FALSE;
5053         }
5054      }
5055
5056      _mesa_reference_program(ctx, &linked_prog, NULL);
5057   }
5058
5059   return GL_TRUE;
5060}
5061
5062void
5063st_translate_stream_output_info(glsl_to_tgsi_visitor *glsl_to_tgsi,
5064                                const GLuint outputMapping[],
5065                                struct pipe_stream_output_info *so)
5066{
5067   unsigned i;
5068   struct gl_transform_feedback_info *info =
5069      &glsl_to_tgsi->shader_program->LinkedTransformFeedback;
5070
5071   for (i = 0; i < info->NumOutputs; i++) {
5072      so->output[i].register_index =
5073         outputMapping[info->Outputs[i].OutputRegister];
5074      so->output[i].start_component = info->Outputs[i].ComponentOffset;
5075      so->output[i].num_components = info->Outputs[i].NumComponents;
5076      so->output[i].output_buffer = info->Outputs[i].OutputBuffer;
5077      so->output[i].dst_offset = info->Outputs[i].DstOffset;
5078   }
5079
5080   for (i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
5081      so->stride[i] = info->BufferStride[i];
5082   }
5083   so->num_outputs = info->NumOutputs;
5084}
5085
5086} /* extern "C" */
5087