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