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