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