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