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