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