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