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