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