mesa: move _mesa_valid_to_render() to api_validate.c
[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 "st_glsl_to_tgsi.h"
34
35 #include "compiler/glsl/glsl_parser_extras.h"
36 #include "compiler/glsl/ir_optimization.h"
37 #include "compiler/glsl/program.h"
38
39 #include "main/errors.h"
40 #include "main/shaderobj.h"
41 #include "main/uniforms.h"
42 #include "main/shaderapi.h"
43 #include "main/shaderimage.h"
44 #include "program/prog_instruction.h"
45
46 #include "pipe/p_context.h"
47 #include "pipe/p_screen.h"
48 #include "tgsi/tgsi_ureg.h"
49 #include "tgsi/tgsi_info.h"
50 #include "util/u_math.h"
51 #include "util/u_memory.h"
52 #include "st_program.h"
53 #include "st_mesa_to_tgsi.h"
54 #include "st_format.h"
55 #include "st_glsl_types.h"
56 #include "st_nir.h"
57
58
59 #define PROGRAM_ANY_CONST ((1 << PROGRAM_STATE_VAR) | \
60 (1 << PROGRAM_CONSTANT) | \
61 (1 << PROGRAM_UNIFORM))
62
63 #define MAX_GLSL_TEXTURE_OFFSET 4
64
65 class st_src_reg;
66 class st_dst_reg;
67
68 static int swizzle_for_size(int size);
69
70 /**
71 * This struct is a corresponding struct to TGSI ureg_src.
72 */
73 class st_src_reg {
74 public:
75 st_src_reg(gl_register_file file, int index, const glsl_type *type)
76 {
77 this->file = file;
78 this->index = index;
79 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
80 this->swizzle = swizzle_for_size(type->vector_elements);
81 else
82 this->swizzle = SWIZZLE_XYZW;
83 this->negate = 0;
84 this->index2D = 0;
85 this->type = type ? type->base_type : GLSL_TYPE_ERROR;
86 this->reladdr = NULL;
87 this->reladdr2 = NULL;
88 this->has_index2 = false;
89 this->double_reg2 = false;
90 this->array_id = 0;
91 this->is_double_vertex_input = false;
92 }
93
94 st_src_reg(gl_register_file file, int index, enum glsl_base_type type)
95 {
96 this->type = type;
97 this->file = file;
98 this->index = index;
99 this->index2D = 0;
100 this->swizzle = SWIZZLE_XYZW;
101 this->negate = 0;
102 this->reladdr = NULL;
103 this->reladdr2 = NULL;
104 this->has_index2 = false;
105 this->double_reg2 = false;
106 this->array_id = 0;
107 this->is_double_vertex_input = false;
108 }
109
110 st_src_reg(gl_register_file file, int index, enum glsl_base_type type, int index2D)
111 {
112 this->type = type;
113 this->file = file;
114 this->index = index;
115 this->index2D = index2D;
116 this->swizzle = SWIZZLE_XYZW;
117 this->negate = 0;
118 this->reladdr = NULL;
119 this->reladdr2 = NULL;
120 this->has_index2 = false;
121 this->double_reg2 = false;
122 this->array_id = 0;
123 this->is_double_vertex_input = false;
124 }
125
126 st_src_reg()
127 {
128 this->type = GLSL_TYPE_ERROR;
129 this->file = PROGRAM_UNDEFINED;
130 this->index = 0;
131 this->index2D = 0;
132 this->swizzle = 0;
133 this->negate = 0;
134 this->reladdr = NULL;
135 this->reladdr2 = NULL;
136 this->has_index2 = false;
137 this->double_reg2 = false;
138 this->array_id = 0;
139 this->is_double_vertex_input = false;
140 }
141
142 explicit st_src_reg(st_dst_reg reg);
143
144 gl_register_file file; /**< PROGRAM_* from Mesa */
145 int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
146 int index2D;
147 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
148 int negate; /**< NEGATE_XYZW mask from mesa */
149 enum glsl_base_type type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
150 /** Register index should be offset by the integer in this reg. */
151 st_src_reg *reladdr;
152 st_src_reg *reladdr2;
153 bool has_index2;
154 /*
155 * Is this the second half of a double register pair?
156 * currently used for input mapping only.
157 */
158 bool double_reg2;
159 unsigned array_id;
160 bool is_double_vertex_input;
161 };
162
163 class st_dst_reg {
164 public:
165 st_dst_reg(gl_register_file file, int writemask, enum glsl_base_type type, int index)
166 {
167 this->file = file;
168 this->index = index;
169 this->index2D = 0;
170 this->writemask = writemask;
171 this->reladdr = NULL;
172 this->reladdr2 = NULL;
173 this->has_index2 = false;
174 this->type = type;
175 this->array_id = 0;
176 }
177
178 st_dst_reg(gl_register_file file, int writemask, enum glsl_base_type type)
179 {
180 this->file = file;
181 this->index = 0;
182 this->index2D = 0;
183 this->writemask = writemask;
184 this->reladdr = NULL;
185 this->reladdr2 = NULL;
186 this->has_index2 = false;
187 this->type = type;
188 this->array_id = 0;
189 }
190
191 st_dst_reg()
192 {
193 this->type = GLSL_TYPE_ERROR;
194 this->file = PROGRAM_UNDEFINED;
195 this->index = 0;
196 this->index2D = 0;
197 this->writemask = 0;
198 this->reladdr = NULL;
199 this->reladdr2 = NULL;
200 this->has_index2 = false;
201 this->array_id = 0;
202 }
203
204 explicit st_dst_reg(st_src_reg reg);
205
206 gl_register_file file; /**< PROGRAM_* from Mesa */
207 int index; /**< temporary index, VERT_ATTRIB_*, VARYING_SLOT_*, etc. */
208 int index2D;
209 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
210 enum glsl_base_type type; /** GLSL_TYPE_* from GLSL IR (enum glsl_base_type) */
211 /** Register index should be offset by the integer in this reg. */
212 st_src_reg *reladdr;
213 st_src_reg *reladdr2;
214 bool has_index2;
215 unsigned array_id;
216 };
217
218 st_src_reg::st_src_reg(st_dst_reg reg)
219 {
220 this->type = reg.type;
221 this->file = reg.file;
222 this->index = reg.index;
223 this->swizzle = SWIZZLE_XYZW;
224 this->negate = 0;
225 this->reladdr = reg.reladdr;
226 this->index2D = reg.index2D;
227 this->reladdr2 = reg.reladdr2;
228 this->has_index2 = reg.has_index2;
229 this->double_reg2 = false;
230 this->array_id = reg.array_id;
231 this->is_double_vertex_input = false;
232 }
233
234 st_dst_reg::st_dst_reg(st_src_reg reg)
235 {
236 this->type = reg.type;
237 this->file = reg.file;
238 this->index = reg.index;
239 this->writemask = WRITEMASK_XYZW;
240 this->reladdr = reg.reladdr;
241 this->index2D = reg.index2D;
242 this->reladdr2 = reg.reladdr2;
243 this->has_index2 = reg.has_index2;
244 this->array_id = reg.array_id;
245 }
246
247 class glsl_to_tgsi_instruction : public exec_node {
248 public:
249 DECLARE_RALLOC_CXX_OPERATORS(glsl_to_tgsi_instruction)
250
251 unsigned op;
252 st_dst_reg dst[2];
253 st_src_reg src[4];
254 /** Pointer to the ir source this tree came from for debugging */
255 ir_instruction *ir;
256 GLboolean cond_update;
257 bool saturate;
258 st_src_reg sampler; /**< sampler register */
259 int sampler_base;
260 int sampler_array_size; /**< 1-based size of sampler array, 1 if not array */
261 int tex_target; /**< One of TEXTURE_*_INDEX */
262 glsl_base_type tex_type;
263 GLboolean tex_shadow;
264 unsigned image_format;
265
266 st_src_reg tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
267 unsigned tex_offset_num_offset;
268 int dead_mask; /**< Used in dead code elimination */
269
270 st_src_reg buffer; /**< buffer register */
271 unsigned buffer_access; /**< buffer access type */
272
273 class function_entry *function; /* Set on TGSI_OPCODE_CAL or TGSI_OPCODE_BGNSUB */
274 const struct tgsi_opcode_info *info;
275 };
276
277 class variable_storage : public exec_node {
278 public:
279 variable_storage(ir_variable *var, gl_register_file file, int index,
280 unsigned array_id = 0)
281 : file(file), index(index), var(var), array_id(array_id)
282 {
283 /* empty */
284 }
285
286 gl_register_file file;
287 int index;
288 ir_variable *var; /* variable that maps to this, if any */
289 unsigned array_id;
290 };
291
292 class immediate_storage : public exec_node {
293 public:
294 immediate_storage(gl_constant_value *values, int size32, int type)
295 {
296 memcpy(this->values, values, size32 * sizeof(gl_constant_value));
297 this->size32 = size32;
298 this->type = type;
299 }
300
301 /* doubles are stored across 2 gl_constant_values */
302 gl_constant_value values[4];
303 int size32; /**< Number of 32-bit components (1-4) */
304 int type; /**< GL_DOUBLE, GL_FLOAT, GL_INT, GL_BOOL, or GL_UNSIGNED_INT */
305 };
306
307 class function_entry : public exec_node {
308 public:
309 ir_function_signature *sig;
310
311 /**
312 * identifier of this function signature used by the program.
313 *
314 * At the point that TGSI instructions for function calls are
315 * generated, we don't know the address of the first instruction of
316 * the function body. So we make the BranchTarget that is called a
317 * small integer and rewrite them during set_branchtargets().
318 */
319 int sig_id;
320
321 /**
322 * Pointer to first instruction of the function body.
323 *
324 * Set during function body emits after main() is processed.
325 */
326 glsl_to_tgsi_instruction *bgn_inst;
327
328 /**
329 * Index of the first instruction of the function body in actual TGSI.
330 *
331 * Set after conversion from glsl_to_tgsi_instruction to TGSI.
332 */
333 int inst;
334
335 /** Storage for the return value. */
336 st_src_reg return_reg;
337 };
338
339 static st_src_reg undef_src = st_src_reg(PROGRAM_UNDEFINED, 0, GLSL_TYPE_ERROR);
340 static st_dst_reg undef_dst = st_dst_reg(PROGRAM_UNDEFINED, SWIZZLE_NOOP, GLSL_TYPE_ERROR);
341
342 struct array_decl {
343 unsigned mesa_index;
344 unsigned array_id;
345 unsigned array_size;
346 enum glsl_base_type array_type;
347 };
348
349 static enum glsl_base_type
350 find_array_type(struct array_decl *arrays, unsigned count, unsigned array_id)
351 {
352 unsigned i;
353
354 for (i = 0; i < count; i++) {
355 struct array_decl *decl = &arrays[i];
356
357 if (array_id == decl->array_id) {
358 return decl->array_type;
359 }
360 }
361 return GLSL_TYPE_ERROR;
362 }
363
364 struct rename_reg_pair {
365 int old_reg;
366 int new_reg;
367 };
368
369 struct glsl_to_tgsi_visitor : public ir_visitor {
370 public:
371 glsl_to_tgsi_visitor();
372 ~glsl_to_tgsi_visitor();
373
374 function_entry *current_function;
375
376 struct gl_context *ctx;
377 struct gl_program *prog;
378 struct gl_shader_program *shader_program;
379 struct gl_linked_shader *shader;
380 struct gl_shader_compiler_options *options;
381
382 int next_temp;
383
384 unsigned *array_sizes;
385 unsigned max_num_arrays;
386 unsigned next_array;
387
388 struct array_decl input_arrays[PIPE_MAX_SHADER_INPUTS];
389 unsigned num_input_arrays;
390 struct array_decl output_arrays[PIPE_MAX_SHADER_OUTPUTS];
391 unsigned num_output_arrays;
392
393 int num_address_regs;
394 uint32_t samplers_used;
395 glsl_base_type sampler_types[PIPE_MAX_SAMPLERS];
396 int sampler_targets[PIPE_MAX_SAMPLERS]; /**< One of TGSI_TEXTURE_* */
397 int buffers_used;
398 int images_used;
399 int image_targets[PIPE_MAX_SHADER_IMAGES];
400 unsigned image_formats[PIPE_MAX_SHADER_IMAGES];
401 bool indirect_addr_consts;
402 int wpos_transform_const;
403
404 int glsl_version;
405 bool native_integers;
406 bool have_sqrt;
407 bool have_fma;
408 bool use_shared_memory;
409
410 variable_storage *find_variable_storage(ir_variable *var);
411
412 int add_constant(gl_register_file file, gl_constant_value values[8],
413 int size, int datatype, GLuint *swizzle_out);
414
415 function_entry *get_function_signature(ir_function_signature *sig);
416
417 st_src_reg get_temp(const glsl_type *type);
418 void reladdr_to_temp(ir_instruction *ir, st_src_reg *reg, int *num_reladdr);
419
420 st_src_reg st_src_reg_for_double(double val);
421 st_src_reg st_src_reg_for_float(float val);
422 st_src_reg st_src_reg_for_int(int val);
423 st_src_reg st_src_reg_for_type(enum glsl_base_type type, int val);
424
425 /**
426 * \name Visit methods
427 *
428 * As typical for the visitor pattern, there must be one \c visit method for
429 * each concrete subclass of \c ir_instruction. Virtual base classes within
430 * the hierarchy should not have \c visit methods.
431 */
432 /*@{*/
433 virtual void visit(ir_variable *);
434 virtual void visit(ir_loop *);
435 virtual void visit(ir_loop_jump *);
436 virtual void visit(ir_function_signature *);
437 virtual void visit(ir_function *);
438 virtual void visit(ir_expression *);
439 virtual void visit(ir_swizzle *);
440 virtual void visit(ir_dereference_variable *);
441 virtual void visit(ir_dereference_array *);
442 virtual void visit(ir_dereference_record *);
443 virtual void visit(ir_assignment *);
444 virtual void visit(ir_constant *);
445 virtual void visit(ir_call *);
446 virtual void visit(ir_return *);
447 virtual void visit(ir_discard *);
448 virtual void visit(ir_texture *);
449 virtual void visit(ir_if *);
450 virtual void visit(ir_emit_vertex *);
451 virtual void visit(ir_end_primitive *);
452 virtual void visit(ir_barrier *);
453 /*@}*/
454
455 void visit_expression(ir_expression *, st_src_reg *) ATTRIBUTE_NOINLINE;
456
457 void visit_atomic_counter_intrinsic(ir_call *);
458 void visit_ssbo_intrinsic(ir_call *);
459 void visit_membar_intrinsic(ir_call *);
460 void visit_shared_intrinsic(ir_call *);
461 void visit_image_intrinsic(ir_call *);
462
463 st_src_reg result;
464
465 /** List of variable_storage */
466 exec_list variables;
467
468 /** List of immediate_storage */
469 exec_list immediates;
470 unsigned num_immediates;
471
472 /** List of function_entry */
473 exec_list function_signatures;
474 int next_signature_id;
475
476 /** List of glsl_to_tgsi_instruction */
477 exec_list instructions;
478
479 glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, unsigned op,
480 st_dst_reg dst = undef_dst,
481 st_src_reg src0 = undef_src,
482 st_src_reg src1 = undef_src,
483 st_src_reg src2 = undef_src,
484 st_src_reg src3 = undef_src);
485
486 glsl_to_tgsi_instruction *emit_asm(ir_instruction *ir, unsigned op,
487 st_dst_reg dst, st_dst_reg dst1,
488 st_src_reg src0 = undef_src,
489 st_src_reg src1 = undef_src,
490 st_src_reg src2 = undef_src,
491 st_src_reg src3 = undef_src);
492
493 unsigned get_opcode(ir_instruction *ir, unsigned op,
494 st_dst_reg dst,
495 st_src_reg src0, st_src_reg src1);
496
497 /**
498 * Emit the correct dot-product instruction for the type of arguments
499 */
500 glsl_to_tgsi_instruction *emit_dp(ir_instruction *ir,
501 st_dst_reg dst,
502 st_src_reg src0,
503 st_src_reg src1,
504 unsigned elements);
505
506 void emit_scalar(ir_instruction *ir, unsigned op,
507 st_dst_reg dst, st_src_reg src0);
508
509 void emit_scalar(ir_instruction *ir, unsigned op,
510 st_dst_reg dst, st_src_reg src0, st_src_reg src1);
511
512 void emit_arl(ir_instruction *ir, st_dst_reg dst, st_src_reg src0);
513
514 void get_deref_offsets(ir_dereference *ir,
515 unsigned *array_size,
516 unsigned *base,
517 unsigned *index,
518 st_src_reg *reladdr);
519 void calc_deref_offsets(ir_dereference *head,
520 ir_dereference *tail,
521 unsigned *array_elements,
522 unsigned *base,
523 unsigned *index,
524 st_src_reg *indirect,
525 unsigned *location);
526
527 bool try_emit_mad(ir_expression *ir,
528 int mul_operand);
529 bool try_emit_mad_for_and_not(ir_expression *ir,
530 int mul_operand);
531
532 void emit_swz(ir_expression *ir);
533
534 bool process_move_condition(ir_rvalue *ir);
535
536 void simplify_cmp(void);
537
538 void rename_temp_registers(int num_renames, struct rename_reg_pair *renames);
539 void get_first_temp_read(int *first_reads);
540 void get_last_temp_read_first_temp_write(int *last_reads, int *first_writes);
541 void get_last_temp_write(int *last_writes);
542
543 void copy_propagate(void);
544 int eliminate_dead_code(void);
545
546 void merge_two_dsts(void);
547 void merge_registers(void);
548 void renumber_registers(void);
549
550 void emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
551 st_dst_reg *l, st_src_reg *r,
552 st_src_reg *cond, bool cond_swap);
553
554 void *mem_ctx;
555 };
556
557 static st_dst_reg address_reg = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 0);
558 static st_dst_reg address_reg2 = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 1);
559 static st_dst_reg sampler_reladdr = st_dst_reg(PROGRAM_ADDRESS, WRITEMASK_X, GLSL_TYPE_FLOAT, 2);
560
561 static void
562 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
563
564 static void
565 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
566 {
567 va_list args;
568 va_start(args, fmt);
569 ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
570 va_end(args);
571
572 prog->LinkStatus = GL_FALSE;
573 }
574
575 static int
576 swizzle_for_size(int size)
577 {
578 static const int size_swizzles[4] = {
579 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
580 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
581 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
582 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
583 };
584
585 assert((size >= 1) && (size <= 4));
586 return size_swizzles[size - 1];
587 }
588
589 static bool
590 is_resource_instruction(unsigned opcode)
591 {
592 switch (opcode) {
593 case TGSI_OPCODE_RESQ:
594 case TGSI_OPCODE_LOAD:
595 case TGSI_OPCODE_ATOMUADD:
596 case TGSI_OPCODE_ATOMXCHG:
597 case TGSI_OPCODE_ATOMCAS:
598 case TGSI_OPCODE_ATOMAND:
599 case TGSI_OPCODE_ATOMOR:
600 case TGSI_OPCODE_ATOMXOR:
601 case TGSI_OPCODE_ATOMUMIN:
602 case TGSI_OPCODE_ATOMUMAX:
603 case TGSI_OPCODE_ATOMIMIN:
604 case TGSI_OPCODE_ATOMIMAX:
605 return true;
606 default:
607 return false;
608 }
609 }
610
611 static unsigned
612 num_inst_dst_regs(const glsl_to_tgsi_instruction *op)
613 {
614 return op->info->num_dst;
615 }
616
617 static unsigned
618 num_inst_src_regs(const glsl_to_tgsi_instruction *op)
619 {
620 return op->info->is_tex || is_resource_instruction(op->op) ?
621 op->info->num_src - 1 : op->info->num_src;
622 }
623
624 glsl_to_tgsi_instruction *
625 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, unsigned op,
626 st_dst_reg dst, st_dst_reg dst1,
627 st_src_reg src0, st_src_reg src1,
628 st_src_reg src2, st_src_reg src3)
629 {
630 glsl_to_tgsi_instruction *inst = new(mem_ctx) glsl_to_tgsi_instruction();
631 int num_reladdr = 0, i, j;
632 bool dst_is_64bit[2];
633
634 op = get_opcode(ir, op, dst, src0, src1);
635
636 /* If we have to do relative addressing, we want to load the ARL
637 * reg directly for one of the regs, and preload the other reladdr
638 * sources into temps.
639 */
640 num_reladdr += dst.reladdr != NULL || dst.reladdr2;
641 num_reladdr += dst1.reladdr != NULL || dst1.reladdr2;
642 num_reladdr += src0.reladdr != NULL || src0.reladdr2 != NULL;
643 num_reladdr += src1.reladdr != NULL || src1.reladdr2 != NULL;
644 num_reladdr += src2.reladdr != NULL || src2.reladdr2 != NULL;
645 num_reladdr += src3.reladdr != NULL || src3.reladdr2 != NULL;
646
647 reladdr_to_temp(ir, &src3, &num_reladdr);
648 reladdr_to_temp(ir, &src2, &num_reladdr);
649 reladdr_to_temp(ir, &src1, &num_reladdr);
650 reladdr_to_temp(ir, &src0, &num_reladdr);
651
652 if (dst.reladdr || dst.reladdr2) {
653 if (dst.reladdr)
654 emit_arl(ir, address_reg, *dst.reladdr);
655 if (dst.reladdr2)
656 emit_arl(ir, address_reg2, *dst.reladdr2);
657 num_reladdr--;
658 }
659 if (dst1.reladdr) {
660 emit_arl(ir, address_reg, *dst1.reladdr);
661 num_reladdr--;
662 }
663 assert(num_reladdr == 0);
664
665 inst->op = op;
666 inst->info = tgsi_get_opcode_info(op);
667 inst->dst[0] = dst;
668 inst->dst[1] = dst1;
669 inst->src[0] = src0;
670 inst->src[1] = src1;
671 inst->src[2] = src2;
672 inst->src[3] = src3;
673 inst->ir = ir;
674 inst->dead_mask = 0;
675 /* default to float, for paths where this is not initialized
676 * (since 0==UINT which is likely wrong):
677 */
678 inst->tex_type = GLSL_TYPE_FLOAT;
679
680 inst->function = NULL;
681
682 /* Update indirect addressing status used by TGSI */
683 if (dst.reladdr || dst.reladdr2) {
684 switch(dst.file) {
685 case PROGRAM_STATE_VAR:
686 case PROGRAM_CONSTANT:
687 case PROGRAM_UNIFORM:
688 this->indirect_addr_consts = true;
689 break;
690 case PROGRAM_IMMEDIATE:
691 assert(!"immediates should not have indirect addressing");
692 break;
693 default:
694 break;
695 }
696 }
697 else {
698 for (i = 0; i < 4; i++) {
699 if(inst->src[i].reladdr) {
700 switch(inst->src[i].file) {
701 case PROGRAM_STATE_VAR:
702 case PROGRAM_CONSTANT:
703 case PROGRAM_UNIFORM:
704 this->indirect_addr_consts = true;
705 break;
706 case PROGRAM_IMMEDIATE:
707 assert(!"immediates should not have indirect addressing");
708 break;
709 default:
710 break;
711 }
712 }
713 }
714 }
715
716 /*
717 * This section contains the double processing.
718 * GLSL just represents doubles as single channel values,
719 * however most HW and TGSI represent doubles as pairs of register channels.
720 *
721 * so we have to fixup destination writemask/index and src swizzle/indexes.
722 * dest writemasks need to translate from single channel write mask
723 * to a dual-channel writemask, but also need to modify the index,
724 * if we are touching the Z,W fields in the pre-translated writemask.
725 *
726 * src channels have similiar index modifications along with swizzle
727 * changes to we pick the XY, ZW pairs from the correct index.
728 *
729 * GLSL [0].x -> TGSI [0].xy
730 * GLSL [0].y -> TGSI [0].zw
731 * GLSL [0].z -> TGSI [1].xy
732 * GLSL [0].w -> TGSI [1].zw
733 */
734 for (j = 0; j < 2; j++) {
735 dst_is_64bit[j] = glsl_base_type_is_64bit(inst->dst[j].type);
736 if (!dst_is_64bit[j] && inst->dst[j].file == PROGRAM_OUTPUT && inst->dst[j].type == GLSL_TYPE_ARRAY) {
737 enum glsl_base_type type = find_array_type(this->output_arrays, this->num_output_arrays, inst->dst[j].array_id);
738 if (glsl_base_type_is_64bit(type))
739 dst_is_64bit[j] = true;
740 }
741 }
742
743 if (dst_is_64bit[0] || dst_is_64bit[1] ||
744 glsl_base_type_is_64bit(inst->src[0].type)) {
745 glsl_to_tgsi_instruction *dinst = NULL;
746 int initial_src_swz[4], initial_src_idx[4];
747 int initial_dst_idx[2], initial_dst_writemask[2];
748 /* select the writemask for dst0 or dst1 */
749 unsigned writemask = inst->dst[1].file == PROGRAM_UNDEFINED ? inst->dst[0].writemask : inst->dst[1].writemask;
750
751 /* copy out the writemask, index and swizzles for all src/dsts. */
752 for (j = 0; j < 2; j++) {
753 initial_dst_writemask[j] = inst->dst[j].writemask;
754 initial_dst_idx[j] = inst->dst[j].index;
755 }
756
757 for (j = 0; j < 4; j++) {
758 initial_src_swz[j] = inst->src[j].swizzle;
759 initial_src_idx[j] = inst->src[j].index;
760 }
761
762 /*
763 * scan all the components in the dst writemask
764 * generate an instruction for each of them if required.
765 */
766 st_src_reg addr;
767 while (writemask) {
768
769 int i = u_bit_scan(&writemask);
770
771 /* before emitting the instruction, see if we have to adjust store
772 * address */
773 if (i > 1 && inst->op == TGSI_OPCODE_STORE &&
774 addr.file == PROGRAM_UNDEFINED) {
775 /* We have to advance the buffer address by 16 */
776 addr = get_temp(glsl_type::uint_type);
777 emit_asm(ir, TGSI_OPCODE_UADD, st_dst_reg(addr),
778 inst->src[0], st_src_reg_for_int(16));
779 }
780
781
782 /* first time use previous instruction */
783 if (dinst == NULL) {
784 dinst = inst;
785 } else {
786 /* create a new instructions for subsequent attempts */
787 dinst = new(mem_ctx) glsl_to_tgsi_instruction();
788 *dinst = *inst;
789 dinst->next = NULL;
790 dinst->prev = NULL;
791 }
792 this->instructions.push_tail(dinst);
793
794 /* modify the destination if we are splitting */
795 for (j = 0; j < 2; j++) {
796 if (dst_is_64bit[j]) {
797 dinst->dst[j].writemask = (i & 1) ? WRITEMASK_ZW : WRITEMASK_XY;
798 dinst->dst[j].index = initial_dst_idx[j];
799 if (i > 1) {
800 if (dinst->op == TGSI_OPCODE_STORE) {
801 dinst->src[0] = addr;
802 } else {
803 dinst->dst[j].index++;
804 }
805 }
806 } else {
807 /* if we aren't writing to a double, just get the bit of the initial writemask
808 for this channel */
809 dinst->dst[j].writemask = initial_dst_writemask[j] & (1 << i);
810 }
811 }
812
813 /* modify the src registers */
814 for (j = 0; j < 4; j++) {
815 int swz = GET_SWZ(initial_src_swz[j], i);
816
817 if (glsl_base_type_is_64bit(dinst->src[j].type)) {
818 dinst->src[j].index = initial_src_idx[j];
819 if (swz > 1) {
820 dinst->src[j].double_reg2 = true;
821 dinst->src[j].index++;
822 }
823
824 if (swz & 1)
825 dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W);
826 else
827 dinst->src[j].swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
828
829 } else {
830 /* some opcodes are special case in what they use as sources
831 - F2D is a float src0, DLDEXP is integer src1 */
832 if (op == TGSI_OPCODE_F2D ||
833 op == TGSI_OPCODE_DLDEXP ||
834 (op == TGSI_OPCODE_UCMP && dst_is_64bit[0])) {
835 dinst->src[j].swizzle = MAKE_SWIZZLE4(swz, swz, swz, swz);
836 }
837 }
838 }
839 }
840 inst = dinst;
841 } else {
842 this->instructions.push_tail(inst);
843 }
844
845
846 return inst;
847 }
848
849 glsl_to_tgsi_instruction *
850 glsl_to_tgsi_visitor::emit_asm(ir_instruction *ir, unsigned op,
851 st_dst_reg dst,
852 st_src_reg src0, st_src_reg src1,
853 st_src_reg src2, st_src_reg src3)
854 {
855 return emit_asm(ir, op, dst, undef_dst, src0, src1, src2, src3);
856 }
857
858 /**
859 * Determines whether to use an integer, unsigned integer, or float opcode
860 * based on the operands and input opcode, then emits the result.
861 */
862 unsigned
863 glsl_to_tgsi_visitor::get_opcode(ir_instruction *ir, unsigned op,
864 st_dst_reg dst,
865 st_src_reg src0, st_src_reg src1)
866 {
867 enum glsl_base_type type = GLSL_TYPE_FLOAT;
868
869 if (op == TGSI_OPCODE_MOV)
870 return op;
871
872 assert(src0.type != GLSL_TYPE_ARRAY);
873 assert(src0.type != GLSL_TYPE_STRUCT);
874 assert(src1.type != GLSL_TYPE_ARRAY);
875 assert(src1.type != GLSL_TYPE_STRUCT);
876
877 if (is_resource_instruction(op))
878 type = src1.type;
879 else if (src0.type == GLSL_TYPE_DOUBLE || src1.type == GLSL_TYPE_DOUBLE)
880 type = GLSL_TYPE_DOUBLE;
881 else if (src0.type == GLSL_TYPE_FLOAT || src1.type == GLSL_TYPE_FLOAT)
882 type = GLSL_TYPE_FLOAT;
883 else if (native_integers)
884 type = src0.type == GLSL_TYPE_BOOL ? GLSL_TYPE_INT : src0.type;
885
886 #define case5(c, f, i, u, d) \
887 case TGSI_OPCODE_##c: \
888 if (type == GLSL_TYPE_DOUBLE) \
889 op = TGSI_OPCODE_##d; \
890 else if (type == GLSL_TYPE_INT) \
891 op = TGSI_OPCODE_##i; \
892 else if (type == GLSL_TYPE_UINT) \
893 op = TGSI_OPCODE_##u; \
894 else \
895 op = TGSI_OPCODE_##f; \
896 break;
897
898 #define case4(c, f, i, u) \
899 case TGSI_OPCODE_##c: \
900 if (type == GLSL_TYPE_INT) \
901 op = TGSI_OPCODE_##i; \
902 else if (type == GLSL_TYPE_UINT) \
903 op = TGSI_OPCODE_##u; \
904 else \
905 op = TGSI_OPCODE_##f; \
906 break;
907
908 #define case3(f, i, u) case4(f, f, i, u)
909 #define case4d(f, i, u, d) case5(f, f, i, u, d)
910 #define case3fid(f, i, d) case5(f, f, i, i, d)
911 #define case2fi(f, i) case4(f, f, i, i)
912 #define case2iu(i, u) case4(i, LAST, i, u)
913
914 #define casecomp(c, f, i, u, d) \
915 case TGSI_OPCODE_##c: \
916 if (type == GLSL_TYPE_DOUBLE) \
917 op = TGSI_OPCODE_##d; \
918 else if (type == GLSL_TYPE_INT || type == GLSL_TYPE_SUBROUTINE) \
919 op = TGSI_OPCODE_##i; \
920 else if (type == GLSL_TYPE_UINT) \
921 op = TGSI_OPCODE_##u; \
922 else if (native_integers) \
923 op = TGSI_OPCODE_##f; \
924 else \
925 op = TGSI_OPCODE_##c; \
926 break;
927
928 switch(op) {
929 case3fid(ADD, UADD, DADD);
930 case3fid(MUL, UMUL, DMUL);
931 case3fid(MAD, UMAD, DMAD);
932 case3fid(FMA, UMAD, DFMA);
933 case3(DIV, IDIV, UDIV);
934 case4d(MAX, IMAX, UMAX, DMAX);
935 case4d(MIN, IMIN, UMIN, DMIN);
936 case2iu(MOD, UMOD);
937
938 casecomp(SEQ, FSEQ, USEQ, USEQ, DSEQ);
939 casecomp(SNE, FSNE, USNE, USNE, DSNE);
940 casecomp(SGE, FSGE, ISGE, USGE, DSGE);
941 casecomp(SLT, FSLT, ISLT, USLT, DSLT);
942
943 case2iu(ISHR, USHR);
944
945 case3fid(SSG, ISSG, DSSG);
946 case3fid(ABS, IABS, DABS);
947
948 case2iu(IBFE, UBFE);
949 case2iu(IMSB, UMSB);
950 case2iu(IMUL_HI, UMUL_HI);
951
952 case3fid(SQRT, SQRT, DSQRT);
953
954 case3fid(RCP, RCP, DRCP);
955 case3fid(RSQ, RSQ, DRSQ);
956
957 case3fid(FRC, FRC, DFRAC);
958 case3fid(TRUNC, TRUNC, DTRUNC);
959 case3fid(CEIL, CEIL, DCEIL);
960 case3fid(FLR, FLR, DFLR);
961 case3fid(ROUND, ROUND, DROUND);
962
963 case2iu(ATOMIMAX, ATOMUMAX);
964 case2iu(ATOMIMIN, ATOMUMIN);
965
966 default: break;
967 }
968
969 assert(op != TGSI_OPCODE_LAST);
970 return op;
971 }
972
973 glsl_to_tgsi_instruction *
974 glsl_to_tgsi_visitor::emit_dp(ir_instruction *ir,
975 st_dst_reg dst, st_src_reg src0, st_src_reg src1,
976 unsigned elements)
977 {
978 static const unsigned dot_opcodes[] = {
979 TGSI_OPCODE_DP2, TGSI_OPCODE_DP3, TGSI_OPCODE_DP4
980 };
981
982 return emit_asm(ir, dot_opcodes[elements - 2], dst, src0, src1);
983 }
984
985 /**
986 * Emits TGSI scalar opcodes to produce unique answers across channels.
987 *
988 * Some TGSI opcodes are scalar-only, like ARB_fp/vp. The src X
989 * channel determines the result across all channels. So to do a vec4
990 * of this operation, we want to emit a scalar per source channel used
991 * to produce dest channels.
992 */
993 void
994 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
995 st_dst_reg dst,
996 st_src_reg orig_src0, st_src_reg orig_src1)
997 {
998 int i, j;
999 int done_mask = ~dst.writemask;
1000
1001 /* TGSI RCP is a scalar operation splatting results to all channels,
1002 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
1003 * dst channels.
1004 */
1005 for (i = 0; i < 4; i++) {
1006 GLuint this_mask = (1 << i);
1007 st_src_reg src0 = orig_src0;
1008 st_src_reg src1 = orig_src1;
1009
1010 if (done_mask & this_mask)
1011 continue;
1012
1013 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
1014 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
1015 for (j = i + 1; j < 4; j++) {
1016 /* If there is another enabled component in the destination that is
1017 * derived from the same inputs, generate its value on this pass as
1018 * well.
1019 */
1020 if (!(done_mask & (1 << j)) &&
1021 GET_SWZ(src0.swizzle, j) == src0_swiz &&
1022 GET_SWZ(src1.swizzle, j) == src1_swiz) {
1023 this_mask |= (1 << j);
1024 }
1025 }
1026 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
1027 src0_swiz, src0_swiz);
1028 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
1029 src1_swiz, src1_swiz);
1030
1031 dst.writemask = this_mask;
1032 emit_asm(ir, op, dst, src0, src1);
1033 done_mask |= this_mask;
1034 }
1035 }
1036
1037 void
1038 glsl_to_tgsi_visitor::emit_scalar(ir_instruction *ir, unsigned op,
1039 st_dst_reg dst, st_src_reg src0)
1040 {
1041 st_src_reg undef = undef_src;
1042
1043 undef.swizzle = SWIZZLE_XXXX;
1044
1045 emit_scalar(ir, op, dst, src0, undef);
1046 }
1047
1048 void
1049 glsl_to_tgsi_visitor::emit_arl(ir_instruction *ir,
1050 st_dst_reg dst, st_src_reg src0)
1051 {
1052 int op = TGSI_OPCODE_ARL;
1053
1054 if (src0.type == GLSL_TYPE_INT || src0.type == GLSL_TYPE_UINT)
1055 op = TGSI_OPCODE_UARL;
1056
1057 assert(dst.file == PROGRAM_ADDRESS);
1058 if (dst.index >= this->num_address_regs)
1059 this->num_address_regs = dst.index + 1;
1060
1061 emit_asm(NULL, op, dst, src0);
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 memcpy(uval, &val, sizeof(uval));
1135 src.index = add_constant(src.file, uval, 1, GL_DOUBLE, &src.swizzle);
1136 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
1137 return src;
1138 }
1139
1140 st_src_reg
1141 glsl_to_tgsi_visitor::st_src_reg_for_int(int val)
1142 {
1143 st_src_reg src(PROGRAM_IMMEDIATE, -1, GLSL_TYPE_INT);
1144 union gl_constant_value uval;
1145
1146 assert(native_integers);
1147
1148 uval.i = val;
1149 src.index = add_constant(src.file, &uval, 1, GL_INT, &src.swizzle);
1150
1151 return src;
1152 }
1153
1154 st_src_reg
1155 glsl_to_tgsi_visitor::st_src_reg_for_type(enum glsl_base_type type, int val)
1156 {
1157 if (native_integers)
1158 return type == GLSL_TYPE_FLOAT ? st_src_reg_for_float(val) :
1159 st_src_reg_for_int(val);
1160 else
1161 return st_src_reg_for_float(val);
1162 }
1163
1164 static int
1165 attrib_type_size(const struct glsl_type *type, bool is_vs_input)
1166 {
1167 return st_glsl_attrib_type_size(type, is_vs_input);
1168 }
1169
1170 static int
1171 type_size(const struct glsl_type *type)
1172 {
1173 return st_glsl_type_size(type);
1174 }
1175
1176 /**
1177 * If the given GLSL type is an array or matrix or a structure containing
1178 * an array/matrix member, return true. Else return false.
1179 *
1180 * This is used to determine which kind of temp storage (PROGRAM_TEMPORARY
1181 * or PROGRAM_ARRAY) should be used for variables of this type. Anytime
1182 * we have an array that might be indexed with a variable, we need to use
1183 * the later storage type.
1184 */
1185 static bool
1186 type_has_array_or_matrix(const glsl_type *type)
1187 {
1188 if (type->is_array() || type->is_matrix())
1189 return true;
1190
1191 if (type->is_record()) {
1192 for (unsigned i = 0; i < type->length; i++) {
1193 if (type_has_array_or_matrix(type->fields.structure[i].type)) {
1194 return true;
1195 }
1196 }
1197 }
1198
1199 return false;
1200 }
1201
1202
1203 /**
1204 * In the initial pass of codegen, we assign temporary numbers to
1205 * intermediate results. (not SSA -- variable assignments will reuse
1206 * storage).
1207 */
1208 st_src_reg
1209 glsl_to_tgsi_visitor::get_temp(const glsl_type *type)
1210 {
1211 st_src_reg src;
1212
1213 src.type = native_integers ? type->base_type : GLSL_TYPE_FLOAT;
1214 src.reladdr = NULL;
1215 src.negate = 0;
1216
1217 if (!options->EmitNoIndirectTemp && type_has_array_or_matrix(type)) {
1218 if (next_array >= max_num_arrays) {
1219 max_num_arrays += 32;
1220 array_sizes = (unsigned*)
1221 realloc(array_sizes, sizeof(array_sizes[0]) * max_num_arrays);
1222 }
1223
1224 src.file = PROGRAM_ARRAY;
1225 src.index = next_array << 16 | 0x8000;
1226 array_sizes[next_array] = type_size(type);
1227 ++next_array;
1228
1229 } else {
1230 src.file = PROGRAM_TEMPORARY;
1231 src.index = next_temp;
1232 next_temp += type_size(type);
1233 }
1234
1235 if (type->is_array() || type->is_record()) {
1236 src.swizzle = SWIZZLE_NOOP;
1237 } else {
1238 src.swizzle = swizzle_for_size(type->vector_elements);
1239 }
1240
1241 return src;
1242 }
1243
1244 variable_storage *
1245 glsl_to_tgsi_visitor::find_variable_storage(ir_variable *var)
1246 {
1247
1248 foreach_in_list(variable_storage, entry, &this->variables) {
1249 if (entry->var == var)
1250 return entry;
1251 }
1252
1253 return NULL;
1254 }
1255
1256 void
1257 glsl_to_tgsi_visitor::visit(ir_variable *ir)
1258 {
1259 if (strcmp(ir->name, "gl_FragCoord") == 0) {
1260 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
1261
1262 fp->OriginUpperLeft = ir->data.origin_upper_left;
1263 fp->PixelCenterInteger = ir->data.pixel_center_integer;
1264 }
1265
1266 if (ir->data.mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
1267 unsigned int i;
1268 const ir_state_slot *const slots = ir->get_state_slots();
1269 assert(slots != NULL);
1270
1271 /* Check if this statevar's setup in the STATE file exactly
1272 * matches how we'll want to reference it as a
1273 * struct/array/whatever. If not, then we need to move it into
1274 * temporary storage and hope that it'll get copy-propagated
1275 * out.
1276 */
1277 for (i = 0; i < ir->get_num_state_slots(); i++) {
1278 if (slots[i].swizzle != SWIZZLE_XYZW) {
1279 break;
1280 }
1281 }
1282
1283 variable_storage *storage;
1284 st_dst_reg dst;
1285 if (i == ir->get_num_state_slots()) {
1286 /* We'll set the index later. */
1287 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
1288 this->variables.push_tail(storage);
1289
1290 dst = undef_dst;
1291 } else {
1292 /* The variable_storage constructor allocates slots based on the size
1293 * of the type. However, this had better match the number of state
1294 * elements that we're going to copy into the new temporary.
1295 */
1296 assert((int) ir->get_num_state_slots() == type_size(ir->type));
1297
1298 dst = st_dst_reg(get_temp(ir->type));
1299
1300 storage = new(mem_ctx) variable_storage(ir, dst.file, dst.index);
1301
1302 this->variables.push_tail(storage);
1303 }
1304
1305
1306 for (unsigned int i = 0; i < ir->get_num_state_slots(); i++) {
1307 int index = _mesa_add_state_reference(this->prog->Parameters,
1308 (gl_state_index *)slots[i].tokens);
1309
1310 if (storage->file == PROGRAM_STATE_VAR) {
1311 if (storage->index == -1) {
1312 storage->index = index;
1313 } else {
1314 assert(index == storage->index + (int)i);
1315 }
1316 } else {
1317 /* We use GLSL_TYPE_FLOAT here regardless of the actual type of
1318 * the data being moved since MOV does not care about the type of
1319 * data it is moving, and we don't want to declare registers with
1320 * array or struct types.
1321 */
1322 st_src_reg src(PROGRAM_STATE_VAR, index, GLSL_TYPE_FLOAT);
1323 src.swizzle = slots[i].swizzle;
1324 emit_asm(ir, TGSI_OPCODE_MOV, dst, src);
1325 /* even a float takes up a whole vec4 reg in a struct/array. */
1326 dst.index++;
1327 }
1328 }
1329
1330 if (storage->file == PROGRAM_TEMPORARY &&
1331 dst.index != storage->index + (int) ir->get_num_state_slots()) {
1332 fail_link(this->shader_program,
1333 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
1334 ir->name, dst.index - storage->index,
1335 type_size(ir->type));
1336 }
1337 }
1338 }
1339
1340 void
1341 glsl_to_tgsi_visitor::visit(ir_loop *ir)
1342 {
1343 emit_asm(NULL, TGSI_OPCODE_BGNLOOP);
1344
1345 visit_exec_list(&ir->body_instructions, this);
1346
1347 emit_asm(NULL, TGSI_OPCODE_ENDLOOP);
1348 }
1349
1350 void
1351 glsl_to_tgsi_visitor::visit(ir_loop_jump *ir)
1352 {
1353 switch (ir->mode) {
1354 case ir_loop_jump::jump_break:
1355 emit_asm(NULL, TGSI_OPCODE_BRK);
1356 break;
1357 case ir_loop_jump::jump_continue:
1358 emit_asm(NULL, TGSI_OPCODE_CONT);
1359 break;
1360 }
1361 }
1362
1363
1364 void
1365 glsl_to_tgsi_visitor::visit(ir_function_signature *ir)
1366 {
1367 assert(0);
1368 (void)ir;
1369 }
1370
1371 void
1372 glsl_to_tgsi_visitor::visit(ir_function *ir)
1373 {
1374 /* Ignore function bodies other than main() -- we shouldn't see calls to
1375 * them since they should all be inlined before we get to glsl_to_tgsi.
1376 */
1377 if (strcmp(ir->name, "main") == 0) {
1378 const ir_function_signature *sig;
1379 exec_list empty;
1380
1381 sig = ir->matching_signature(NULL, &empty, false);
1382
1383 assert(sig);
1384
1385 foreach_in_list(ir_instruction, ir, &sig->body) {
1386 ir->accept(this);
1387 }
1388 }
1389 }
1390
1391 bool
1392 glsl_to_tgsi_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
1393 {
1394 int nonmul_operand = 1 - mul_operand;
1395 st_src_reg a, b, c;
1396 st_dst_reg result_dst;
1397
1398 ir_expression *expr = ir->operands[mul_operand]->as_expression();
1399 if (!expr || expr->operation != ir_binop_mul)
1400 return false;
1401
1402 expr->operands[0]->accept(this);
1403 a = this->result;
1404 expr->operands[1]->accept(this);
1405 b = this->result;
1406 ir->operands[nonmul_operand]->accept(this);
1407 c = this->result;
1408
1409 this->result = get_temp(ir->type);
1410 result_dst = st_dst_reg(this->result);
1411 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1412 emit_asm(ir, TGSI_OPCODE_MAD, result_dst, a, b, c);
1413
1414 return true;
1415 }
1416
1417 /**
1418 * Emit MAD(a, -b, a) instead of AND(a, NOT(b))
1419 *
1420 * The logic values are 1.0 for true and 0.0 for false. Logical-and is
1421 * implemented using multiplication, and logical-or is implemented using
1422 * addition. Logical-not can be implemented as (true - x), or (1.0 - x).
1423 * As result, the logical expression (a & !b) can be rewritten as:
1424 *
1425 * - a * !b
1426 * - a * (1 - b)
1427 * - (a * 1) - (a * b)
1428 * - a + -(a * b)
1429 * - a + (a * -b)
1430 *
1431 * This final expression can be implemented as a single MAD(a, -b, a)
1432 * instruction.
1433 */
1434 bool
1435 glsl_to_tgsi_visitor::try_emit_mad_for_and_not(ir_expression *ir, int try_operand)
1436 {
1437 const int other_operand = 1 - try_operand;
1438 st_src_reg a, b;
1439
1440 ir_expression *expr = ir->operands[try_operand]->as_expression();
1441 if (!expr || expr->operation != ir_unop_logic_not)
1442 return false;
1443
1444 ir->operands[other_operand]->accept(this);
1445 a = this->result;
1446 expr->operands[0]->accept(this);
1447 b = this->result;
1448
1449 b.negate = ~b.negate;
1450
1451 this->result = get_temp(ir->type);
1452 emit_asm(ir, TGSI_OPCODE_MAD, st_dst_reg(this->result), a, b, a);
1453
1454 return true;
1455 }
1456
1457 void
1458 glsl_to_tgsi_visitor::reladdr_to_temp(ir_instruction *ir,
1459 st_src_reg *reg, int *num_reladdr)
1460 {
1461 if (!reg->reladdr && !reg->reladdr2)
1462 return;
1463
1464 if (reg->reladdr) emit_arl(ir, address_reg, *reg->reladdr);
1465 if (reg->reladdr2) emit_arl(ir, address_reg2, *reg->reladdr2);
1466
1467 if (*num_reladdr != 1) {
1468 st_src_reg temp = get_temp(reg->type == GLSL_TYPE_DOUBLE ? glsl_type::dvec4_type : glsl_type::vec4_type);
1469
1470 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), *reg);
1471 *reg = temp;
1472 }
1473
1474 (*num_reladdr)--;
1475 }
1476
1477 void
1478 glsl_to_tgsi_visitor::visit(ir_expression *ir)
1479 {
1480 st_src_reg op[ARRAY_SIZE(ir->operands)];
1481
1482 /* Quick peephole: Emit MAD(a, b, c) instead of ADD(MUL(a, b), c)
1483 */
1484 if (ir->operation == ir_binop_add) {
1485 if (try_emit_mad(ir, 1))
1486 return;
1487 if (try_emit_mad(ir, 0))
1488 return;
1489 }
1490
1491 /* Quick peephole: Emit OPCODE_MAD(-a, -b, a) instead of AND(a, NOT(b))
1492 */
1493 if (!native_integers && ir->operation == ir_binop_logic_and) {
1494 if (try_emit_mad_for_and_not(ir, 1))
1495 return;
1496 if (try_emit_mad_for_and_not(ir, 0))
1497 return;
1498 }
1499
1500 if (ir->operation == ir_quadop_vector)
1501 assert(!"ir_quadop_vector should have been lowered");
1502
1503 for (unsigned int operand = 0; operand < ir->get_num_operands(); operand++) {
1504 this->result.file = PROGRAM_UNDEFINED;
1505 ir->operands[operand]->accept(this);
1506 if (this->result.file == PROGRAM_UNDEFINED) {
1507 printf("Failed to get tree for expression operand:\n");
1508 ir->operands[operand]->print();
1509 printf("\n");
1510 exit(1);
1511 }
1512 op[operand] = this->result;
1513
1514 /* Matrix expression operands should have been broken down to vector
1515 * operations already.
1516 */
1517 assert(!ir->operands[operand]->type->is_matrix());
1518 }
1519
1520 visit_expression(ir, op);
1521 }
1522
1523 /* The non-recursive part of the expression visitor lives in a separate
1524 * function and should be prevented from being inlined, to avoid a stack
1525 * explosion when deeply nested expressions are visited.
1526 */
1527 void
1528 glsl_to_tgsi_visitor::visit_expression(ir_expression* ir, st_src_reg *op)
1529 {
1530 st_src_reg result_src;
1531 st_dst_reg result_dst;
1532
1533 int vector_elements = ir->operands[0]->type->vector_elements;
1534 if (ir->operands[1]) {
1535 vector_elements = MAX2(vector_elements,
1536 ir->operands[1]->type->vector_elements);
1537 }
1538
1539 this->result.file = PROGRAM_UNDEFINED;
1540
1541 /* Storage for our result. Ideally for an assignment we'd be using
1542 * the actual storage for the result here, instead.
1543 */
1544 result_src = get_temp(ir->type);
1545 /* convenience for the emit functions below. */
1546 result_dst = st_dst_reg(result_src);
1547 /* Limit writes to the channels that will be used by result_src later.
1548 * This does limit this temp's use as a temporary for multi-instruction
1549 * sequences.
1550 */
1551 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1552
1553 switch (ir->operation) {
1554 case ir_unop_logic_not:
1555 if (result_dst.type != GLSL_TYPE_FLOAT)
1556 emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
1557 else {
1558 /* Previously 'SEQ dst, src, 0.0' was used for this. However, many
1559 * older GPUs implement SEQ using multiple instructions (i915 uses two
1560 * SGE instructions and a MUL instruction). Since our logic values are
1561 * 0.0 and 1.0, 1-x also implements !x.
1562 */
1563 op[0].negate = ~op[0].negate;
1564 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], st_src_reg_for_float(1.0));
1565 }
1566 break;
1567 case ir_unop_neg:
1568 if (result_dst.type == GLSL_TYPE_INT || result_dst.type == GLSL_TYPE_UINT)
1569 emit_asm(ir, TGSI_OPCODE_INEG, result_dst, op[0]);
1570 else if (result_dst.type == GLSL_TYPE_DOUBLE)
1571 emit_asm(ir, TGSI_OPCODE_DNEG, result_dst, op[0]);
1572 else {
1573 op[0].negate = ~op[0].negate;
1574 result_src = op[0];
1575 }
1576 break;
1577 case ir_unop_subroutine_to_int:
1578 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1579 break;
1580 case ir_unop_abs:
1581 emit_asm(ir, TGSI_OPCODE_ABS, result_dst, op[0]);
1582 break;
1583 case ir_unop_sign:
1584 emit_asm(ir, TGSI_OPCODE_SSG, result_dst, op[0]);
1585 break;
1586 case ir_unop_rcp:
1587 emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, op[0]);
1588 break;
1589
1590 case ir_unop_exp2:
1591 emit_scalar(ir, TGSI_OPCODE_EX2, result_dst, op[0]);
1592 break;
1593 case ir_unop_exp:
1594 case ir_unop_log:
1595 assert(!"not reached: should be handled by ir_explog_to_explog2");
1596 break;
1597 case ir_unop_log2:
1598 emit_scalar(ir, TGSI_OPCODE_LG2, result_dst, op[0]);
1599 break;
1600 case ir_unop_sin:
1601 emit_scalar(ir, TGSI_OPCODE_SIN, result_dst, op[0]);
1602 break;
1603 case ir_unop_cos:
1604 emit_scalar(ir, TGSI_OPCODE_COS, result_dst, op[0]);
1605 break;
1606 case ir_unop_saturate: {
1607 glsl_to_tgsi_instruction *inst;
1608 inst = emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1609 inst->saturate = true;
1610 break;
1611 }
1612
1613 case ir_unop_dFdx:
1614 case ir_unop_dFdx_coarse:
1615 emit_asm(ir, TGSI_OPCODE_DDX, result_dst, op[0]);
1616 break;
1617 case ir_unop_dFdx_fine:
1618 emit_asm(ir, TGSI_OPCODE_DDX_FINE, result_dst, op[0]);
1619 break;
1620 case ir_unop_dFdy:
1621 case ir_unop_dFdy_coarse:
1622 case ir_unop_dFdy_fine:
1623 {
1624 /* The X component contains 1 or -1 depending on whether the framebuffer
1625 * is a FBO or the window system buffer, respectively.
1626 * It is then multiplied with the source operand of DDY.
1627 */
1628 static const gl_state_index transform_y_state[STATE_LENGTH]
1629 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
1630
1631 unsigned transform_y_index =
1632 _mesa_add_state_reference(this->prog->Parameters,
1633 transform_y_state);
1634
1635 st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
1636 transform_y_index,
1637 glsl_type::vec4_type);
1638 transform_y.swizzle = SWIZZLE_XXXX;
1639
1640 st_src_reg temp = get_temp(glsl_type::vec4_type);
1641
1642 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(temp), transform_y, op[0]);
1643 emit_asm(ir, ir->operation == ir_unop_dFdy_fine ?
1644 TGSI_OPCODE_DDY_FINE : TGSI_OPCODE_DDY, result_dst, temp);
1645 break;
1646 }
1647
1648 case ir_unop_frexp_sig:
1649 emit_asm(ir, TGSI_OPCODE_DFRACEXP, result_dst, undef_dst, op[0]);
1650 break;
1651
1652 case ir_unop_frexp_exp:
1653 emit_asm(ir, TGSI_OPCODE_DFRACEXP, undef_dst, result_dst, op[0]);
1654 break;
1655
1656 case ir_unop_noise: {
1657 /* At some point, a motivated person could add a better
1658 * implementation of noise. Currently not even the nvidia
1659 * binary drivers do anything more than this. In any case, the
1660 * place to do this is in the GL state tracker, not the poor
1661 * driver.
1662 */
1663 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, st_src_reg_for_float(0.5));
1664 break;
1665 }
1666
1667 case ir_binop_add:
1668 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1669 break;
1670 case ir_binop_sub:
1671 emit_asm(ir, TGSI_OPCODE_SUB, result_dst, op[0], op[1]);
1672 break;
1673
1674 case ir_binop_mul:
1675 emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1676 break;
1677 case ir_binop_div:
1678 if (result_dst.type == GLSL_TYPE_FLOAT || result_dst.type == GLSL_TYPE_DOUBLE)
1679 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1680 else
1681 emit_asm(ir, TGSI_OPCODE_DIV, result_dst, op[0], op[1]);
1682 break;
1683 case ir_binop_mod:
1684 if (result_dst.type == GLSL_TYPE_FLOAT)
1685 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1686 else
1687 emit_asm(ir, TGSI_OPCODE_MOD, result_dst, op[0], op[1]);
1688 break;
1689
1690 case ir_binop_less:
1691 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, op[0], op[1]);
1692 break;
1693 case ir_binop_greater:
1694 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, op[1], op[0]);
1695 break;
1696 case ir_binop_lequal:
1697 emit_asm(ir, TGSI_OPCODE_SGE, result_dst, op[1], op[0]);
1698 break;
1699 case ir_binop_gequal:
1700 emit_asm(ir, TGSI_OPCODE_SGE, result_dst, op[0], op[1]);
1701 break;
1702 case ir_binop_equal:
1703 emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1704 break;
1705 case ir_binop_nequal:
1706 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1707 break;
1708 case ir_binop_all_equal:
1709 /* "==" operator producing a scalar boolean. */
1710 if (ir->operands[0]->type->is_vector() ||
1711 ir->operands[1]->type->is_vector()) {
1712 st_src_reg temp = get_temp(native_integers ?
1713 glsl_type::uvec4_type :
1714 glsl_type::vec4_type);
1715
1716 if (native_integers) {
1717 st_dst_reg temp_dst = st_dst_reg(temp);
1718 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1719
1720 if (ir->operands[0]->type->is_boolean() &&
1721 ir->operands[1]->as_constant() &&
1722 ir->operands[1]->as_constant()->is_one()) {
1723 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1724 } else {
1725 emit_asm(ir, TGSI_OPCODE_SEQ, st_dst_reg(temp), op[0], op[1]);
1726 }
1727
1728 /* Emit 1-3 AND operations to combine the SEQ results. */
1729 switch (ir->operands[0]->type->vector_elements) {
1730 case 2:
1731 break;
1732 case 3:
1733 temp_dst.writemask = WRITEMASK_Y;
1734 temp1.swizzle = SWIZZLE_YYYY;
1735 temp2.swizzle = SWIZZLE_ZZZZ;
1736 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1737 break;
1738 case 4:
1739 temp_dst.writemask = WRITEMASK_X;
1740 temp1.swizzle = SWIZZLE_XXXX;
1741 temp2.swizzle = SWIZZLE_YYYY;
1742 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1743 temp_dst.writemask = WRITEMASK_Y;
1744 temp1.swizzle = SWIZZLE_ZZZZ;
1745 temp2.swizzle = SWIZZLE_WWWW;
1746 emit_asm(ir, TGSI_OPCODE_AND, temp_dst, temp1, temp2);
1747 }
1748
1749 temp1.swizzle = SWIZZLE_XXXX;
1750 temp2.swizzle = SWIZZLE_YYYY;
1751 emit_asm(ir, TGSI_OPCODE_AND, result_dst, temp1, temp2);
1752 } else {
1753 emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1754
1755 /* After the dot-product, the value will be an integer on the
1756 * range [0,4]. Zero becomes 1.0, and positive values become zero.
1757 */
1758 emit_dp(ir, result_dst, temp, temp, vector_elements);
1759
1760 /* Negating the result of the dot-product gives values on the range
1761 * [-4, 0]. Zero becomes 1.0, and negative values become zero.
1762 * This is achieved using SGE.
1763 */
1764 st_src_reg sge_src = result_src;
1765 sge_src.negate = ~sge_src.negate;
1766 emit_asm(ir, TGSI_OPCODE_SGE, result_dst, sge_src, st_src_reg_for_float(0.0));
1767 }
1768 } else {
1769 emit_asm(ir, TGSI_OPCODE_SEQ, result_dst, op[0], op[1]);
1770 }
1771 break;
1772 case ir_binop_any_nequal:
1773 /* "!=" operator producing a scalar boolean. */
1774 if (ir->operands[0]->type->is_vector() ||
1775 ir->operands[1]->type->is_vector()) {
1776 st_src_reg temp = get_temp(native_integers ?
1777 glsl_type::uvec4_type :
1778 glsl_type::vec4_type);
1779 if (ir->operands[0]->type->is_boolean() &&
1780 ir->operands[1]->as_constant() &&
1781 ir->operands[1]->as_constant()->is_zero()) {
1782 emit_asm(ir, TGSI_OPCODE_MOV, st_dst_reg(temp), op[0]);
1783 } else {
1784 emit_asm(ir, TGSI_OPCODE_SNE, st_dst_reg(temp), op[0], op[1]);
1785 }
1786
1787 if (native_integers) {
1788 st_dst_reg temp_dst = st_dst_reg(temp);
1789 st_src_reg temp1 = st_src_reg(temp), temp2 = st_src_reg(temp);
1790
1791 /* Emit 1-3 OR operations to combine the SNE results. */
1792 switch (ir->operands[0]->type->vector_elements) {
1793 case 2:
1794 break;
1795 case 3:
1796 temp_dst.writemask = WRITEMASK_Y;
1797 temp1.swizzle = SWIZZLE_YYYY;
1798 temp2.swizzle = SWIZZLE_ZZZZ;
1799 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1800 break;
1801 case 4:
1802 temp_dst.writemask = WRITEMASK_X;
1803 temp1.swizzle = SWIZZLE_XXXX;
1804 temp2.swizzle = SWIZZLE_YYYY;
1805 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1806 temp_dst.writemask = WRITEMASK_Y;
1807 temp1.swizzle = SWIZZLE_ZZZZ;
1808 temp2.swizzle = SWIZZLE_WWWW;
1809 emit_asm(ir, TGSI_OPCODE_OR, temp_dst, temp1, temp2);
1810 }
1811
1812 temp1.swizzle = SWIZZLE_XXXX;
1813 temp2.swizzle = SWIZZLE_YYYY;
1814 emit_asm(ir, TGSI_OPCODE_OR, result_dst, temp1, temp2);
1815 } else {
1816 /* After the dot-product, the value will be an integer on the
1817 * range [0,4]. Zero stays zero, and positive values become 1.0.
1818 */
1819 glsl_to_tgsi_instruction *const dp =
1820 emit_dp(ir, result_dst, temp, temp, vector_elements);
1821 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1822 /* The clamping to [0,1] can be done for free in the fragment
1823 * shader with a saturate.
1824 */
1825 dp->saturate = true;
1826 } else {
1827 /* Negating the result of the dot-product gives values on the range
1828 * [-4, 0]. Zero stays zero, and negative values become 1.0. This
1829 * achieved using SLT.
1830 */
1831 st_src_reg slt_src = result_src;
1832 slt_src.negate = ~slt_src.negate;
1833 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1834 }
1835 }
1836 } else {
1837 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1838 }
1839 break;
1840
1841 case ir_binop_logic_xor:
1842 if (native_integers)
1843 emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
1844 else
1845 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], op[1]);
1846 break;
1847
1848 case ir_binop_logic_or: {
1849 if (native_integers) {
1850 /* If integers are used as booleans, we can use an actual "or"
1851 * instruction.
1852 */
1853 assert(native_integers);
1854 emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
1855 } else {
1856 /* After the addition, the value will be an integer on the
1857 * range [0,2]. Zero stays zero, and positive values become 1.0.
1858 */
1859 glsl_to_tgsi_instruction *add =
1860 emit_asm(ir, TGSI_OPCODE_ADD, result_dst, op[0], op[1]);
1861 if (this->prog->Target == GL_FRAGMENT_PROGRAM_ARB) {
1862 /* The clamping to [0,1] can be done for free in the fragment
1863 * shader with a saturate if floats are being used as boolean values.
1864 */
1865 add->saturate = true;
1866 } else {
1867 /* Negating the result of the addition gives values on the range
1868 * [-2, 0]. Zero stays zero, and negative values become 1.0. This
1869 * is achieved using SLT.
1870 */
1871 st_src_reg slt_src = result_src;
1872 slt_src.negate = ~slt_src.negate;
1873 emit_asm(ir, TGSI_OPCODE_SLT, result_dst, slt_src, st_src_reg_for_float(0.0));
1874 }
1875 }
1876 break;
1877 }
1878
1879 case ir_binop_logic_and:
1880 /* If native integers are disabled, the bool args are stored as float 0.0
1881 * or 1.0, so "mul" gives us "and". If they're enabled, just use the
1882 * actual AND opcode.
1883 */
1884 if (native_integers)
1885 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
1886 else
1887 emit_asm(ir, TGSI_OPCODE_MUL, result_dst, op[0], op[1]);
1888 break;
1889
1890 case ir_binop_dot:
1891 assert(ir->operands[0]->type->is_vector());
1892 assert(ir->operands[0]->type == ir->operands[1]->type);
1893 emit_dp(ir, result_dst, op[0], op[1],
1894 ir->operands[0]->type->vector_elements);
1895 break;
1896
1897 case ir_unop_sqrt:
1898 if (have_sqrt) {
1899 emit_scalar(ir, TGSI_OPCODE_SQRT, result_dst, op[0]);
1900 } else {
1901 /* This is the only instruction sequence that makes the game "Risen"
1902 * render correctly. ABS is not required for the game, but since GLSL
1903 * declares negative values as "undefined", allowing us to do whatever
1904 * we want, I choose to use ABS to match DX9 and pre-GLSL RSQ
1905 * behavior.
1906 */
1907 emit_scalar(ir, TGSI_OPCODE_ABS, result_dst, op[0]);
1908 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, result_src);
1909 emit_scalar(ir, TGSI_OPCODE_RCP, result_dst, result_src);
1910 }
1911 break;
1912 case ir_unop_rsq:
1913 emit_scalar(ir, TGSI_OPCODE_RSQ, result_dst, op[0]);
1914 break;
1915 case ir_unop_i2f:
1916 if (native_integers) {
1917 emit_asm(ir, TGSI_OPCODE_I2F, result_dst, op[0]);
1918 break;
1919 }
1920 /* fallthrough to next case otherwise */
1921 case ir_unop_b2f:
1922 if (native_integers) {
1923 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_float(1.0));
1924 break;
1925 }
1926 /* fallthrough to next case otherwise */
1927 case ir_unop_i2u:
1928 case ir_unop_u2i:
1929 /* Converting between signed and unsigned integers is a no-op. */
1930 result_src = op[0];
1931 result_src.type = result_dst.type;
1932 break;
1933 case ir_unop_b2i:
1934 if (native_integers) {
1935 /* Booleans are stored as integers using ~0 for true and 0 for false.
1936 * GLSL requires that int(bool) return 1 for true and 0 for false.
1937 * This conversion is done with AND, but it could be done with NEG.
1938 */
1939 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], st_src_reg_for_int(1));
1940 } else {
1941 /* Booleans and integers are both stored as floats when native
1942 * integers are disabled.
1943 */
1944 result_src = op[0];
1945 }
1946 break;
1947 case ir_unop_f2i:
1948 if (native_integers)
1949 emit_asm(ir, TGSI_OPCODE_F2I, result_dst, op[0]);
1950 else
1951 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1952 break;
1953 case ir_unop_f2u:
1954 if (native_integers)
1955 emit_asm(ir, TGSI_OPCODE_F2U, result_dst, op[0]);
1956 else
1957 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1958 break;
1959 case ir_unop_bitcast_f2i:
1960 case ir_unop_bitcast_f2u:
1961 /* Make sure we don't propagate the negate modifier to integer opcodes. */
1962 if (op[0].negate)
1963 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
1964 else
1965 result_src = op[0];
1966 result_src.type = ir->operation == ir_unop_bitcast_f2i ? GLSL_TYPE_INT :
1967 GLSL_TYPE_UINT;
1968 break;
1969 case ir_unop_bitcast_i2f:
1970 case ir_unop_bitcast_u2f:
1971 result_src = op[0];
1972 result_src.type = GLSL_TYPE_FLOAT;
1973 break;
1974 case ir_unop_f2b:
1975 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1976 break;
1977 case ir_unop_d2b:
1978 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_double(0.0));
1979 break;
1980 case ir_unop_i2b:
1981 if (native_integers)
1982 emit_asm(ir, TGSI_OPCODE_USNE, result_dst, op[0], st_src_reg_for_int(0));
1983 else
1984 emit_asm(ir, TGSI_OPCODE_SNE, result_dst, op[0], st_src_reg_for_float(0.0));
1985 break;
1986 case ir_unop_trunc:
1987 emit_asm(ir, TGSI_OPCODE_TRUNC, result_dst, op[0]);
1988 break;
1989 case ir_unop_ceil:
1990 emit_asm(ir, TGSI_OPCODE_CEIL, result_dst, op[0]);
1991 break;
1992 case ir_unop_floor:
1993 emit_asm(ir, TGSI_OPCODE_FLR, result_dst, op[0]);
1994 break;
1995 case ir_unop_round_even:
1996 emit_asm(ir, TGSI_OPCODE_ROUND, result_dst, op[0]);
1997 break;
1998 case ir_unop_fract:
1999 emit_asm(ir, TGSI_OPCODE_FRC, result_dst, op[0]);
2000 break;
2001
2002 case ir_binop_min:
2003 emit_asm(ir, TGSI_OPCODE_MIN, result_dst, op[0], op[1]);
2004 break;
2005 case ir_binop_max:
2006 emit_asm(ir, TGSI_OPCODE_MAX, result_dst, op[0], op[1]);
2007 break;
2008 case ir_binop_pow:
2009 emit_scalar(ir, TGSI_OPCODE_POW, result_dst, op[0], op[1]);
2010 break;
2011
2012 case ir_unop_bit_not:
2013 if (native_integers) {
2014 emit_asm(ir, TGSI_OPCODE_NOT, result_dst, op[0]);
2015 break;
2016 }
2017 case ir_unop_u2f:
2018 if (native_integers) {
2019 emit_asm(ir, TGSI_OPCODE_U2F, result_dst, op[0]);
2020 break;
2021 }
2022 case ir_binop_lshift:
2023 if (native_integers) {
2024 emit_asm(ir, TGSI_OPCODE_SHL, result_dst, op[0], op[1]);
2025 break;
2026 }
2027 case ir_binop_rshift:
2028 if (native_integers) {
2029 emit_asm(ir, TGSI_OPCODE_ISHR, result_dst, op[0], op[1]);
2030 break;
2031 }
2032 case ir_binop_bit_and:
2033 if (native_integers) {
2034 emit_asm(ir, TGSI_OPCODE_AND, result_dst, op[0], op[1]);
2035 break;
2036 }
2037 case ir_binop_bit_xor:
2038 if (native_integers) {
2039 emit_asm(ir, TGSI_OPCODE_XOR, result_dst, op[0], op[1]);
2040 break;
2041 }
2042 case ir_binop_bit_or:
2043 if (native_integers) {
2044 emit_asm(ir, TGSI_OPCODE_OR, result_dst, op[0], op[1]);
2045 break;
2046 }
2047
2048 assert(!"GLSL 1.30 features unsupported");
2049 break;
2050
2051 case ir_binop_ubo_load: {
2052 ir_constant *const_uniform_block = ir->operands[0]->as_constant();
2053 ir_constant *const_offset_ir = ir->operands[1]->as_constant();
2054 unsigned const_offset = const_offset_ir ? const_offset_ir->value.u[0] : 0;
2055 unsigned const_block = const_uniform_block ? const_uniform_block->value.u[0] + 1 : 0;
2056 st_src_reg index_reg = get_temp(glsl_type::uint_type);
2057 st_src_reg cbuf;
2058
2059 cbuf.type = ir->type->base_type;
2060 cbuf.file = PROGRAM_CONSTANT;
2061 cbuf.index = 0;
2062 cbuf.reladdr = NULL;
2063 cbuf.negate = 0;
2064
2065 assert(ir->type->is_vector() || ir->type->is_scalar());
2066
2067 if (const_offset_ir) {
2068 /* Constant index into constant buffer */
2069 cbuf.reladdr = NULL;
2070 cbuf.index = const_offset / 16;
2071 }
2072 else {
2073 /* Relative/variable index into constant buffer */
2074 emit_asm(ir, TGSI_OPCODE_USHR, st_dst_reg(index_reg), op[1],
2075 st_src_reg_for_int(4));
2076 cbuf.reladdr = ralloc(mem_ctx, st_src_reg);
2077 memcpy(cbuf.reladdr, &index_reg, sizeof(index_reg));
2078 }
2079
2080 if (const_uniform_block) {
2081 /* Constant constant buffer */
2082 cbuf.reladdr2 = NULL;
2083 cbuf.index2D = const_block;
2084 cbuf.has_index2 = true;
2085 }
2086 else {
2087 /* Relative/variable constant buffer */
2088 cbuf.reladdr2 = ralloc(mem_ctx, st_src_reg);
2089 cbuf.index2D = 1;
2090 memcpy(cbuf.reladdr2, &op[0], sizeof(st_src_reg));
2091 cbuf.has_index2 = true;
2092 }
2093
2094 cbuf.swizzle = swizzle_for_size(ir->type->vector_elements);
2095 if (glsl_base_type_is_64bit(cbuf.type))
2096 cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 8,
2097 const_offset % 16 / 8,
2098 const_offset % 16 / 8,
2099 const_offset % 16 / 8);
2100 else
2101 cbuf.swizzle += MAKE_SWIZZLE4(const_offset % 16 / 4,
2102 const_offset % 16 / 4,
2103 const_offset % 16 / 4,
2104 const_offset % 16 / 4);
2105
2106 if (ir->type->base_type == GLSL_TYPE_BOOL) {
2107 emit_asm(ir, TGSI_OPCODE_USNE, result_dst, cbuf, st_src_reg_for_int(0));
2108 } else {
2109 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, cbuf);
2110 }
2111 break;
2112 }
2113 case ir_triop_lrp:
2114 /* note: we have to reorder the three args here */
2115 emit_asm(ir, TGSI_OPCODE_LRP, result_dst, op[2], op[1], op[0]);
2116 break;
2117 case ir_triop_csel:
2118 if (this->ctx->Const.NativeIntegers)
2119 emit_asm(ir, TGSI_OPCODE_UCMP, result_dst, op[0], op[1], op[2]);
2120 else {
2121 op[0].negate = ~op[0].negate;
2122 emit_asm(ir, TGSI_OPCODE_CMP, result_dst, op[0], op[1], op[2]);
2123 }
2124 break;
2125 case ir_triop_bitfield_extract:
2126 emit_asm(ir, TGSI_OPCODE_IBFE, result_dst, op[0], op[1], op[2]);
2127 break;
2128 case ir_quadop_bitfield_insert:
2129 emit_asm(ir, TGSI_OPCODE_BFI, result_dst, op[0], op[1], op[2], op[3]);
2130 break;
2131 case ir_unop_bitfield_reverse:
2132 emit_asm(ir, TGSI_OPCODE_BREV, result_dst, op[0]);
2133 break;
2134 case ir_unop_bit_count:
2135 emit_asm(ir, TGSI_OPCODE_POPC, result_dst, op[0]);
2136 break;
2137 case ir_unop_find_msb:
2138 emit_asm(ir, TGSI_OPCODE_IMSB, result_dst, op[0]);
2139 break;
2140 case ir_unop_find_lsb:
2141 emit_asm(ir, TGSI_OPCODE_LSB, result_dst, op[0]);
2142 break;
2143 case ir_binop_imul_high:
2144 emit_asm(ir, TGSI_OPCODE_IMUL_HI, result_dst, op[0], op[1]);
2145 break;
2146 case ir_triop_fma:
2147 /* In theory, MAD is incorrect here. */
2148 if (have_fma)
2149 emit_asm(ir, TGSI_OPCODE_FMA, result_dst, op[0], op[1], op[2]);
2150 else
2151 emit_asm(ir, TGSI_OPCODE_MAD, result_dst, op[0], op[1], op[2]);
2152 break;
2153 case ir_unop_interpolate_at_centroid:
2154 emit_asm(ir, TGSI_OPCODE_INTERP_CENTROID, result_dst, op[0]);
2155 break;
2156 case ir_binop_interpolate_at_offset: {
2157 /* The y coordinate needs to be flipped for the default fb */
2158 static const gl_state_index transform_y_state[STATE_LENGTH]
2159 = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM };
2160
2161 unsigned transform_y_index =
2162 _mesa_add_state_reference(this->prog->Parameters,
2163 transform_y_state);
2164
2165 st_src_reg transform_y = st_src_reg(PROGRAM_STATE_VAR,
2166 transform_y_index,
2167 glsl_type::vec4_type);
2168 transform_y.swizzle = SWIZZLE_XXXX;
2169
2170 st_src_reg temp = get_temp(glsl_type::vec2_type);
2171 st_dst_reg temp_dst = st_dst_reg(temp);
2172
2173 emit_asm(ir, TGSI_OPCODE_MOV, temp_dst, op[1]);
2174 temp_dst.writemask = WRITEMASK_Y;
2175 emit_asm(ir, TGSI_OPCODE_MUL, temp_dst, transform_y, op[1]);
2176 emit_asm(ir, TGSI_OPCODE_INTERP_OFFSET, result_dst, op[0], temp);
2177 break;
2178 }
2179 case ir_binop_interpolate_at_sample:
2180 emit_asm(ir, TGSI_OPCODE_INTERP_SAMPLE, result_dst, op[0], op[1]);
2181 break;
2182
2183 case ir_unop_d2f:
2184 emit_asm(ir, TGSI_OPCODE_D2F, result_dst, op[0]);
2185 break;
2186 case ir_unop_f2d:
2187 emit_asm(ir, TGSI_OPCODE_F2D, result_dst, op[0]);
2188 break;
2189 case ir_unop_d2i:
2190 emit_asm(ir, TGSI_OPCODE_D2I, result_dst, op[0]);
2191 break;
2192 case ir_unop_i2d:
2193 emit_asm(ir, TGSI_OPCODE_I2D, result_dst, op[0]);
2194 break;
2195 case ir_unop_d2u:
2196 emit_asm(ir, TGSI_OPCODE_D2U, result_dst, op[0]);
2197 break;
2198 case ir_unop_u2d:
2199 emit_asm(ir, TGSI_OPCODE_U2D, result_dst, op[0]);
2200 break;
2201 case ir_unop_unpack_double_2x32:
2202 case ir_unop_pack_double_2x32:
2203 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, op[0]);
2204 break;
2205
2206 case ir_binop_ldexp:
2207 if (ir->operands[0]->type->base_type == GLSL_TYPE_DOUBLE) {
2208 emit_asm(ir, TGSI_OPCODE_DLDEXP, result_dst, op[0], op[1]);
2209 } else {
2210 assert(!"Invalid ldexp for non-double opcode in glsl_to_tgsi_visitor::visit()");
2211 }
2212 break;
2213
2214 case ir_unop_pack_half_2x16:
2215 emit_asm(ir, TGSI_OPCODE_PK2H, result_dst, op[0]);
2216 break;
2217 case ir_unop_unpack_half_2x16:
2218 emit_asm(ir, TGSI_OPCODE_UP2H, result_dst, op[0]);
2219 break;
2220
2221 case ir_unop_get_buffer_size: {
2222 ir_constant *const_offset = ir->operands[0]->as_constant();
2223 st_src_reg buffer(
2224 PROGRAM_BUFFER,
2225 ctx->Const.Program[shader->Stage].MaxAtomicBuffers +
2226 (const_offset ? const_offset->value.u[0] : 0),
2227 GLSL_TYPE_UINT);
2228 if (!const_offset) {
2229 buffer.reladdr = ralloc(mem_ctx, st_src_reg);
2230 *buffer.reladdr = op[0];
2231 emit_arl(ir, sampler_reladdr, op[0]);
2232 }
2233 emit_asm(ir, TGSI_OPCODE_RESQ, result_dst)->buffer = buffer;
2234 break;
2235 }
2236
2237 case ir_unop_vote_any:
2238 emit_asm(ir, TGSI_OPCODE_VOTE_ANY, result_dst, op[0]);
2239 break;
2240 case ir_unop_vote_all:
2241 emit_asm(ir, TGSI_OPCODE_VOTE_ALL, result_dst, op[0]);
2242 break;
2243 case ir_unop_vote_eq:
2244 emit_asm(ir, TGSI_OPCODE_VOTE_EQ, result_dst, op[0]);
2245 break;
2246
2247 case ir_unop_pack_snorm_2x16:
2248 case ir_unop_pack_unorm_2x16:
2249 case ir_unop_pack_snorm_4x8:
2250 case ir_unop_pack_unorm_4x8:
2251
2252 case ir_unop_unpack_snorm_2x16:
2253 case ir_unop_unpack_unorm_2x16:
2254 case ir_unop_unpack_snorm_4x8:
2255 case ir_unop_unpack_unorm_4x8:
2256
2257 case ir_quadop_vector:
2258 case ir_binop_vector_extract:
2259 case ir_triop_vector_insert:
2260 case ir_binop_carry:
2261 case ir_binop_borrow:
2262 case ir_unop_ssbo_unsized_array_length:
2263 /* This operation is not supported, or should have already been handled.
2264 */
2265 assert(!"Invalid ir opcode in glsl_to_tgsi_visitor::visit()");
2266 break;
2267 }
2268
2269 this->result = result_src;
2270 }
2271
2272
2273 void
2274 glsl_to_tgsi_visitor::visit(ir_swizzle *ir)
2275 {
2276 st_src_reg src;
2277 int i;
2278 int swizzle[4];
2279
2280 /* Note that this is only swizzles in expressions, not those on the left
2281 * hand side of an assignment, which do write masking. See ir_assignment
2282 * for that.
2283 */
2284
2285 ir->val->accept(this);
2286 src = this->result;
2287 assert(src.file != PROGRAM_UNDEFINED);
2288 assert(ir->type->vector_elements > 0);
2289
2290 for (i = 0; i < 4; i++) {
2291 if (i < ir->type->vector_elements) {
2292 switch (i) {
2293 case 0:
2294 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.x);
2295 break;
2296 case 1:
2297 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.y);
2298 break;
2299 case 2:
2300 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.z);
2301 break;
2302 case 3:
2303 swizzle[i] = GET_SWZ(src.swizzle, ir->mask.w);
2304 break;
2305 }
2306 } else {
2307 /* If the type is smaller than a vec4, replicate the last
2308 * channel out.
2309 */
2310 swizzle[i] = swizzle[ir->type->vector_elements - 1];
2311 }
2312 }
2313
2314 src.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1], swizzle[2], swizzle[3]);
2315
2316 this->result = src;
2317 }
2318
2319 /* Test if the variable is an array. Note that geometry and
2320 * tessellation shader inputs are outputs are always arrays (except
2321 * for patch inputs), so only the array element type is considered.
2322 */
2323 static bool
2324 is_inout_array(unsigned stage, ir_variable *var, bool *is_2d)
2325 {
2326 const glsl_type *type = var->type;
2327
2328 if ((stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
2329 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out))
2330 return false;
2331
2332 *is_2d = false;
2333
2334 if (((stage == MESA_SHADER_GEOMETRY && var->data.mode == ir_var_shader_in) ||
2335 (stage == MESA_SHADER_TESS_EVAL && var->data.mode == ir_var_shader_in) ||
2336 stage == MESA_SHADER_TESS_CTRL) &&
2337 !var->data.patch) {
2338 if (!var->type->is_array())
2339 return false; /* a system value probably */
2340
2341 type = var->type->fields.array;
2342 *is_2d = true;
2343 }
2344
2345 return type->is_array() || type->is_matrix();
2346 }
2347
2348 void
2349 glsl_to_tgsi_visitor::visit(ir_dereference_variable *ir)
2350 {
2351 variable_storage *entry = find_variable_storage(ir->var);
2352 ir_variable *var = ir->var;
2353 bool is_2d;
2354
2355 if (!entry) {
2356 switch (var->data.mode) {
2357 case ir_var_uniform:
2358 entry = new(mem_ctx) variable_storage(var, PROGRAM_UNIFORM,
2359 var->data.param_index);
2360 this->variables.push_tail(entry);
2361 break;
2362 case ir_var_shader_in:
2363 /* The linker assigns locations for varyings and attributes,
2364 * including deprecated builtins (like gl_Color), user-assign
2365 * generic attributes (glBindVertexLocation), and
2366 * user-defined varyings.
2367 */
2368 assert(var->data.location != -1);
2369
2370 if (is_inout_array(shader->Stage, var, &is_2d)) {
2371 struct array_decl *decl = &input_arrays[num_input_arrays];
2372
2373 decl->mesa_index = var->data.location;
2374 decl->array_id = num_input_arrays + 1;
2375 if (is_2d) {
2376 decl->array_size = type_size(var->type->fields.array);
2377 decl->array_type = var->type->fields.array->without_array()->base_type;
2378 } else {
2379 decl->array_size = type_size(var->type);
2380 decl->array_type = var->type->without_array()->base_type;
2381 }
2382 num_input_arrays++;
2383
2384 entry = new(mem_ctx) variable_storage(var,
2385 PROGRAM_INPUT,
2386 var->data.location,
2387 decl->array_id);
2388 }
2389 else {
2390 entry = new(mem_ctx) variable_storage(var,
2391 PROGRAM_INPUT,
2392 var->data.location);
2393 }
2394 this->variables.push_tail(entry);
2395 break;
2396 case ir_var_shader_out:
2397 assert(var->data.location != -1);
2398
2399 if (is_inout_array(shader->Stage, var, &is_2d)) {
2400 struct array_decl *decl = &output_arrays[num_output_arrays];
2401
2402 decl->mesa_index = var->data.location;
2403 decl->array_id = num_output_arrays + 1;
2404 if (is_2d) {
2405 decl->array_size = type_size(var->type->fields.array);
2406 decl->array_type = var->type->fields.array->without_array()->base_type;
2407 } else {
2408 decl->array_size = type_size(var->type);
2409 decl->array_type = var->type->without_array()->base_type;
2410 }
2411 num_output_arrays++;
2412
2413 entry = new(mem_ctx) variable_storage(var,
2414 PROGRAM_OUTPUT,
2415 var->data.location,
2416 decl->array_id);
2417 }
2418 else {
2419 entry = new(mem_ctx) variable_storage(var,
2420 PROGRAM_OUTPUT,
2421 var->data.location
2422 + FRAG_RESULT_MAX *
2423 var->data.index);
2424 }
2425 this->variables.push_tail(entry);
2426 break;
2427 case ir_var_system_value:
2428 entry = new(mem_ctx) variable_storage(var,
2429 PROGRAM_SYSTEM_VALUE,
2430 var->data.location);
2431 break;
2432 case ir_var_auto:
2433 case ir_var_temporary:
2434 st_src_reg src = get_temp(var->type);
2435
2436 entry = new(mem_ctx) variable_storage(var, src.file, src.index);
2437 this->variables.push_tail(entry);
2438
2439 break;
2440 }
2441
2442 if (!entry) {
2443 printf("Failed to make storage for %s\n", var->name);
2444 exit(1);
2445 }
2446 }
2447
2448 this->result = st_src_reg(entry->file, entry->index, var->type);
2449 this->result.array_id = entry->array_id;
2450 if (this->shader->Stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in && var->type->is_double())
2451 this->result.is_double_vertex_input = true;
2452 if (!native_integers)
2453 this->result.type = GLSL_TYPE_FLOAT;
2454 }
2455
2456 static void
2457 shrink_array_declarations(struct array_decl *arrays, unsigned count,
2458 GLbitfield64 usage_mask,
2459 GLbitfield64 double_usage_mask,
2460 GLbitfield patch_usage_mask)
2461 {
2462 unsigned i;
2463 int j;
2464
2465 /* Fix array declarations by removing unused array elements at both ends
2466 * of the arrays. For example, mat4[3] where only mat[1] is used.
2467 */
2468 for (i = 0; i < count; i++) {
2469 struct array_decl *decl = &arrays[i];
2470
2471 /* Shrink the beginning. */
2472 for (j = 0; j < (int)decl->array_size; j++) {
2473 if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2474 if (patch_usage_mask &
2475 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2476 break;
2477 }
2478 else {
2479 if (usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2480 break;
2481 if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2482 break;
2483 }
2484
2485 decl->mesa_index++;
2486 decl->array_size--;
2487 j--;
2488 }
2489
2490 /* Shrink the end. */
2491 for (j = decl->array_size-1; j >= 0; j--) {
2492 if (decl->mesa_index >= VARYING_SLOT_PATCH0) {
2493 if (patch_usage_mask &
2494 BITFIELD64_BIT(decl->mesa_index - VARYING_SLOT_PATCH0 + j))
2495 break;
2496 }
2497 else {
2498 if (usage_mask & BITFIELD64_BIT(decl->mesa_index+j))
2499 break;
2500 if (double_usage_mask & BITFIELD64_BIT(decl->mesa_index+j-1))
2501 break;
2502 }
2503
2504 decl->array_size--;
2505 }
2506 }
2507 }
2508
2509 void
2510 glsl_to_tgsi_visitor::visit(ir_dereference_array *ir)
2511 {
2512 ir_constant *index;
2513 st_src_reg src;
2514 int element_size = type_size(ir->type);
2515 bool is_2D = false;
2516
2517 index = ir->array_index->constant_expression_value();
2518
2519 ir->array->accept(this);
2520 src = this->result;
2521
2522 if (ir->array->ir_type != ir_type_dereference_array) {
2523 switch (this->prog->Target) {
2524 case GL_TESS_CONTROL_PROGRAM_NV:
2525 is_2D = (src.file == PROGRAM_INPUT || src.file == PROGRAM_OUTPUT) &&
2526 !ir->variable_referenced()->data.patch;
2527 break;
2528 case GL_TESS_EVALUATION_PROGRAM_NV:
2529 is_2D = src.file == PROGRAM_INPUT &&
2530 !ir->variable_referenced()->data.patch;
2531 break;
2532 case GL_GEOMETRY_PROGRAM_NV:
2533 is_2D = src.file == PROGRAM_INPUT;
2534 break;
2535 }
2536 }
2537
2538 if (is_2D)
2539 element_size = 1;
2540
2541 if (index) {
2542
2543 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
2544 src.file == PROGRAM_INPUT)
2545 element_size = attrib_type_size(ir->type, true);
2546 if (is_2D) {
2547 src.index2D = index->value.i[0];
2548 src.has_index2 = true;
2549 } else
2550 src.index += index->value.i[0] * element_size;
2551 } else {
2552 /* Variable index array dereference. It eats the "vec4" of the
2553 * base of the array and an index that offsets the TGSI register
2554 * index.
2555 */
2556 ir->array_index->accept(this);
2557
2558 st_src_reg index_reg;
2559
2560 if (element_size == 1) {
2561 index_reg = this->result;
2562 } else {
2563 index_reg = get_temp(native_integers ?
2564 glsl_type::int_type : glsl_type::float_type);
2565
2566 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(index_reg),
2567 this->result, st_src_reg_for_type(index_reg.type, element_size));
2568 }
2569
2570 /* If there was already a relative address register involved, add the
2571 * new and the old together to get the new offset.
2572 */
2573 if (!is_2D && src.reladdr != NULL) {
2574 st_src_reg accum_reg = get_temp(native_integers ?
2575 glsl_type::int_type : glsl_type::float_type);
2576
2577 emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(accum_reg),
2578 index_reg, *src.reladdr);
2579
2580 index_reg = accum_reg;
2581 }
2582
2583 if (is_2D) {
2584 src.reladdr2 = ralloc(mem_ctx, st_src_reg);
2585 memcpy(src.reladdr2, &index_reg, sizeof(index_reg));
2586 src.index2D = 0;
2587 src.has_index2 = true;
2588 } else {
2589 src.reladdr = ralloc(mem_ctx, st_src_reg);
2590 memcpy(src.reladdr, &index_reg, sizeof(index_reg));
2591 }
2592 }
2593
2594 /* If the type is smaller than a vec4, replicate the last channel out. */
2595 if (ir->type->is_scalar() || ir->type->is_vector())
2596 src.swizzle = swizzle_for_size(ir->type->vector_elements);
2597 else
2598 src.swizzle = SWIZZLE_NOOP;
2599
2600 /* Change the register type to the element type of the array. */
2601 src.type = ir->type->base_type;
2602
2603 this->result = src;
2604 }
2605
2606 void
2607 glsl_to_tgsi_visitor::visit(ir_dereference_record *ir)
2608 {
2609 unsigned int i;
2610 const glsl_type *struct_type = ir->record->type;
2611 int offset = 0;
2612
2613 ir->record->accept(this);
2614
2615 for (i = 0; i < struct_type->length; i++) {
2616 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
2617 break;
2618 offset += type_size(struct_type->fields.structure[i].type);
2619 }
2620
2621 /* If the type is smaller than a vec4, replicate the last channel out. */
2622 if (ir->type->is_scalar() || ir->type->is_vector())
2623 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
2624 else
2625 this->result.swizzle = SWIZZLE_NOOP;
2626
2627 this->result.index += offset;
2628 this->result.type = ir->type->base_type;
2629 }
2630
2631 /**
2632 * We want to be careful in assignment setup to hit the actual storage
2633 * instead of potentially using a temporary like we might with the
2634 * ir_dereference handler.
2635 */
2636 static st_dst_reg
2637 get_assignment_lhs(ir_dereference *ir, glsl_to_tgsi_visitor *v)
2638 {
2639 /* The LHS must be a dereference. If the LHS is a variable indexed array
2640 * access of a vector, it must be separated into a series conditional moves
2641 * before reaching this point (see ir_vec_index_to_cond_assign).
2642 */
2643 assert(ir->as_dereference());
2644 ir_dereference_array *deref_array = ir->as_dereference_array();
2645 if (deref_array) {
2646 assert(!deref_array->array->type->is_vector());
2647 }
2648
2649 /* Use the rvalue deref handler for the most part. We'll ignore
2650 * swizzles in it and write swizzles using writemask, though.
2651 */
2652 ir->accept(v);
2653 return st_dst_reg(v->result);
2654 }
2655
2656 /**
2657 * Process the condition of a conditional assignment
2658 *
2659 * Examines the condition of a conditional assignment to generate the optimal
2660 * first operand of a \c CMP instruction. If the condition is a relational
2661 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
2662 * used as the source for the \c CMP instruction. Otherwise the comparison
2663 * is processed to a boolean result, and the boolean result is used as the
2664 * operand to the CMP instruction.
2665 */
2666 bool
2667 glsl_to_tgsi_visitor::process_move_condition(ir_rvalue *ir)
2668 {
2669 ir_rvalue *src_ir = ir;
2670 bool negate = true;
2671 bool switch_order = false;
2672
2673 ir_expression *const expr = ir->as_expression();
2674
2675 if (native_integers) {
2676 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2677 enum glsl_base_type type = expr->operands[0]->type->base_type;
2678 if (type == GLSL_TYPE_INT || type == GLSL_TYPE_UINT ||
2679 type == GLSL_TYPE_BOOL) {
2680 if (expr->operation == ir_binop_equal) {
2681 if (expr->operands[0]->is_zero()) {
2682 src_ir = expr->operands[1];
2683 switch_order = true;
2684 }
2685 else if (expr->operands[1]->is_zero()) {
2686 src_ir = expr->operands[0];
2687 switch_order = true;
2688 }
2689 }
2690 else if (expr->operation == ir_binop_nequal) {
2691 if (expr->operands[0]->is_zero()) {
2692 src_ir = expr->operands[1];
2693 }
2694 else if (expr->operands[1]->is_zero()) {
2695 src_ir = expr->operands[0];
2696 }
2697 }
2698 }
2699 }
2700
2701 src_ir->accept(this);
2702 return switch_order;
2703 }
2704
2705 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
2706 bool zero_on_left = false;
2707
2708 if (expr->operands[0]->is_zero()) {
2709 src_ir = expr->operands[1];
2710 zero_on_left = true;
2711 } else if (expr->operands[1]->is_zero()) {
2712 src_ir = expr->operands[0];
2713 zero_on_left = false;
2714 }
2715
2716 /* a is - 0 + - 0 +
2717 * (a < 0) T F F ( a < 0) T F F
2718 * (0 < a) F F T (-a < 0) F F T
2719 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
2720 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
2721 * (a > 0) F F T (-a < 0) F F T
2722 * (0 > a) T F F ( a < 0) T F F
2723 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
2724 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
2725 *
2726 * Note that exchanging the order of 0 and 'a' in the comparison simply
2727 * means that the value of 'a' should be negated.
2728 */
2729 if (src_ir != ir) {
2730 switch (expr->operation) {
2731 case ir_binop_less:
2732 switch_order = false;
2733 negate = zero_on_left;
2734 break;
2735
2736 case ir_binop_greater:
2737 switch_order = false;
2738 negate = !zero_on_left;
2739 break;
2740
2741 case ir_binop_lequal:
2742 switch_order = true;
2743 negate = !zero_on_left;
2744 break;
2745
2746 case ir_binop_gequal:
2747 switch_order = true;
2748 negate = zero_on_left;
2749 break;
2750
2751 default:
2752 /* This isn't the right kind of comparison afterall, so make sure
2753 * the whole condition is visited.
2754 */
2755 src_ir = ir;
2756 break;
2757 }
2758 }
2759 }
2760
2761 src_ir->accept(this);
2762
2763 /* We use the TGSI_OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
2764 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
2765 * choose which value TGSI_OPCODE_CMP produces without an extra instruction
2766 * computing the condition.
2767 */
2768 if (negate)
2769 this->result.negate = ~this->result.negate;
2770
2771 return switch_order;
2772 }
2773
2774 void
2775 glsl_to_tgsi_visitor::emit_block_mov(ir_assignment *ir, const struct glsl_type *type,
2776 st_dst_reg *l, st_src_reg *r,
2777 st_src_reg *cond, bool cond_swap)
2778 {
2779 if (type->base_type == GLSL_TYPE_STRUCT) {
2780 for (unsigned int i = 0; i < type->length; i++) {
2781 emit_block_mov(ir, type->fields.structure[i].type, l, r,
2782 cond, cond_swap);
2783 }
2784 return;
2785 }
2786
2787 if (type->is_array()) {
2788 for (unsigned int i = 0; i < type->length; i++) {
2789 emit_block_mov(ir, type->fields.array, l, r, cond, cond_swap);
2790 }
2791 return;
2792 }
2793
2794 if (type->is_matrix()) {
2795 const struct glsl_type *vec_type;
2796
2797 vec_type = glsl_type::get_instance(type->is_double() ? GLSL_TYPE_DOUBLE : GLSL_TYPE_FLOAT,
2798 type->vector_elements, 1);
2799
2800 for (int i = 0; i < type->matrix_columns; i++) {
2801 emit_block_mov(ir, vec_type, l, r, cond, cond_swap);
2802 }
2803 return;
2804 }
2805
2806 assert(type->is_scalar() || type->is_vector());
2807
2808 r->type = type->base_type;
2809 if (cond) {
2810 st_src_reg l_src = st_src_reg(*l);
2811 l_src.swizzle = swizzle_for_size(type->vector_elements);
2812
2813 if (native_integers) {
2814 emit_asm(ir, TGSI_OPCODE_UCMP, *l, *cond,
2815 cond_swap ? l_src : *r,
2816 cond_swap ? *r : l_src);
2817 } else {
2818 emit_asm(ir, TGSI_OPCODE_CMP, *l, *cond,
2819 cond_swap ? l_src : *r,
2820 cond_swap ? *r : l_src);
2821 }
2822 } else {
2823 emit_asm(ir, TGSI_OPCODE_MOV, *l, *r);
2824 }
2825 l->index++;
2826 r->index++;
2827 if (type->is_dual_slot()) {
2828 l->index++;
2829 if (r->is_double_vertex_input == false)
2830 r->index++;
2831 }
2832 }
2833
2834 void
2835 glsl_to_tgsi_visitor::visit(ir_assignment *ir)
2836 {
2837 st_dst_reg l;
2838 st_src_reg r;
2839
2840 ir->rhs->accept(this);
2841 r = this->result;
2842
2843 l = get_assignment_lhs(ir->lhs, this);
2844
2845 /* FINISHME: This should really set to the correct maximal writemask for each
2846 * FINISHME: component written (in the loops below). This case can only
2847 * FINISHME: occur for matrices, arrays, and structures.
2848 */
2849 if (ir->write_mask == 0) {
2850 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
2851
2852 if (ir->lhs->type->is_array() || ir->lhs->type->without_array()->is_matrix()) {
2853 if (ir->lhs->type->without_array()->is_64bit()) {
2854 switch (ir->lhs->type->without_array()->vector_elements) {
2855 case 1:
2856 l.writemask = WRITEMASK_X;
2857 break;
2858 case 2:
2859 l.writemask = WRITEMASK_XY;
2860 break;
2861 case 3:
2862 l.writemask = WRITEMASK_XYZ;
2863 break;
2864 case 4:
2865 l.writemask = WRITEMASK_XYZW;
2866 break;
2867 }
2868 } else
2869 l.writemask = WRITEMASK_XYZW;
2870 }
2871 } else if (ir->lhs->type->is_scalar() &&
2872 !ir->lhs->type->is_64bit() &&
2873 ir->lhs->variable_referenced()->data.mode == ir_var_shader_out) {
2874 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
2875 * FINISHME: W component of fragment shader output zero, work correctly.
2876 */
2877 l.writemask = WRITEMASK_XYZW;
2878 } else {
2879 int swizzles[4];
2880 int first_enabled_chan = 0;
2881 int rhs_chan = 0;
2882
2883 l.writemask = ir->write_mask;
2884
2885 for (int i = 0; i < 4; i++) {
2886 if (l.writemask & (1 << i)) {
2887 first_enabled_chan = GET_SWZ(r.swizzle, i);
2888 break;
2889 }
2890 }
2891
2892 /* Swizzle a small RHS vector into the channels being written.
2893 *
2894 * glsl ir treats write_mask as dictating how many channels are
2895 * present on the RHS while TGSI treats write_mask as just
2896 * showing which channels of the vec4 RHS get written.
2897 */
2898 for (int i = 0; i < 4; i++) {
2899 if (l.writemask & (1 << i))
2900 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
2901 else
2902 swizzles[i] = first_enabled_chan;
2903 }
2904 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
2905 swizzles[2], swizzles[3]);
2906 }
2907
2908 assert(l.file != PROGRAM_UNDEFINED);
2909 assert(r.file != PROGRAM_UNDEFINED);
2910
2911 if (ir->condition) {
2912 const bool switch_order = this->process_move_condition(ir->condition);
2913 st_src_reg condition = this->result;
2914
2915 emit_block_mov(ir, ir->lhs->type, &l, &r, &condition, switch_order);
2916 } else if (ir->rhs->as_expression() &&
2917 this->instructions.get_tail() &&
2918 ir->rhs == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->ir &&
2919 type_size(ir->lhs->type) == 1 &&
2920 l.writemask == ((glsl_to_tgsi_instruction *)this->instructions.get_tail())->dst[0].writemask) {
2921 /* To avoid emitting an extra MOV when assigning an expression to a
2922 * variable, emit the last instruction of the expression again, but
2923 * replace the destination register with the target of the assignment.
2924 * Dead code elimination will remove the original instruction.
2925 */
2926 glsl_to_tgsi_instruction *inst, *new_inst;
2927 inst = (glsl_to_tgsi_instruction *)this->instructions.get_tail();
2928 new_inst = emit_asm(ir, inst->op, l, inst->src[0], inst->src[1], inst->src[2], inst->src[3]);
2929 new_inst->saturate = inst->saturate;
2930 inst->dead_mask = inst->dst[0].writemask;
2931 } else {
2932 emit_block_mov(ir, ir->rhs->type, &l, &r, NULL, false);
2933 }
2934 }
2935
2936
2937 void
2938 glsl_to_tgsi_visitor::visit(ir_constant *ir)
2939 {
2940 st_src_reg src;
2941 GLdouble stack_vals[4] = { 0 };
2942 gl_constant_value *values = (gl_constant_value *) stack_vals;
2943 GLenum gl_type = GL_NONE;
2944 unsigned int i;
2945 static int in_array = 0;
2946 gl_register_file file = in_array ? PROGRAM_CONSTANT : PROGRAM_IMMEDIATE;
2947
2948 /* Unfortunately, 4 floats is all we can get into
2949 * _mesa_add_typed_unnamed_constant. So, make a temp to store an
2950 * aggregate constant and move each constant value into it. If we
2951 * get lucky, copy propagation will eliminate the extra moves.
2952 */
2953 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
2954 st_src_reg temp_base = get_temp(ir->type);
2955 st_dst_reg temp = st_dst_reg(temp_base);
2956
2957 foreach_in_list(ir_constant, field_value, &ir->components) {
2958 int size = type_size(field_value->type);
2959
2960 assert(size > 0);
2961
2962 field_value->accept(this);
2963 src = this->result;
2964
2965 for (i = 0; i < (unsigned int)size; i++) {
2966 emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
2967
2968 src.index++;
2969 temp.index++;
2970 }
2971 }
2972 this->result = temp_base;
2973 return;
2974 }
2975
2976 if (ir->type->is_array()) {
2977 st_src_reg temp_base = get_temp(ir->type);
2978 st_dst_reg temp = st_dst_reg(temp_base);
2979 int size = type_size(ir->type->fields.array);
2980
2981 assert(size > 0);
2982 in_array++;
2983
2984 for (i = 0; i < ir->type->length; i++) {
2985 ir->array_elements[i]->accept(this);
2986 src = this->result;
2987 for (int j = 0; j < size; j++) {
2988 emit_asm(ir, TGSI_OPCODE_MOV, temp, src);
2989
2990 src.index++;
2991 temp.index++;
2992 }
2993 }
2994 this->result = temp_base;
2995 in_array--;
2996 return;
2997 }
2998
2999 if (ir->type->is_matrix()) {
3000 st_src_reg mat = get_temp(ir->type);
3001 st_dst_reg mat_column = st_dst_reg(mat);
3002
3003 for (i = 0; i < ir->type->matrix_columns; i++) {
3004 switch (ir->type->base_type) {
3005 case GLSL_TYPE_FLOAT:
3006 values = (gl_constant_value *) &ir->value.f[i * ir->type->vector_elements];
3007
3008 src = st_src_reg(file, -1, ir->type->base_type);
3009 src.index = add_constant(file,
3010 values,
3011 ir->type->vector_elements,
3012 GL_FLOAT,
3013 &src.swizzle);
3014 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3015 break;
3016 case GLSL_TYPE_DOUBLE:
3017 values = (gl_constant_value *) &ir->value.d[i * ir->type->vector_elements];
3018 src = st_src_reg(file, -1, ir->type->base_type);
3019 src.index = add_constant(file,
3020 values,
3021 ir->type->vector_elements,
3022 GL_DOUBLE,
3023 &src.swizzle);
3024 if (ir->type->vector_elements >= 2) {
3025 mat_column.writemask = WRITEMASK_XY;
3026 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
3027 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3028 } else {
3029 mat_column.writemask = WRITEMASK_X;
3030 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X);
3031 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3032 }
3033 src.index++;
3034 if (ir->type->vector_elements > 2) {
3035 if (ir->type->vector_elements == 4) {
3036 mat_column.writemask = WRITEMASK_ZW;
3037 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_Y);
3038 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3039 } else {
3040 mat_column.writemask = WRITEMASK_Z;
3041 src.swizzle = MAKE_SWIZZLE4(SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y);
3042 emit_asm(ir, TGSI_OPCODE_MOV, mat_column, src);
3043 mat_column.writemask = WRITEMASK_XYZW;
3044 src.swizzle = SWIZZLE_XYZW;
3045 }
3046 mat_column.index++;
3047 }
3048 break;
3049 default:
3050 unreachable("Illegal matrix constant type.\n");
3051 break;
3052 }
3053 mat_column.index++;
3054 }
3055 this->result = mat;
3056 return;
3057 }
3058
3059 switch (ir->type->base_type) {
3060 case GLSL_TYPE_FLOAT:
3061 gl_type = GL_FLOAT;
3062 for (i = 0; i < ir->type->vector_elements; i++) {
3063 values[i].f = ir->value.f[i];
3064 }
3065 break;
3066 case GLSL_TYPE_DOUBLE:
3067 gl_type = GL_DOUBLE;
3068 for (i = 0; i < ir->type->vector_elements; i++) {
3069 memcpy(&values[i * 2], &ir->value.d[i], sizeof(double));
3070 }
3071 break;
3072 case GLSL_TYPE_UINT:
3073 gl_type = native_integers ? GL_UNSIGNED_INT : GL_FLOAT;
3074 for (i = 0; i < ir->type->vector_elements; i++) {
3075 if (native_integers)
3076 values[i].u = ir->value.u[i];
3077 else
3078 values[i].f = ir->value.u[i];
3079 }
3080 break;
3081 case GLSL_TYPE_INT:
3082 gl_type = native_integers ? GL_INT : GL_FLOAT;
3083 for (i = 0; i < ir->type->vector_elements; i++) {
3084 if (native_integers)
3085 values[i].i = ir->value.i[i];
3086 else
3087 values[i].f = ir->value.i[i];
3088 }
3089 break;
3090 case GLSL_TYPE_BOOL:
3091 gl_type = native_integers ? GL_BOOL : GL_FLOAT;
3092 for (i = 0; i < ir->type->vector_elements; i++) {
3093 values[i].u = ir->value.b[i] ? ctx->Const.UniformBooleanTrue : 0;
3094 }
3095 break;
3096 default:
3097 assert(!"Non-float/uint/int/bool constant");
3098 }
3099
3100 this->result = st_src_reg(file, -1, ir->type);
3101 this->result.index = add_constant(file,
3102 values,
3103 ir->type->vector_elements,
3104 gl_type,
3105 &this->result.swizzle);
3106 }
3107
3108 function_entry *
3109 glsl_to_tgsi_visitor::get_function_signature(ir_function_signature *sig)
3110 {
3111 foreach_in_list_use_after(function_entry, entry, &this->function_signatures) {
3112 if (entry->sig == sig)
3113 return entry;
3114 }
3115
3116 entry = ralloc(mem_ctx, function_entry);
3117 entry->sig = sig;
3118 entry->sig_id = this->next_signature_id++;
3119 entry->bgn_inst = NULL;
3120
3121 /* Allocate storage for all the parameters. */
3122 foreach_in_list(ir_variable, param, &sig->parameters) {
3123 variable_storage *storage;
3124
3125 storage = find_variable_storage(param);
3126 assert(!storage);
3127
3128 st_src_reg src = get_temp(param->type);
3129
3130 storage = new(mem_ctx) variable_storage(param, src.file, src.index);
3131 this->variables.push_tail(storage);
3132 }
3133
3134 if (!sig->return_type->is_void()) {
3135 entry->return_reg = get_temp(sig->return_type);
3136 } else {
3137 entry->return_reg = undef_src;
3138 }
3139
3140 this->function_signatures.push_tail(entry);
3141 return entry;
3142 }
3143
3144 void
3145 glsl_to_tgsi_visitor::visit_atomic_counter_intrinsic(ir_call *ir)
3146 {
3147 const char *callee = ir->callee->function_name();
3148 exec_node *param = ir->actual_parameters.get_head();
3149 ir_dereference *deref = static_cast<ir_dereference *>(param);
3150 ir_variable *location = deref->variable_referenced();
3151
3152 st_src_reg buffer(
3153 PROGRAM_BUFFER, location->data.binding, GLSL_TYPE_ATOMIC_UINT);
3154
3155 /* Calculate the surface offset */
3156 st_src_reg offset;
3157 unsigned array_size = 0, base = 0, index = 0;
3158
3159 get_deref_offsets(deref, &array_size, &base, &index, &offset);
3160
3161 if (offset.file != PROGRAM_UNDEFINED) {
3162 emit_asm(ir, TGSI_OPCODE_MUL, st_dst_reg(offset),
3163 offset, st_src_reg_for_int(ATOMIC_COUNTER_SIZE));
3164 emit_asm(ir, TGSI_OPCODE_ADD, st_dst_reg(offset),
3165 offset, st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE));
3166 } else {
3167 offset = st_src_reg_for_int(location->data.offset + index * ATOMIC_COUNTER_SIZE);
3168 }
3169
3170 ir->return_deref->accept(this);
3171 st_dst_reg dst(this->result);
3172 dst.writemask = WRITEMASK_X;
3173
3174 glsl_to_tgsi_instruction *inst;
3175
3176 if (!strcmp("__intrinsic_atomic_read", callee)) {
3177 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, offset);
3178 } else if (!strcmp("__intrinsic_atomic_increment", callee)) {
3179 inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3180 st_src_reg_for_int(1));
3181 } else if (!strcmp("__intrinsic_atomic_predecrement", callee)) {
3182 inst = emit_asm(ir, TGSI_OPCODE_ATOMUADD, dst, offset,
3183 st_src_reg_for_int(-1));
3184 emit_asm(ir, TGSI_OPCODE_ADD, dst, this->result, st_src_reg_for_int(-1));
3185 } else {
3186 param = param->get_next();
3187 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3188 val->accept(this);
3189
3190 st_src_reg data = this->result, data2 = undef_src;
3191 unsigned opcode;
3192 if (!strcmp("__intrinsic_atomic_add", callee))
3193 opcode = TGSI_OPCODE_ATOMUADD;
3194 else if (!strcmp("__intrinsic_atomic_min", callee))
3195 opcode = TGSI_OPCODE_ATOMIMIN;
3196 else if (!strcmp("__intrinsic_atomic_max", callee))
3197 opcode = TGSI_OPCODE_ATOMIMAX;
3198 else if (!strcmp("__intrinsic_atomic_and", callee))
3199 opcode = TGSI_OPCODE_ATOMAND;
3200 else if (!strcmp("__intrinsic_atomic_or", callee))
3201 opcode = TGSI_OPCODE_ATOMOR;
3202 else if (!strcmp("__intrinsic_atomic_xor", callee))
3203 opcode = TGSI_OPCODE_ATOMXOR;
3204 else if (!strcmp("__intrinsic_atomic_exchange", callee))
3205 opcode = TGSI_OPCODE_ATOMXCHG;
3206 else if (!strcmp("__intrinsic_atomic_comp_swap", callee)) {
3207 opcode = TGSI_OPCODE_ATOMCAS;
3208 param = param->get_next();
3209 val = ((ir_instruction *)param)->as_rvalue();
3210 val->accept(this);
3211 data2 = this->result;
3212 } else if (!strcmp("__intrinsic_atomic_sub", callee)) {
3213 opcode = TGSI_OPCODE_ATOMUADD;
3214 st_src_reg res = get_temp(glsl_type::uvec4_type);
3215 st_dst_reg dstres = st_dst_reg(res);
3216 dstres.writemask = dst.writemask;
3217 emit_asm(ir, TGSI_OPCODE_INEG, dstres, data);
3218 data = res;
3219 } else {
3220 assert(!"Unexpected intrinsic");
3221 return;
3222 }
3223
3224 inst = emit_asm(ir, opcode, dst, offset, data, data2);
3225 }
3226
3227 inst->buffer = buffer;
3228 }
3229
3230 void
3231 glsl_to_tgsi_visitor::visit_ssbo_intrinsic(ir_call *ir)
3232 {
3233 const char *callee = ir->callee->function_name();
3234 exec_node *param = ir->actual_parameters.get_head();
3235
3236 ir_rvalue *block = ((ir_instruction *)param)->as_rvalue();
3237
3238 param = param->get_next();
3239 ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3240
3241 ir_constant *const_block = block->as_constant();
3242
3243 st_src_reg buffer(
3244 PROGRAM_BUFFER,
3245 ctx->Const.Program[shader->Stage].MaxAtomicBuffers +
3246 (const_block ? const_block->value.u[0] : 0),
3247 GLSL_TYPE_UINT);
3248
3249 if (!const_block) {
3250 block->accept(this);
3251 buffer.reladdr = ralloc(mem_ctx, st_src_reg);
3252 *buffer.reladdr = this->result;
3253 emit_arl(ir, sampler_reladdr, this->result);
3254 }
3255
3256 /* Calculate the surface offset */
3257 offset->accept(this);
3258 st_src_reg off = this->result;
3259
3260 st_dst_reg dst = undef_dst;
3261 if (ir->return_deref) {
3262 ir->return_deref->accept(this);
3263 dst = st_dst_reg(this->result);
3264 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3265 }
3266
3267 glsl_to_tgsi_instruction *inst;
3268
3269 if (!strcmp("__intrinsic_load_ssbo", callee)) {
3270 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3271 if (dst.type == GLSL_TYPE_BOOL)
3272 emit_asm(ir, TGSI_OPCODE_USNE, dst, st_src_reg(dst), st_src_reg_for_int(0));
3273 } else if (!strcmp("__intrinsic_store_ssbo", callee)) {
3274 param = param->get_next();
3275 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3276 val->accept(this);
3277
3278 param = param->get_next();
3279 ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3280 assert(write_mask);
3281 dst.writemask = write_mask->value.u[0];
3282
3283 dst.type = this->result.type;
3284 inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3285 } else {
3286 param = param->get_next();
3287 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3288 val->accept(this);
3289
3290 st_src_reg data = this->result, data2 = undef_src;
3291 unsigned opcode;
3292 if (!strcmp("__intrinsic_atomic_add_ssbo", callee))
3293 opcode = TGSI_OPCODE_ATOMUADD;
3294 else if (!strcmp("__intrinsic_atomic_min_ssbo", callee))
3295 opcode = TGSI_OPCODE_ATOMIMIN;
3296 else if (!strcmp("__intrinsic_atomic_max_ssbo", callee))
3297 opcode = TGSI_OPCODE_ATOMIMAX;
3298 else if (!strcmp("__intrinsic_atomic_and_ssbo", callee))
3299 opcode = TGSI_OPCODE_ATOMAND;
3300 else if (!strcmp("__intrinsic_atomic_or_ssbo", callee))
3301 opcode = TGSI_OPCODE_ATOMOR;
3302 else if (!strcmp("__intrinsic_atomic_xor_ssbo", callee))
3303 opcode = TGSI_OPCODE_ATOMXOR;
3304 else if (!strcmp("__intrinsic_atomic_exchange_ssbo", callee))
3305 opcode = TGSI_OPCODE_ATOMXCHG;
3306 else if (!strcmp("__intrinsic_atomic_comp_swap_ssbo", callee)) {
3307 opcode = TGSI_OPCODE_ATOMCAS;
3308 param = param->get_next();
3309 val = ((ir_instruction *)param)->as_rvalue();
3310 val->accept(this);
3311 data2 = this->result;
3312 } else {
3313 assert(!"Unexpected intrinsic");
3314 return;
3315 }
3316
3317 inst = emit_asm(ir, opcode, dst, off, data, data2);
3318 }
3319
3320 param = param->get_next();
3321 ir_constant *access = NULL;
3322 if (!param->is_tail_sentinel()) {
3323 access = ((ir_instruction *)param)->as_constant();
3324 assert(access);
3325 }
3326
3327 /* The emit_asm() might have actually split the op into pieces, e.g. for
3328 * double stores. We have to go back and fix up all the generated ops.
3329 */
3330 unsigned op = inst->op;
3331 do {
3332 inst->buffer = buffer;
3333 if (access)
3334 inst->buffer_access = access->value.u[0];
3335 inst = (glsl_to_tgsi_instruction *)inst->get_prev();
3336 if (inst->op == TGSI_OPCODE_UADD)
3337 inst = (glsl_to_tgsi_instruction *)inst->get_prev();
3338 } while (inst && inst->op == op && inst->buffer.file == PROGRAM_UNDEFINED);
3339 }
3340
3341 void
3342 glsl_to_tgsi_visitor::visit_membar_intrinsic(ir_call *ir)
3343 {
3344 const char *callee = ir->callee->function_name();
3345
3346 if (!strcmp("__intrinsic_memory_barrier", callee))
3347 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3348 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3349 TGSI_MEMBAR_ATOMIC_BUFFER |
3350 TGSI_MEMBAR_SHADER_IMAGE |
3351 TGSI_MEMBAR_SHARED));
3352 else if (!strcmp("__intrinsic_memory_barrier_atomic_counter", callee))
3353 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3354 st_src_reg_for_int(TGSI_MEMBAR_ATOMIC_BUFFER));
3355 else if (!strcmp("__intrinsic_memory_barrier_buffer", callee))
3356 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3357 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER));
3358 else if (!strcmp("__intrinsic_memory_barrier_image", callee))
3359 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3360 st_src_reg_for_int(TGSI_MEMBAR_SHADER_IMAGE));
3361 else if (!strcmp("__intrinsic_memory_barrier_shared", callee))
3362 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3363 st_src_reg_for_int(TGSI_MEMBAR_SHARED));
3364 else if (!strcmp("__intrinsic_group_memory_barrier", callee))
3365 emit_asm(ir, TGSI_OPCODE_MEMBAR, undef_dst,
3366 st_src_reg_for_int(TGSI_MEMBAR_SHADER_BUFFER |
3367 TGSI_MEMBAR_ATOMIC_BUFFER |
3368 TGSI_MEMBAR_SHADER_IMAGE |
3369 TGSI_MEMBAR_SHARED |
3370 TGSI_MEMBAR_THREAD_GROUP));
3371 else
3372 assert(!"Unexpected memory barrier intrinsic");
3373 }
3374
3375 void
3376 glsl_to_tgsi_visitor::visit_shared_intrinsic(ir_call *ir)
3377 {
3378 const char *callee = ir->callee->function_name();
3379 exec_node *param = ir->actual_parameters.get_head();
3380
3381 ir_rvalue *offset = ((ir_instruction *)param)->as_rvalue();
3382
3383 st_src_reg buffer(PROGRAM_MEMORY, 0, GLSL_TYPE_UINT);
3384
3385 /* Calculate the surface offset */
3386 offset->accept(this);
3387 st_src_reg off = this->result;
3388
3389 st_dst_reg dst = undef_dst;
3390 if (ir->return_deref) {
3391 ir->return_deref->accept(this);
3392 dst = st_dst_reg(this->result);
3393 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3394 }
3395
3396 glsl_to_tgsi_instruction *inst;
3397
3398 if (!strcmp("__intrinsic_load_shared", callee)) {
3399 inst = emit_asm(ir, TGSI_OPCODE_LOAD, dst, off);
3400 inst->buffer = buffer;
3401 } else if (!strcmp("__intrinsic_store_shared", callee)) {
3402 param = param->get_next();
3403 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3404 val->accept(this);
3405
3406 param = param->get_next();
3407 ir_constant *write_mask = ((ir_instruction *)param)->as_constant();
3408 assert(write_mask);
3409 dst.writemask = write_mask->value.u[0];
3410
3411 dst.type = this->result.type;
3412 inst = emit_asm(ir, TGSI_OPCODE_STORE, dst, off, this->result);
3413 inst->buffer = buffer;
3414 } else {
3415 param = param->get_next();
3416 ir_rvalue *val = ((ir_instruction *)param)->as_rvalue();
3417 val->accept(this);
3418
3419 st_src_reg data = this->result, data2 = undef_src;
3420 unsigned opcode;
3421 if (!strcmp("__intrinsic_atomic_add_shared", callee))
3422 opcode = TGSI_OPCODE_ATOMUADD;
3423 else if (!strcmp("__intrinsic_atomic_min_shared", callee))
3424 opcode = TGSI_OPCODE_ATOMIMIN;
3425 else if (!strcmp("__intrinsic_atomic_max_shared", callee))
3426 opcode = TGSI_OPCODE_ATOMIMAX;
3427 else if (!strcmp("__intrinsic_atomic_and_shared", callee))
3428 opcode = TGSI_OPCODE_ATOMAND;
3429 else if (!strcmp("__intrinsic_atomic_or_shared", callee))
3430 opcode = TGSI_OPCODE_ATOMOR;
3431 else if (!strcmp("__intrinsic_atomic_xor_shared", callee))
3432 opcode = TGSI_OPCODE_ATOMXOR;
3433 else if (!strcmp("__intrinsic_atomic_exchange_shared", callee))
3434 opcode = TGSI_OPCODE_ATOMXCHG;
3435 else if (!strcmp("__intrinsic_atomic_comp_swap_shared", callee)) {
3436 opcode = TGSI_OPCODE_ATOMCAS;
3437 param = param->get_next();
3438 val = ((ir_instruction *)param)->as_rvalue();
3439 val->accept(this);
3440 data2 = this->result;
3441 } else {
3442 assert(!"Unexpected intrinsic");
3443 return;
3444 }
3445
3446 inst = emit_asm(ir, opcode, dst, off, data, data2);
3447 inst->buffer = buffer;
3448 }
3449 }
3450
3451 void
3452 glsl_to_tgsi_visitor::visit_image_intrinsic(ir_call *ir)
3453 {
3454 const char *callee = ir->callee->function_name();
3455 exec_node *param = ir->actual_parameters.get_head();
3456
3457 ir_dereference *img = (ir_dereference *)param;
3458 const ir_variable *imgvar = img->variable_referenced();
3459 const glsl_type *type = imgvar->type->without_array();
3460 unsigned sampler_array_size = 1, sampler_base = 0;
3461
3462 st_src_reg reladdr;
3463 st_src_reg image(PROGRAM_IMAGE, 0, GLSL_TYPE_UINT);
3464
3465 get_deref_offsets(img, &sampler_array_size, &sampler_base,
3466 (unsigned int *)&image.index, &reladdr);
3467 if (reladdr.file != PROGRAM_UNDEFINED) {
3468 image.reladdr = ralloc(mem_ctx, st_src_reg);
3469 *image.reladdr = reladdr;
3470 emit_arl(ir, sampler_reladdr, reladdr);
3471 }
3472
3473 st_dst_reg dst = undef_dst;
3474 if (ir->return_deref) {
3475 ir->return_deref->accept(this);
3476 dst = st_dst_reg(this->result);
3477 dst.writemask = (1 << ir->return_deref->type->vector_elements) - 1;
3478 }
3479
3480 glsl_to_tgsi_instruction *inst;
3481
3482 if (!strcmp("__intrinsic_image_size", callee)) {
3483 dst.writemask = WRITEMASK_XYZ;
3484 inst = emit_asm(ir, TGSI_OPCODE_RESQ, dst);
3485 } else if (!strcmp("__intrinsic_image_samples", callee)) {
3486 st_src_reg res = get_temp(glsl_type::ivec4_type);
3487 st_dst_reg dstres = st_dst_reg(res);
3488 dstres.writemask = WRITEMASK_W;
3489 inst = emit_asm(ir, TGSI_OPCODE_RESQ, dstres);
3490 res.swizzle = SWIZZLE_WWWW;
3491 emit_asm(ir, TGSI_OPCODE_MOV, dst, res);
3492 } else {
3493 st_src_reg arg1 = undef_src, arg2 = undef_src;
3494 st_src_reg coord;
3495 st_dst_reg coord_dst;
3496 coord = get_temp(glsl_type::ivec4_type);
3497 coord_dst = st_dst_reg(coord);
3498 coord_dst.writemask = (1 << type->coordinate_components()) - 1;
3499 param = param->get_next();
3500 ((ir_dereference *)param)->accept(this);
3501 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
3502 coord.swizzle = SWIZZLE_XXXX;
3503 switch (type->coordinate_components()) {
3504 case 4: assert(!"unexpected coord count");
3505 /* fallthrough */
3506 case 3: coord.swizzle |= SWIZZLE_Z << 6;
3507 /* fallthrough */
3508 case 2: coord.swizzle |= SWIZZLE_Y << 3;
3509 }
3510
3511 if (type->sampler_dimensionality == GLSL_SAMPLER_DIM_MS) {
3512 param = param->get_next();
3513 ((ir_dereference *)param)->accept(this);
3514 st_src_reg sample = this->result;
3515 sample.swizzle = SWIZZLE_XXXX;
3516 coord_dst.writemask = WRITEMASK_W;
3517 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample);
3518 coord.swizzle |= SWIZZLE_W << 9;
3519 }
3520
3521 param = param->get_next();
3522 if (!param->is_tail_sentinel()) {
3523 ((ir_dereference *)param)->accept(this);
3524 arg1 = this->result;
3525 param = param->get_next();
3526 }
3527
3528 if (!param->is_tail_sentinel()) {
3529 ((ir_dereference *)param)->accept(this);
3530 arg2 = this->result;
3531 param = param->get_next();
3532 }
3533
3534 assert(param->is_tail_sentinel());
3535
3536 unsigned opcode;
3537 if (!strcmp("__intrinsic_image_load", callee))
3538 opcode = TGSI_OPCODE_LOAD;
3539 else if (!strcmp("__intrinsic_image_store", callee))
3540 opcode = TGSI_OPCODE_STORE;
3541 else if (!strcmp("__intrinsic_image_atomic_add", callee))
3542 opcode = TGSI_OPCODE_ATOMUADD;
3543 else if (!strcmp("__intrinsic_image_atomic_min", callee))
3544 opcode = TGSI_OPCODE_ATOMIMIN;
3545 else if (!strcmp("__intrinsic_image_atomic_max", callee))
3546 opcode = TGSI_OPCODE_ATOMIMAX;
3547 else if (!strcmp("__intrinsic_image_atomic_and", callee))
3548 opcode = TGSI_OPCODE_ATOMAND;
3549 else if (!strcmp("__intrinsic_image_atomic_or", callee))
3550 opcode = TGSI_OPCODE_ATOMOR;
3551 else if (!strcmp("__intrinsic_image_atomic_xor", callee))
3552 opcode = TGSI_OPCODE_ATOMXOR;
3553 else if (!strcmp("__intrinsic_image_atomic_exchange", callee))
3554 opcode = TGSI_OPCODE_ATOMXCHG;
3555 else if (!strcmp("__intrinsic_image_atomic_comp_swap", callee))
3556 opcode = TGSI_OPCODE_ATOMCAS;
3557 else {
3558 assert(!"Unexpected intrinsic");
3559 return;
3560 }
3561
3562 inst = emit_asm(ir, opcode, dst, coord, arg1, arg2);
3563 if (opcode == TGSI_OPCODE_STORE)
3564 inst->dst[0].writemask = WRITEMASK_XYZW;
3565 }
3566
3567 inst->buffer = image;
3568 inst->sampler_array_size = sampler_array_size;
3569 inst->sampler_base = sampler_base;
3570
3571 switch (type->sampler_dimensionality) {
3572 case GLSL_SAMPLER_DIM_1D:
3573 inst->tex_target = (type->sampler_array)
3574 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
3575 break;
3576 case GLSL_SAMPLER_DIM_2D:
3577 inst->tex_target = (type->sampler_array)
3578 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
3579 break;
3580 case GLSL_SAMPLER_DIM_3D:
3581 inst->tex_target = TEXTURE_3D_INDEX;
3582 break;
3583 case GLSL_SAMPLER_DIM_CUBE:
3584 inst->tex_target = (type->sampler_array)
3585 ? TEXTURE_CUBE_ARRAY_INDEX : TEXTURE_CUBE_INDEX;
3586 break;
3587 case GLSL_SAMPLER_DIM_RECT:
3588 inst->tex_target = TEXTURE_RECT_INDEX;
3589 break;
3590 case GLSL_SAMPLER_DIM_BUF:
3591 inst->tex_target = TEXTURE_BUFFER_INDEX;
3592 break;
3593 case GLSL_SAMPLER_DIM_EXTERNAL:
3594 inst->tex_target = TEXTURE_EXTERNAL_INDEX;
3595 break;
3596 case GLSL_SAMPLER_DIM_MS:
3597 inst->tex_target = (type->sampler_array)
3598 ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX : TEXTURE_2D_MULTISAMPLE_INDEX;
3599 break;
3600 default:
3601 assert(!"Should not get here.");
3602 }
3603
3604 inst->image_format = st_mesa_format_to_pipe_format(st_context(ctx),
3605 _mesa_get_shader_image_format(imgvar->data.image_format));
3606
3607 if (imgvar->data.image_coherent)
3608 inst->buffer_access |= TGSI_MEMORY_COHERENT;
3609 if (imgvar->data.image_restrict)
3610 inst->buffer_access |= TGSI_MEMORY_RESTRICT;
3611 if (imgvar->data.image_volatile)
3612 inst->buffer_access |= TGSI_MEMORY_VOLATILE;
3613 }
3614
3615 void
3616 glsl_to_tgsi_visitor::visit(ir_call *ir)
3617 {
3618 glsl_to_tgsi_instruction *call_inst;
3619 ir_function_signature *sig = ir->callee;
3620 const char *callee = sig->function_name();
3621 function_entry *entry;
3622 int i;
3623
3624 /* Filter out intrinsics */
3625 if (!strcmp("__intrinsic_atomic_read", callee) ||
3626 !strcmp("__intrinsic_atomic_increment", callee) ||
3627 !strcmp("__intrinsic_atomic_predecrement", callee) ||
3628 !strcmp("__intrinsic_atomic_add", callee) ||
3629 !strcmp("__intrinsic_atomic_sub", callee) ||
3630 !strcmp("__intrinsic_atomic_min", callee) ||
3631 !strcmp("__intrinsic_atomic_max", callee) ||
3632 !strcmp("__intrinsic_atomic_and", callee) ||
3633 !strcmp("__intrinsic_atomic_or", callee) ||
3634 !strcmp("__intrinsic_atomic_xor", callee) ||
3635 !strcmp("__intrinsic_atomic_exchange", callee) ||
3636 !strcmp("__intrinsic_atomic_comp_swap", callee)) {
3637 visit_atomic_counter_intrinsic(ir);
3638 return;
3639 }
3640
3641 if (!strcmp("__intrinsic_load_ssbo", callee) ||
3642 !strcmp("__intrinsic_store_ssbo", callee) ||
3643 !strcmp("__intrinsic_atomic_add_ssbo", callee) ||
3644 !strcmp("__intrinsic_atomic_min_ssbo", callee) ||
3645 !strcmp("__intrinsic_atomic_max_ssbo", callee) ||
3646 !strcmp("__intrinsic_atomic_and_ssbo", callee) ||
3647 !strcmp("__intrinsic_atomic_or_ssbo", callee) ||
3648 !strcmp("__intrinsic_atomic_xor_ssbo", callee) ||
3649 !strcmp("__intrinsic_atomic_exchange_ssbo", callee) ||
3650 !strcmp("__intrinsic_atomic_comp_swap_ssbo", callee)) {
3651 visit_ssbo_intrinsic(ir);
3652 return;
3653 }
3654
3655 if (!strcmp("__intrinsic_memory_barrier", callee) ||
3656 !strcmp("__intrinsic_memory_barrier_atomic_counter", callee) ||
3657 !strcmp("__intrinsic_memory_barrier_buffer", callee) ||
3658 !strcmp("__intrinsic_memory_barrier_image", callee) ||
3659 !strcmp("__intrinsic_memory_barrier_shared", callee) ||
3660 !strcmp("__intrinsic_group_memory_barrier", callee)) {
3661 visit_membar_intrinsic(ir);
3662 return;
3663 }
3664
3665 if (!strcmp("__intrinsic_load_shared", callee) ||
3666 !strcmp("__intrinsic_store_shared", callee) ||
3667 !strcmp("__intrinsic_atomic_add_shared", callee) ||
3668 !strcmp("__intrinsic_atomic_min_shared", callee) ||
3669 !strcmp("__intrinsic_atomic_max_shared", callee) ||
3670 !strcmp("__intrinsic_atomic_and_shared", callee) ||
3671 !strcmp("__intrinsic_atomic_or_shared", callee) ||
3672 !strcmp("__intrinsic_atomic_xor_shared", callee) ||
3673 !strcmp("__intrinsic_atomic_exchange_shared", callee) ||
3674 !strcmp("__intrinsic_atomic_comp_swap_shared", callee)) {
3675 visit_shared_intrinsic(ir);
3676 return;
3677 }
3678
3679 if (!strcmp("__intrinsic_image_load", callee) ||
3680 !strcmp("__intrinsic_image_store", callee) ||
3681 !strcmp("__intrinsic_image_atomic_add", callee) ||
3682 !strcmp("__intrinsic_image_atomic_min", callee) ||
3683 !strcmp("__intrinsic_image_atomic_max", callee) ||
3684 !strcmp("__intrinsic_image_atomic_and", callee) ||
3685 !strcmp("__intrinsic_image_atomic_or", callee) ||
3686 !strcmp("__intrinsic_image_atomic_xor", callee) ||
3687 !strcmp("__intrinsic_image_atomic_exchange", callee) ||
3688 !strcmp("__intrinsic_image_atomic_comp_swap", callee) ||
3689 !strcmp("__intrinsic_image_size", callee) ||
3690 !strcmp("__intrinsic_image_samples", callee)) {
3691 visit_image_intrinsic(ir);
3692 return;
3693 }
3694
3695 entry = get_function_signature(sig);
3696 /* Process in parameters. */
3697 foreach_two_lists(formal_node, &sig->parameters,
3698 actual_node, &ir->actual_parameters) {
3699 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
3700 ir_variable *param = (ir_variable *) formal_node;
3701
3702 if (param->data.mode == ir_var_function_in ||
3703 param->data.mode == ir_var_function_inout) {
3704 variable_storage *storage = find_variable_storage(param);
3705 assert(storage);
3706
3707 param_rval->accept(this);
3708 st_src_reg r = this->result;
3709
3710 st_dst_reg l;
3711 l.file = storage->file;
3712 l.index = storage->index;
3713 l.reladdr = NULL;
3714 l.writemask = WRITEMASK_XYZW;
3715
3716 for (i = 0; i < type_size(param->type); i++) {
3717 emit_asm(ir, TGSI_OPCODE_MOV, l, r);
3718 l.index++;
3719 r.index++;
3720 }
3721 }
3722 }
3723
3724 /* Emit call instruction */
3725 call_inst = emit_asm(ir, TGSI_OPCODE_CAL);
3726 call_inst->function = entry;
3727
3728 /* Process out parameters. */
3729 foreach_two_lists(formal_node, &sig->parameters,
3730 actual_node, &ir->actual_parameters) {
3731 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
3732 ir_variable *param = (ir_variable *) formal_node;
3733
3734 if (param->data.mode == ir_var_function_out ||
3735 param->data.mode == ir_var_function_inout) {
3736 variable_storage *storage = find_variable_storage(param);
3737 assert(storage);
3738
3739 st_src_reg r;
3740 r.file = storage->file;
3741 r.index = storage->index;
3742 r.reladdr = NULL;
3743 r.swizzle = SWIZZLE_NOOP;
3744 r.negate = 0;
3745
3746 param_rval->accept(this);
3747 st_dst_reg l = st_dst_reg(this->result);
3748
3749 for (i = 0; i < type_size(param->type); i++) {
3750 emit_asm(ir, TGSI_OPCODE_MOV, l, r);
3751 l.index++;
3752 r.index++;
3753 }
3754 }
3755 }
3756
3757 /* Process return value. */
3758 this->result = entry->return_reg;
3759 }
3760
3761 void
3762 glsl_to_tgsi_visitor::calc_deref_offsets(ir_dereference *head,
3763 ir_dereference *tail,
3764 unsigned *array_elements,
3765 unsigned *base,
3766 unsigned *index,
3767 st_src_reg *indirect,
3768 unsigned *location)
3769 {
3770 switch (tail->ir_type) {
3771 case ir_type_dereference_record: {
3772 ir_dereference_record *deref_record = tail->as_dereference_record();
3773 const glsl_type *struct_type = deref_record->record->type;
3774 int field_index = deref_record->record->type->field_index(deref_record->field);
3775
3776 calc_deref_offsets(head, deref_record->record->as_dereference(), array_elements, base, index, indirect, location);
3777
3778 assert(field_index >= 0);
3779 *location += struct_type->record_location_offset(field_index);
3780 break;
3781 }
3782
3783 case ir_type_dereference_array: {
3784 ir_dereference_array *deref_arr = tail->as_dereference_array();
3785 ir_constant *array_index = deref_arr->array_index->constant_expression_value();
3786
3787 if (!array_index) {
3788 st_src_reg temp_reg;
3789 st_dst_reg temp_dst;
3790
3791 temp_reg = get_temp(glsl_type::uint_type);
3792 temp_dst = st_dst_reg(temp_reg);
3793 temp_dst.writemask = 1;
3794
3795 deref_arr->array_index->accept(this);
3796 if (*array_elements != 1)
3797 emit_asm(NULL, TGSI_OPCODE_MUL, temp_dst, this->result, st_src_reg_for_int(*array_elements));
3798 else
3799 emit_asm(NULL, TGSI_OPCODE_MOV, temp_dst, this->result);
3800
3801 if (indirect->file == PROGRAM_UNDEFINED)
3802 *indirect = temp_reg;
3803 else {
3804 temp_dst = st_dst_reg(*indirect);
3805 temp_dst.writemask = 1;
3806 emit_asm(NULL, TGSI_OPCODE_ADD, temp_dst, *indirect, temp_reg);
3807 }
3808 } else
3809 *index += array_index->value.u[0] * *array_elements;
3810
3811 *array_elements *= deref_arr->array->type->length;
3812
3813 calc_deref_offsets(head, deref_arr->array->as_dereference(), array_elements, base, index, indirect, location);
3814 break;
3815 }
3816 default:
3817 break;
3818 }
3819 }
3820
3821 void
3822 glsl_to_tgsi_visitor::get_deref_offsets(ir_dereference *ir,
3823 unsigned *array_size,
3824 unsigned *base,
3825 unsigned *index,
3826 st_src_reg *reladdr)
3827 {
3828 GLuint shader = _mesa_program_enum_to_shader_stage(this->prog->Target);
3829 unsigned location = 0;
3830 ir_variable *var = ir->variable_referenced();
3831
3832 memset(reladdr, 0, sizeof(*reladdr));
3833 reladdr->file = PROGRAM_UNDEFINED;
3834
3835 *base = 0;
3836 *array_size = 1;
3837
3838 assert(var);
3839 location = var->data.location;
3840 calc_deref_offsets(ir, ir, array_size, base, index, reladdr, &location);
3841
3842 /*
3843 * If we end up with no indirect then adjust the base to the index,
3844 * and set the array size to 1.
3845 */
3846 if (reladdr->file == PROGRAM_UNDEFINED) {
3847 *base = *index;
3848 *array_size = 1;
3849 }
3850
3851 if (location != 0xffffffff) {
3852 *base += this->shader_program->UniformStorage[location].opaque[shader].index;
3853 *index += this->shader_program->UniformStorage[location].opaque[shader].index;
3854 }
3855 }
3856
3857 void
3858 glsl_to_tgsi_visitor::visit(ir_texture *ir)
3859 {
3860 st_src_reg result_src, coord, cube_sc, lod_info, projector, dx, dy;
3861 st_src_reg offset[MAX_GLSL_TEXTURE_OFFSET], sample_index, component;
3862 st_src_reg levels_src, reladdr;
3863 st_dst_reg result_dst, coord_dst, cube_sc_dst;
3864 glsl_to_tgsi_instruction *inst = NULL;
3865 unsigned opcode = TGSI_OPCODE_NOP;
3866 const glsl_type *sampler_type = ir->sampler->type;
3867 unsigned sampler_array_size = 1, sampler_index = 0, sampler_base = 0;
3868 bool is_cube_array = false;
3869 unsigned i;
3870
3871 /* if we are a cube array sampler */
3872 if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE &&
3873 sampler_type->sampler_array)) {
3874 is_cube_array = true;
3875 }
3876
3877 if (ir->coordinate) {
3878 ir->coordinate->accept(this);
3879
3880 /* Put our coords in a temp. We'll need to modify them for shadow,
3881 * projection, or LOD, so the only case we'd use it as-is is if
3882 * we're doing plain old texturing. The optimization passes on
3883 * glsl_to_tgsi_visitor should handle cleaning up our mess in that case.
3884 */
3885 coord = get_temp(glsl_type::vec4_type);
3886 coord_dst = st_dst_reg(coord);
3887 coord_dst.writemask = (1 << ir->coordinate->type->vector_elements) - 1;
3888 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
3889 }
3890
3891 if (ir->projector) {
3892 ir->projector->accept(this);
3893 projector = this->result;
3894 }
3895
3896 /* Storage for our result. Ideally for an assignment we'd be using
3897 * the actual storage for the result here, instead.
3898 */
3899 result_src = get_temp(ir->type);
3900 result_dst = st_dst_reg(result_src);
3901
3902 switch (ir->op) {
3903 case ir_tex:
3904 opcode = (is_cube_array && ir->shadow_comparitor) ? TGSI_OPCODE_TEX2 : TGSI_OPCODE_TEX;
3905 if (ir->offset) {
3906 ir->offset->accept(this);
3907 offset[0] = this->result;
3908 }
3909 break;
3910 case ir_txb:
3911 if (is_cube_array ||
3912 sampler_type == glsl_type::samplerCubeShadow_type) {
3913 opcode = TGSI_OPCODE_TXB2;
3914 }
3915 else {
3916 opcode = TGSI_OPCODE_TXB;
3917 }
3918 ir->lod_info.bias->accept(this);
3919 lod_info = this->result;
3920 if (ir->offset) {
3921 ir->offset->accept(this);
3922 offset[0] = this->result;
3923 }
3924 break;
3925 case ir_txl:
3926 opcode = is_cube_array ? TGSI_OPCODE_TXL2 : TGSI_OPCODE_TXL;
3927 ir->lod_info.lod->accept(this);
3928 lod_info = this->result;
3929 if (ir->offset) {
3930 ir->offset->accept(this);
3931 offset[0] = this->result;
3932 }
3933 break;
3934 case ir_txd:
3935 opcode = TGSI_OPCODE_TXD;
3936 ir->lod_info.grad.dPdx->accept(this);
3937 dx = this->result;
3938 ir->lod_info.grad.dPdy->accept(this);
3939 dy = this->result;
3940 if (ir->offset) {
3941 ir->offset->accept(this);
3942 offset[0] = this->result;
3943 }
3944 break;
3945 case ir_txs:
3946 opcode = TGSI_OPCODE_TXQ;
3947 ir->lod_info.lod->accept(this);
3948 lod_info = this->result;
3949 break;
3950 case ir_query_levels:
3951 opcode = TGSI_OPCODE_TXQ;
3952 lod_info = undef_src;
3953 levels_src = get_temp(ir->type);
3954 break;
3955 case ir_txf:
3956 opcode = TGSI_OPCODE_TXF;
3957 ir->lod_info.lod->accept(this);
3958 lod_info = this->result;
3959 if (ir->offset) {
3960 ir->offset->accept(this);
3961 offset[0] = this->result;
3962 }
3963 break;
3964 case ir_txf_ms:
3965 opcode = TGSI_OPCODE_TXF;
3966 ir->lod_info.sample_index->accept(this);
3967 sample_index = this->result;
3968 break;
3969 case ir_tg4:
3970 opcode = TGSI_OPCODE_TG4;
3971 ir->lod_info.component->accept(this);
3972 component = this->result;
3973 if (ir->offset) {
3974 ir->offset->accept(this);
3975 if (ir->offset->type->base_type == GLSL_TYPE_ARRAY) {
3976 const glsl_type *elt_type = ir->offset->type->fields.array;
3977 for (i = 0; i < ir->offset->type->length; i++) {
3978 offset[i] = this->result;
3979 offset[i].index += i * type_size(elt_type);
3980 offset[i].type = elt_type->base_type;
3981 offset[i].swizzle = swizzle_for_size(elt_type->vector_elements);
3982 }
3983 } else {
3984 offset[0] = this->result;
3985 }
3986 }
3987 break;
3988 case ir_lod:
3989 opcode = TGSI_OPCODE_LODQ;
3990 break;
3991 case ir_texture_samples:
3992 opcode = TGSI_OPCODE_TXQS;
3993 break;
3994 case ir_samples_identical:
3995 unreachable("Unexpected ir_samples_identical opcode");
3996 }
3997
3998 if (ir->projector) {
3999 if (opcode == TGSI_OPCODE_TEX) {
4000 /* Slot the projector in as the last component of the coord. */
4001 coord_dst.writemask = WRITEMASK_W;
4002 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, projector);
4003 coord_dst.writemask = WRITEMASK_XYZW;
4004 opcode = TGSI_OPCODE_TXP;
4005 } else {
4006 st_src_reg coord_w = coord;
4007 coord_w.swizzle = SWIZZLE_WWWW;
4008
4009 /* For the other TEX opcodes there's no projective version
4010 * since the last slot is taken up by LOD info. Do the
4011 * projective divide now.
4012 */
4013 coord_dst.writemask = WRITEMASK_W;
4014 emit_asm(ir, TGSI_OPCODE_RCP, coord_dst, projector);
4015
4016 /* In the case where we have to project the coordinates "by hand,"
4017 * the shadow comparator value must also be projected.
4018 */
4019 st_src_reg tmp_src = coord;
4020 if (ir->shadow_comparitor) {
4021 /* Slot the shadow value in as the second to last component of the
4022 * coord.
4023 */
4024 ir->shadow_comparitor->accept(this);
4025
4026 tmp_src = get_temp(glsl_type::vec4_type);
4027 st_dst_reg tmp_dst = st_dst_reg(tmp_src);
4028
4029 /* Projective division not allowed for array samplers. */
4030 assert(!sampler_type->sampler_array);
4031
4032 tmp_dst.writemask = WRITEMASK_Z;
4033 emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, this->result);
4034
4035 tmp_dst.writemask = WRITEMASK_XY;
4036 emit_asm(ir, TGSI_OPCODE_MOV, tmp_dst, coord);
4037 }
4038
4039 coord_dst.writemask = WRITEMASK_XYZ;
4040 emit_asm(ir, TGSI_OPCODE_MUL, coord_dst, tmp_src, coord_w);
4041
4042 coord_dst.writemask = WRITEMASK_XYZW;
4043 coord.swizzle = SWIZZLE_XYZW;
4044 }
4045 }
4046
4047 /* If projection is done and the opcode is not TGSI_OPCODE_TXP, then the shadow
4048 * comparator was put in the correct place (and projected) by the code,
4049 * above, that handles by-hand projection.
4050 */
4051 if (ir->shadow_comparitor && (!ir->projector || opcode == TGSI_OPCODE_TXP)) {
4052 /* Slot the shadow value in as the second to last component of the
4053 * coord.
4054 */
4055 ir->shadow_comparitor->accept(this);
4056
4057 if (is_cube_array) {
4058 cube_sc = get_temp(glsl_type::float_type);
4059 cube_sc_dst = st_dst_reg(cube_sc);
4060 cube_sc_dst.writemask = WRITEMASK_X;
4061 emit_asm(ir, TGSI_OPCODE_MOV, cube_sc_dst, this->result);
4062 cube_sc_dst.writemask = WRITEMASK_X;
4063 }
4064 else {
4065 if ((sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_2D &&
4066 sampler_type->sampler_array) ||
4067 sampler_type->sampler_dimensionality == GLSL_SAMPLER_DIM_CUBE) {
4068 coord_dst.writemask = WRITEMASK_W;
4069 } else {
4070 coord_dst.writemask = WRITEMASK_Z;
4071 }
4072 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, this->result);
4073 coord_dst.writemask = WRITEMASK_XYZW;
4074 }
4075 }
4076
4077 if (ir->op == ir_txf_ms) {
4078 coord_dst.writemask = WRITEMASK_W;
4079 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, sample_index);
4080 coord_dst.writemask = WRITEMASK_XYZW;
4081 } else if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXB ||
4082 opcode == TGSI_OPCODE_TXF) {
4083 /* TGSI stores LOD or LOD bias in the last channel of the coords. */
4084 coord_dst.writemask = WRITEMASK_W;
4085 emit_asm(ir, TGSI_OPCODE_MOV, coord_dst, lod_info);
4086 coord_dst.writemask = WRITEMASK_XYZW;
4087 }
4088
4089 get_deref_offsets(ir->sampler, &sampler_array_size, &sampler_base,
4090 &sampler_index, &reladdr);
4091 if (reladdr.file != PROGRAM_UNDEFINED)
4092 emit_arl(ir, sampler_reladdr, reladdr);
4093
4094 if (opcode == TGSI_OPCODE_TXD)
4095 inst = emit_asm(ir, opcode, result_dst, coord, dx, dy);
4096 else if (opcode == TGSI_OPCODE_TXQ) {
4097 if (ir->op == ir_query_levels) {
4098 /* the level is stored in W */
4099 inst = emit_asm(ir, opcode, st_dst_reg(levels_src), lod_info);
4100 result_dst.writemask = WRITEMASK_X;
4101 levels_src.swizzle = SWIZZLE_WWWW;
4102 emit_asm(ir, TGSI_OPCODE_MOV, result_dst, levels_src);
4103 } else
4104 inst = emit_asm(ir, opcode, result_dst, lod_info);
4105 } else if (opcode == TGSI_OPCODE_TXQS) {
4106 inst = emit_asm(ir, opcode, result_dst);
4107 } else if (opcode == TGSI_OPCODE_TXF) {
4108 inst = emit_asm(ir, opcode, result_dst, coord);
4109 } else if (opcode == TGSI_OPCODE_TXL2 || opcode == TGSI_OPCODE_TXB2) {
4110 inst = emit_asm(ir, opcode, result_dst, coord, lod_info);
4111 } else if (opcode == TGSI_OPCODE_TEX2) {
4112 inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4113 } else if (opcode == TGSI_OPCODE_TG4) {
4114 if (is_cube_array && ir->shadow_comparitor) {
4115 inst = emit_asm(ir, opcode, result_dst, coord, cube_sc);
4116 } else {
4117 inst = emit_asm(ir, opcode, result_dst, coord, component);
4118 }
4119 } else
4120 inst = emit_asm(ir, opcode, result_dst, coord);
4121
4122 if (ir->shadow_comparitor)
4123 inst->tex_shadow = GL_TRUE;
4124
4125 inst->sampler.index = sampler_index;
4126 inst->sampler_array_size = sampler_array_size;
4127 inst->sampler_base = sampler_base;
4128
4129 if (reladdr.file != PROGRAM_UNDEFINED) {
4130 inst->sampler.reladdr = ralloc(mem_ctx, st_src_reg);
4131 memcpy(inst->sampler.reladdr, &reladdr, sizeof(reladdr));
4132 }
4133
4134 if (ir->offset) {
4135 for (i = 0; i < MAX_GLSL_TEXTURE_OFFSET && offset[i].file != PROGRAM_UNDEFINED; i++)
4136 inst->tex_offsets[i] = offset[i];
4137 inst->tex_offset_num_offset = i;
4138 }
4139
4140 switch (sampler_type->sampler_dimensionality) {
4141 case GLSL_SAMPLER_DIM_1D:
4142 inst->tex_target = (sampler_type->sampler_array)
4143 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
4144 break;
4145 case GLSL_SAMPLER_DIM_2D:
4146 inst->tex_target = (sampler_type->sampler_array)
4147 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
4148 break;
4149 case GLSL_SAMPLER_DIM_3D:
4150 inst->tex_target = TEXTURE_3D_INDEX;
4151 break;
4152 case GLSL_SAMPLER_DIM_CUBE:
4153 inst->tex_target = (sampler_type->sampler_array)
4154 ? TEXTURE_CUBE_ARRAY_INDEX : TEXTURE_CUBE_INDEX;
4155 break;
4156 case GLSL_SAMPLER_DIM_RECT:
4157 inst->tex_target = TEXTURE_RECT_INDEX;
4158 break;
4159 case GLSL_SAMPLER_DIM_BUF:
4160 inst->tex_target = TEXTURE_BUFFER_INDEX;
4161 break;
4162 case GLSL_SAMPLER_DIM_EXTERNAL:
4163 inst->tex_target = TEXTURE_EXTERNAL_INDEX;
4164 break;
4165 case GLSL_SAMPLER_DIM_MS:
4166 inst->tex_target = (sampler_type->sampler_array)
4167 ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX : TEXTURE_2D_MULTISAMPLE_INDEX;
4168 break;
4169 default:
4170 assert(!"Should not get here.");
4171 }
4172
4173 inst->tex_type = ir->type->base_type;
4174
4175 this->result = result_src;
4176 }
4177
4178 void
4179 glsl_to_tgsi_visitor::visit(ir_return *ir)
4180 {
4181 if (ir->get_value()) {
4182 st_dst_reg l;
4183 int i;
4184
4185 assert(current_function);
4186
4187 ir->get_value()->accept(this);
4188 st_src_reg r = this->result;
4189
4190 l = st_dst_reg(current_function->return_reg);
4191
4192 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
4193 emit_asm(ir, TGSI_OPCODE_MOV, l, r);
4194 l.index++;
4195 r.index++;
4196 }
4197 }
4198
4199 emit_asm(ir, TGSI_OPCODE_RET);
4200 }
4201
4202 void
4203 glsl_to_tgsi_visitor::visit(ir_discard *ir)
4204 {
4205 if (ir->condition) {
4206 ir->condition->accept(this);
4207 st_src_reg condition = this->result;
4208
4209 /* Convert the bool condition to a float so we can negate. */
4210 if (native_integers) {
4211 st_src_reg temp = get_temp(ir->condition->type);
4212 emit_asm(ir, TGSI_OPCODE_AND, st_dst_reg(temp),
4213 condition, st_src_reg_for_float(1.0));
4214 condition = temp;
4215 }
4216
4217 condition.negate = ~condition.negate;
4218 emit_asm(ir, TGSI_OPCODE_KILL_IF, undef_dst, condition);
4219 } else {
4220 /* unconditional kil */
4221 emit_asm(ir, TGSI_OPCODE_KILL);
4222 }
4223 }
4224
4225 void
4226 glsl_to_tgsi_visitor::visit(ir_if *ir)
4227 {
4228 unsigned if_opcode;
4229 glsl_to_tgsi_instruction *if_inst;
4230
4231 ir->condition->accept(this);
4232 assert(this->result.file != PROGRAM_UNDEFINED);
4233
4234 if_opcode = native_integers ? TGSI_OPCODE_UIF : TGSI_OPCODE_IF;
4235
4236 if_inst = emit_asm(ir->condition, if_opcode, undef_dst, this->result);
4237
4238 this->instructions.push_tail(if_inst);
4239
4240 visit_exec_list(&ir->then_instructions, this);
4241
4242 if (!ir->else_instructions.is_empty()) {
4243 emit_asm(ir->condition, TGSI_OPCODE_ELSE);
4244 visit_exec_list(&ir->else_instructions, this);
4245 }
4246
4247 if_inst = emit_asm(ir->condition, TGSI_OPCODE_ENDIF);
4248 }
4249
4250
4251 void
4252 glsl_to_tgsi_visitor::visit(ir_emit_vertex *ir)
4253 {
4254 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4255
4256 ir->stream->accept(this);
4257 emit_asm(ir, TGSI_OPCODE_EMIT, undef_dst, this->result);
4258 }
4259
4260 void
4261 glsl_to_tgsi_visitor::visit(ir_end_primitive *ir)
4262 {
4263 assert(this->prog->Target == GL_GEOMETRY_PROGRAM_NV);
4264
4265 ir->stream->accept(this);
4266 emit_asm(ir, TGSI_OPCODE_ENDPRIM, undef_dst, this->result);
4267 }
4268
4269 void
4270 glsl_to_tgsi_visitor::visit(ir_barrier *ir)
4271 {
4272 assert(this->prog->Target == GL_TESS_CONTROL_PROGRAM_NV ||
4273 this->prog->Target == GL_COMPUTE_PROGRAM_NV);
4274
4275 emit_asm(ir, TGSI_OPCODE_BARRIER);
4276 }
4277
4278 glsl_to_tgsi_visitor::glsl_to_tgsi_visitor()
4279 {
4280 STATIC_ASSERT(sizeof(samplers_used) * 8 >= PIPE_MAX_SAMPLERS);
4281
4282 result.file = PROGRAM_UNDEFINED;
4283 next_temp = 1;
4284 array_sizes = NULL;
4285 max_num_arrays = 0;
4286 next_array = 0;
4287 num_input_arrays = 0;
4288 num_output_arrays = 0;
4289 next_signature_id = 1;
4290 num_immediates = 0;
4291 current_function = NULL;
4292 num_address_regs = 0;
4293 samplers_used = 0;
4294 buffers_used = 0;
4295 images_used = 0;
4296 indirect_addr_consts = false;
4297 wpos_transform_const = -1;
4298 glsl_version = 0;
4299 native_integers = false;
4300 mem_ctx = ralloc_context(NULL);
4301 ctx = NULL;
4302 prog = NULL;
4303 shader_program = NULL;
4304 shader = NULL;
4305 options = NULL;
4306 have_sqrt = false;
4307 have_fma = false;
4308 use_shared_memory = false;
4309 }
4310
4311 glsl_to_tgsi_visitor::~glsl_to_tgsi_visitor()
4312 {
4313 free(array_sizes);
4314 ralloc_free(mem_ctx);
4315 }
4316
4317 extern "C" void free_glsl_to_tgsi_visitor(glsl_to_tgsi_visitor *v)
4318 {
4319 delete v;
4320 }
4321
4322
4323 /**
4324 * Count resources used by the given gpu program (number of texture
4325 * samplers, etc).
4326 */
4327 static void
4328 count_resources(glsl_to_tgsi_visitor *v, gl_program *prog)
4329 {
4330 v->samplers_used = 0;
4331 v->buffers_used = 0;
4332 v->images_used = 0;
4333
4334 foreach_in_list(glsl_to_tgsi_instruction, inst, &v->instructions) {
4335 if (inst->info->is_tex) {
4336 for (int i = 0; i < inst->sampler_array_size; i++) {
4337 unsigned idx = inst->sampler_base + i;
4338 v->samplers_used |= 1u << idx;
4339
4340 debug_assert(idx < (int)ARRAY_SIZE(v->sampler_types));
4341 v->sampler_types[idx] = inst->tex_type;
4342 v->sampler_targets[idx] =
4343 st_translate_texture_target(inst->tex_target, inst->tex_shadow);
4344
4345 if (inst->tex_shadow) {
4346 prog->ShadowSamplers |= 1 << (inst->sampler.index + i);
4347 }
4348 }
4349 }
4350
4351 if (inst->tex_target == TEXTURE_EXTERNAL_INDEX)
4352 prog->ExternalSamplersUsed |= 1 << inst->sampler.index;
4353
4354 if (inst->buffer.file != PROGRAM_UNDEFINED && (
4355 is_resource_instruction(inst->op) ||
4356 inst->op == TGSI_OPCODE_STORE)) {
4357 if (inst->buffer.file == PROGRAM_BUFFER) {
4358 v->buffers_used |= 1 << inst->buffer.index;
4359 } else if (inst->buffer.file == PROGRAM_MEMORY) {
4360 v->use_shared_memory = true;
4361 } else {
4362 assert(inst->buffer.file == PROGRAM_IMAGE);
4363 for (int i = 0; i < inst->sampler_array_size; i++) {
4364 unsigned idx = inst->sampler_base + i;
4365 v->images_used |= 1 << idx;
4366 v->image_targets[idx] =
4367 st_translate_texture_target(inst->tex_target, false);
4368 v->image_formats[idx] = inst->image_format;
4369 }
4370 }
4371 }
4372 }
4373 prog->SamplersUsed = v->samplers_used;
4374
4375 if (v->shader_program != NULL)
4376 _mesa_update_shader_textures_used(v->shader_program, prog);
4377 }
4378
4379 /**
4380 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
4381 * are read from the given src in this instruction
4382 */
4383 static int
4384 get_src_arg_mask(st_dst_reg dst, st_src_reg src)
4385 {
4386 int read_mask = 0, comp;
4387
4388 /* Now, given the src swizzle and the written channels, find which
4389 * components are actually read
4390 */
4391 for (comp = 0; comp < 4; ++comp) {
4392 const unsigned coord = GET_SWZ(src.swizzle, comp);
4393 assert(coord < 4);
4394 if (dst.writemask & (1 << comp) && coord <= SWIZZLE_W)
4395 read_mask |= 1 << coord;
4396 }
4397
4398 return read_mask;
4399 }
4400
4401 /**
4402 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
4403 * instruction is the first instruction to write to register T0. There are
4404 * several lowering passes done in GLSL IR (e.g. branches and
4405 * relative addressing) that create a large number of conditional assignments
4406 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
4407 *
4408 * Here is why this conversion is safe:
4409 * CMP T0, T1 T2 T0 can be expanded to:
4410 * if (T1 < 0.0)
4411 * MOV T0, T2;
4412 * else
4413 * MOV T0, T0;
4414 *
4415 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
4416 * as the original program. If (T1 < 0.0) evaluates to false, executing
4417 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
4418 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
4419 * because any instruction that was going to read from T0 after this was going
4420 * to read a garbage value anyway.
4421 */
4422 void
4423 glsl_to_tgsi_visitor::simplify_cmp(void)
4424 {
4425 int tempWritesSize = 0;
4426 unsigned *tempWrites = NULL;
4427 unsigned outputWrites[VARYING_SLOT_TESS_MAX];
4428
4429 memset(outputWrites, 0, sizeof(outputWrites));
4430
4431 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4432 unsigned prevWriteMask = 0;
4433
4434 /* Give up if we encounter relative addressing or flow control. */
4435 if (inst->dst[0].reladdr || inst->dst[0].reladdr2 ||
4436 inst->dst[1].reladdr || inst->dst[1].reladdr2 ||
4437 tgsi_get_opcode_info(inst->op)->is_branch ||
4438 inst->op == TGSI_OPCODE_BGNSUB ||
4439 inst->op == TGSI_OPCODE_CONT ||
4440 inst->op == TGSI_OPCODE_END ||
4441 inst->op == TGSI_OPCODE_ENDSUB ||
4442 inst->op == TGSI_OPCODE_RET) {
4443 break;
4444 }
4445
4446 if (inst->dst[0].file == PROGRAM_OUTPUT) {
4447 assert(inst->dst[0].index < (signed)ARRAY_SIZE(outputWrites));
4448 prevWriteMask = outputWrites[inst->dst[0].index];
4449 outputWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4450 } else if (inst->dst[0].file == PROGRAM_TEMPORARY) {
4451 if (inst->dst[0].index >= tempWritesSize) {
4452 const int inc = 4096;
4453
4454 tempWrites = (unsigned*)
4455 realloc(tempWrites,
4456 (tempWritesSize + inc) * sizeof(unsigned));
4457 if (!tempWrites)
4458 return;
4459
4460 memset(tempWrites + tempWritesSize, 0, inc * sizeof(unsigned));
4461 tempWritesSize += inc;
4462 }
4463
4464 prevWriteMask = tempWrites[inst->dst[0].index];
4465 tempWrites[inst->dst[0].index] |= inst->dst[0].writemask;
4466 } else
4467 continue;
4468
4469 /* For a CMP to be considered a conditional write, the destination
4470 * register and source register two must be the same. */
4471 if (inst->op == TGSI_OPCODE_CMP
4472 && !(inst->dst[0].writemask & prevWriteMask)
4473 && inst->src[2].file == inst->dst[0].file
4474 && inst->src[2].index == inst->dst[0].index
4475 && inst->dst[0].writemask == get_src_arg_mask(inst->dst[0], inst->src[2])) {
4476
4477 inst->op = TGSI_OPCODE_MOV;
4478 inst->info = tgsi_get_opcode_info(inst->op);
4479 inst->src[0] = inst->src[1];
4480 }
4481 }
4482
4483 free(tempWrites);
4484 }
4485
4486 /* Replaces all references to a temporary register index with another index. */
4487 void
4488 glsl_to_tgsi_visitor::rename_temp_registers(int num_renames, struct rename_reg_pair *renames)
4489 {
4490 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4491 unsigned j;
4492 int k;
4493 for (j = 0; j < num_inst_src_regs(inst); j++) {
4494 if (inst->src[j].file == PROGRAM_TEMPORARY)
4495 for (k = 0; k < num_renames; k++)
4496 if (inst->src[j].index == renames[k].old_reg)
4497 inst->src[j].index = renames[k].new_reg;
4498 }
4499
4500 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4501 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY)
4502 for (k = 0; k < num_renames; k++)
4503 if (inst->tex_offsets[j].index == renames[k].old_reg)
4504 inst->tex_offsets[j].index = renames[k].new_reg;
4505 }
4506
4507 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4508 if (inst->dst[j].file == PROGRAM_TEMPORARY)
4509 for (k = 0; k < num_renames; k++)
4510 if (inst->dst[j].index == renames[k].old_reg)
4511 inst->dst[j].index = renames[k].new_reg;
4512 }
4513 }
4514 }
4515
4516 void
4517 glsl_to_tgsi_visitor::get_first_temp_read(int *first_reads)
4518 {
4519 int depth = 0; /* loop depth */
4520 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4521 unsigned i = 0, j;
4522
4523 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4524 for (j = 0; j < num_inst_src_regs(inst); j++) {
4525 if (inst->src[j].file == PROGRAM_TEMPORARY) {
4526 if (first_reads[inst->src[j].index] == -1)
4527 first_reads[inst->src[j].index] = (depth == 0) ? i : loop_start;
4528 }
4529 }
4530 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4531 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY) {
4532 if (first_reads[inst->tex_offsets[j].index] == -1)
4533 first_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : loop_start;
4534 }
4535 }
4536 if (inst->op == TGSI_OPCODE_BGNLOOP) {
4537 if(depth++ == 0)
4538 loop_start = i;
4539 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4540 if (--depth == 0)
4541 loop_start = -1;
4542 }
4543 assert(depth >= 0);
4544 i++;
4545 }
4546 }
4547
4548 void
4549 glsl_to_tgsi_visitor::get_last_temp_read_first_temp_write(int *last_reads, int *first_writes)
4550 {
4551 int depth = 0; /* loop depth */
4552 int loop_start = -1; /* index of the first active BGNLOOP (if any) */
4553 unsigned i = 0, j;
4554 int k;
4555 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4556 for (j = 0; j < num_inst_src_regs(inst); j++) {
4557 if (inst->src[j].file == PROGRAM_TEMPORARY)
4558 last_reads[inst->src[j].index] = (depth == 0) ? i : -2;
4559 }
4560 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4561 if (inst->dst[j].file == PROGRAM_TEMPORARY) {
4562 if (first_writes[inst->dst[j].index] == -1)
4563 first_writes[inst->dst[j].index] = (depth == 0) ? i : loop_start;
4564 last_reads[inst->dst[j].index] = (depth == 0) ? i : -2;
4565 }
4566 }
4567 for (j = 0; j < inst->tex_offset_num_offset; j++) {
4568 if (inst->tex_offsets[j].file == PROGRAM_TEMPORARY)
4569 last_reads[inst->tex_offsets[j].index] = (depth == 0) ? i : -2;
4570 }
4571 if (inst->op == TGSI_OPCODE_BGNLOOP) {
4572 if(depth++ == 0)
4573 loop_start = i;
4574 } else if (inst->op == TGSI_OPCODE_ENDLOOP) {
4575 if (--depth == 0) {
4576 loop_start = -1;
4577 for (k = 0; k < this->next_temp; k++) {
4578 if (last_reads[k] == -2) {
4579 last_reads[k] = i;
4580 }
4581 }
4582 }
4583 }
4584 assert(depth >= 0);
4585 i++;
4586 }
4587 }
4588
4589 void
4590 glsl_to_tgsi_visitor::get_last_temp_write(int *last_writes)
4591 {
4592 int depth = 0; /* loop depth */
4593 int i = 0, k;
4594 unsigned j;
4595
4596 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4597 for (j = 0; j < num_inst_dst_regs(inst); j++) {
4598 if (inst->dst[j].file == PROGRAM_TEMPORARY)
4599 last_writes[inst->dst[j].index] = (depth == 0) ? i : -2;
4600 }
4601
4602 if (inst->op == TGSI_OPCODE_BGNLOOP)
4603 depth++;
4604 else if (inst->op == TGSI_OPCODE_ENDLOOP)
4605 if (--depth == 0) {
4606 for (k = 0; k < this->next_temp; k++) {
4607 if (last_writes[k] == -2) {
4608 last_writes[k] = i;
4609 }
4610 }
4611 }
4612 assert(depth >= 0);
4613 i++;
4614 }
4615 }
4616
4617 /*
4618 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
4619 * channels for copy propagation and updates following instructions to
4620 * use the original versions.
4621 *
4622 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
4623 * will occur. As an example, a TXP production before this pass:
4624 *
4625 * 0: MOV TEMP[1], INPUT[4].xyyy;
4626 * 1: MOV TEMP[1].w, INPUT[4].wwww;
4627 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
4628 *
4629 * and after:
4630 *
4631 * 0: MOV TEMP[1], INPUT[4].xyyy;
4632 * 1: MOV TEMP[1].w, INPUT[4].wwww;
4633 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4634 *
4635 * which allows for dead code elimination on TEMP[1]'s writes.
4636 */
4637 void
4638 glsl_to_tgsi_visitor::copy_propagate(void)
4639 {
4640 glsl_to_tgsi_instruction **acp = rzalloc_array(mem_ctx,
4641 glsl_to_tgsi_instruction *,
4642 this->next_temp * 4);
4643 int *acp_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
4644 int level = 0;
4645
4646 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4647 assert(inst->dst[0].file != PROGRAM_TEMPORARY
4648 || inst->dst[0].index < this->next_temp);
4649
4650 /* First, do any copy propagation possible into the src regs. */
4651 for (int r = 0; r < 3; r++) {
4652 glsl_to_tgsi_instruction *first = NULL;
4653 bool good = true;
4654 int acp_base = inst->src[r].index * 4;
4655
4656 if (inst->src[r].file != PROGRAM_TEMPORARY ||
4657 inst->src[r].reladdr ||
4658 inst->src[r].reladdr2)
4659 continue;
4660
4661 /* See if we can find entries in the ACP consisting of MOVs
4662 * from the same src register for all the swizzled channels
4663 * of this src register reference.
4664 */
4665 for (int i = 0; i < 4; i++) {
4666 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
4667 glsl_to_tgsi_instruction *copy_chan = acp[acp_base + src_chan];
4668
4669 if (!copy_chan) {
4670 good = false;
4671 break;
4672 }
4673
4674 assert(acp_level[acp_base + src_chan] <= level);
4675
4676 if (!first) {
4677 first = copy_chan;
4678 } else {
4679 if (first->src[0].file != copy_chan->src[0].file ||
4680 first->src[0].index != copy_chan->src[0].index ||
4681 first->src[0].double_reg2 != copy_chan->src[0].double_reg2 ||
4682 first->src[0].index2D != copy_chan->src[0].index2D) {
4683 good = false;
4684 break;
4685 }
4686 }
4687 }
4688
4689 if (good) {
4690 /* We've now validated that we can copy-propagate to
4691 * replace this src register reference. Do it.
4692 */
4693 inst->src[r].file = first->src[0].file;
4694 inst->src[r].index = first->src[0].index;
4695 inst->src[r].index2D = first->src[0].index2D;
4696 inst->src[r].has_index2 = first->src[0].has_index2;
4697 inst->src[r].double_reg2 = first->src[0].double_reg2;
4698 inst->src[r].array_id = first->src[0].array_id;
4699
4700 int swizzle = 0;
4701 for (int i = 0; i < 4; i++) {
4702 int src_chan = GET_SWZ(inst->src[r].swizzle, i);
4703 glsl_to_tgsi_instruction *copy_inst = acp[acp_base + src_chan];
4704 swizzle |= (GET_SWZ(copy_inst->src[0].swizzle, src_chan) << (3 * i));
4705 }
4706 inst->src[r].swizzle = swizzle;
4707 }
4708 }
4709
4710 switch (inst->op) {
4711 case TGSI_OPCODE_BGNLOOP:
4712 case TGSI_OPCODE_ENDLOOP:
4713 /* End of a basic block, clear the ACP entirely. */
4714 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
4715 break;
4716
4717 case TGSI_OPCODE_IF:
4718 case TGSI_OPCODE_UIF:
4719 ++level;
4720 break;
4721
4722 case TGSI_OPCODE_ENDIF:
4723 case TGSI_OPCODE_ELSE:
4724 /* Clear all channels written inside the block from the ACP, but
4725 * leaving those that were not touched.
4726 */
4727 for (int r = 0; r < this->next_temp; r++) {
4728 for (int c = 0; c < 4; c++) {
4729 if (!acp[4 * r + c])
4730 continue;
4731
4732 if (acp_level[4 * r + c] >= level)
4733 acp[4 * r + c] = NULL;
4734 }
4735 }
4736 if (inst->op == TGSI_OPCODE_ENDIF)
4737 --level;
4738 break;
4739
4740 default:
4741 /* Continuing the block, clear any written channels from
4742 * the ACP.
4743 */
4744 for (int d = 0; d < 2; d++) {
4745 if (inst->dst[d].file == PROGRAM_TEMPORARY && inst->dst[d].reladdr) {
4746 /* Any temporary might be written, so no copy propagation
4747 * across this instruction.
4748 */
4749 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
4750 } else if (inst->dst[d].file == PROGRAM_OUTPUT &&
4751 inst->dst[d].reladdr) {
4752 /* Any output might be written, so no copy propagation
4753 * from outputs across this instruction.
4754 */
4755 for (int r = 0; r < this->next_temp; r++) {
4756 for (int c = 0; c < 4; c++) {
4757 if (!acp[4 * r + c])
4758 continue;
4759
4760 if (acp[4 * r + c]->src[0].file == PROGRAM_OUTPUT)
4761 acp[4 * r + c] = NULL;
4762 }
4763 }
4764 } else if (inst->dst[d].file == PROGRAM_TEMPORARY ||
4765 inst->dst[d].file == PROGRAM_OUTPUT) {
4766 /* Clear where it's used as dst. */
4767 if (inst->dst[d].file == PROGRAM_TEMPORARY) {
4768 for (int c = 0; c < 4; c++) {
4769 if (inst->dst[d].writemask & (1 << c))
4770 acp[4 * inst->dst[d].index + c] = NULL;
4771 }
4772 }
4773
4774 /* Clear where it's used as src. */
4775 for (int r = 0; r < this->next_temp; r++) {
4776 for (int c = 0; c < 4; c++) {
4777 if (!acp[4 * r + c])
4778 continue;
4779
4780 int src_chan = GET_SWZ(acp[4 * r + c]->src[0].swizzle, c);
4781
4782 if (acp[4 * r + c]->src[0].file == inst->dst[d].file &&
4783 acp[4 * r + c]->src[0].index == inst->dst[d].index &&
4784 inst->dst[d].writemask & (1 << src_chan)) {
4785 acp[4 * r + c] = NULL;
4786 }
4787 }
4788 }
4789 }
4790 }
4791 break;
4792 }
4793
4794 /* If this is a copy, add it to the ACP. */
4795 if (inst->op == TGSI_OPCODE_MOV &&
4796 inst->dst[0].file == PROGRAM_TEMPORARY &&
4797 !(inst->dst[0].file == inst->src[0].file &&
4798 inst->dst[0].index == inst->src[0].index) &&
4799 !inst->dst[0].reladdr &&
4800 !inst->dst[0].reladdr2 &&
4801 !inst->saturate &&
4802 inst->src[0].file != PROGRAM_ARRAY &&
4803 !inst->src[0].reladdr &&
4804 !inst->src[0].reladdr2 &&
4805 !inst->src[0].negate) {
4806 for (int i = 0; i < 4; i++) {
4807 if (inst->dst[0].writemask & (1 << i)) {
4808 acp[4 * inst->dst[0].index + i] = inst;
4809 acp_level[4 * inst->dst[0].index + i] = level;
4810 }
4811 }
4812 }
4813 }
4814
4815 ralloc_free(acp_level);
4816 ralloc_free(acp);
4817 }
4818
4819 /*
4820 * On a basic block basis, tracks available PROGRAM_TEMPORARY registers for dead
4821 * code elimination.
4822 *
4823 * The glsl_to_tgsi_visitor lazily produces code assuming that this pass
4824 * will occur. As an example, a TXP production after copy propagation but
4825 * before this pass:
4826 *
4827 * 0: MOV TEMP[1], INPUT[4].xyyy;
4828 * 1: MOV TEMP[1].w, INPUT[4].wwww;
4829 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4830 *
4831 * and after this pass:
4832 *
4833 * 0: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
4834 */
4835 int
4836 glsl_to_tgsi_visitor::eliminate_dead_code(void)
4837 {
4838 glsl_to_tgsi_instruction **writes = rzalloc_array(mem_ctx,
4839 glsl_to_tgsi_instruction *,
4840 this->next_temp * 4);
4841 int *write_level = rzalloc_array(mem_ctx, int, this->next_temp * 4);
4842 int level = 0;
4843 int removed = 0;
4844
4845 foreach_in_list(glsl_to_tgsi_instruction, inst, &this->instructions) {
4846 assert(inst->dst[0].file != PROGRAM_TEMPORARY
4847 || inst->dst[0].index < this->next_temp);
4848
4849 switch (inst->op) {
4850 case TGSI_OPCODE_BGNLOOP:
4851 case TGSI_OPCODE_ENDLOOP:
4852 case TGSI_OPCODE_CONT:
4853 case TGSI_OPCODE_BRK:
4854 /* End of a basic block, clear the write array entirely.
4855 *
4856 * This keeps us from killing dead code when the writes are
4857 * on either side of a loop, even when the register isn't touched
4858 * inside the loop. However, glsl_to_tgsi_visitor doesn't seem to emit
4859 * dead code of this type, so it shouldn't make a difference as long as
4860 * the dead code elimination pass in the GLSL compiler does its job.
4861 */
4862 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4863 break;
4864
4865 case TGSI_OPCODE_ENDIF:
4866 case TGSI_OPCODE_ELSE:
4867 /* Promote the recorded level of all channels written inside the
4868 * preceding if or else block to the level above the if/else block.
4869 */
4870 for (int r = 0; r < this->next_temp; r++) {
4871 for (int c = 0; c < 4; c++) {
4872 if (!writes[4 * r + c])
4873 continue;
4874
4875 if (write_level[4 * r + c] == level)
4876 write_level[4 * r + c] = level-1;
4877 }
4878 }
4879 if(inst->op == TGSI_OPCODE_ENDIF)
4880 --level;
4881 break;
4882
4883 case TGSI_OPCODE_IF:
4884 case TGSI_OPCODE_UIF:
4885 ++level;
4886 /* fallthrough to default case to mark the condition as read */
4887 default:
4888 /* Continuing the block, clear any channels from the write array that
4889 * are read by this instruction.
4890 */
4891 for (unsigned i = 0; i < ARRAY_SIZE(inst->src); i++) {
4892 if (inst->src[i].file == PROGRAM_TEMPORARY && inst->src[i].reladdr){
4893 /* Any temporary might be read, so no dead code elimination
4894 * across this instruction.
4895 */
4896 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4897 } else if (inst->src[i].file == PROGRAM_TEMPORARY) {
4898 /* Clear where it's used as src. */
4899 int src_chans = 1 << GET_SWZ(inst->src[i].swizzle, 0);
4900 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 1);
4901 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 2);
4902 src_chans |= 1 << GET_SWZ(inst->src[i].swizzle, 3);
4903
4904 for (int c = 0; c < 4; c++) {
4905 if (src_chans & (1 << c))
4906 writes[4 * inst->src[i].index + c] = NULL;
4907 }
4908 }
4909 }
4910 for (unsigned i = 0; i < inst->tex_offset_num_offset; i++) {
4911 if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY && inst->tex_offsets[i].reladdr){
4912 /* Any temporary might be read, so no dead code elimination
4913 * across this instruction.
4914 */
4915 memset(writes, 0, sizeof(*writes) * this->next_temp * 4);
4916 } else if (inst->tex_offsets[i].file == PROGRAM_TEMPORARY) {
4917 /* Clear where it's used as src. */
4918 int src_chans = 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 0);
4919 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 1);
4920 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 2);
4921 src_chans |= 1 << GET_SWZ(inst->tex_offsets[i].swizzle, 3);
4922
4923 for (int c = 0; c < 4; c++) {
4924 if (src_chans & (1 << c))
4925 writes[4 * inst->tex_offsets[i].index + c] = NULL;
4926 }
4927 }
4928 }
4929 break;
4930 }
4931
4932 /* If this instruction writes to a temporary, add it to the write array.
4933 * If there is already an instruction in the write array for one or more
4934 * of the channels, flag that channel write as dead.
4935 */
4936 for (unsigned i = 0; i < ARRAY_SIZE(inst->dst); i++) {
4937 if (inst->dst[i].file == PROGRAM_TEMPORARY &&
4938 !inst->dst[i].reladdr) {
4939 for (int c = 0; c < 4; c++) {
4940 if (inst->dst[i].writemask & (1 << c)) {
4941 if (writes[4 * inst->dst[i].index + c]) {
4942 if (write_level[4 * inst->dst[i].index + c] < level)
4943 continue;
4944 else
4945 writes[4 * inst->dst[i].index + c]->dead_mask |= (1 << c);
4946 }
4947 writes[4 * inst->dst[i].index + c] = inst;
4948 write_level[4 * inst->dst[i].index + c] = level;
4949 }
4950 }
4951 }
4952 }
4953 }
4954
4955 /* Anything still in the write array at this point is dead code. */
4956 for (int r = 0; r < this->next_temp; r++) {
4957 for (int c = 0; c < 4; c++) {
4958 glsl_to_tgsi_instruction *inst = writes[4 * r + c];
4959 if (inst)
4960 inst->dead_mask |= (1 << c);
4961 }
4962 }
4963
4964 /* Now actually remove the instructions that are completely dead and update
4965 * the writemask of other instructions with dead channels.
4966 */
4967 foreach_in_list_safe(glsl_to_tgsi_instruction, inst, &this->instructions) {
4968 if (!inst->dead_mask || !inst->dst[0].writemask)
4969 continue;
4970 /* No amount of dead masks should remove memory stores */
4971 if (inst->info->is_store)
4972 continue;
4973
4974 if ((inst->dst[0].writemask & ~inst->dead_mask) == 0) {
4975 inst->remove();
4976 delete inst;
4977 removed++;
4978 } else {
4979 if (glsl_base_type_is_64bit(inst->dst[0].type)) {
4980 if (inst->dead_mask == WRITEMASK_XY ||
4981 inst->dead_mask == WRITEMASK_ZW)
4982 inst->dst[0].writemask &= ~(inst->dead_mask);
4983 } else
4984 inst->dst[0].writemask &= ~(inst->dead_mask);
4985 }
4986 }
4987
4988 ralloc_free(write_level);
4989 ralloc_free(writes);
4990
4991 return removed;
4992 }
4993
4994 /* merge DFRACEXP instructions into one. */
4995 void
4996 glsl_to_tgsi_visitor::merge_two_dsts(void)
4997 {
4998 foreach_in_list_safe(glsl_to_tgsi_instruction, inst, &this->instructions) {
4999 glsl_to_tgsi_instruction *inst2;
5000 bool merged;
5001 if (num_inst_dst_regs(inst) != 2)
5002 continue;
5003
5004 if (inst->dst[0].file != PROGRAM_UNDEFINED &&
5005 inst->dst[1].file != PROGRAM_UNDEFINED)
5006 continue;
5007
5008 inst2 = (glsl_to_tgsi_instruction *) inst->next;
5009 do {
5010
5011 if (inst->src[0].file == inst2->src[0].file &&
5012 inst->src[0].index == inst2->src[0].index &&
5013 inst->src[0].type == inst2->src[0].type &&
5014 inst->src[0].swizzle == inst2->src[0].swizzle)
5015 break;
5016 inst2 = (glsl_to_tgsi_instruction *) inst2->next;
5017 } while (inst2);
5018
5019 if (!inst2)
5020 continue;
5021 merged = false;
5022 if (inst->dst[0].file == PROGRAM_UNDEFINED) {
5023 merged = true;
5024 inst->dst[0] = inst2->dst[0];
5025 } else if (inst->dst[1].file == PROGRAM_UNDEFINED) {
5026 inst->dst[1] = inst2->dst[1];
5027 merged = true;
5028 }
5029
5030 if (merged) {
5031 inst2->remove();
5032 delete inst2;
5033 }
5034 }
5035 }
5036
5037 /* Merges temporary registers together where possible to reduce the number of
5038 * registers needed to run a program.
5039 *
5040 * Produces optimal code only after copy propagation and dead code elimination
5041 * have been run. */
5042 void
5043 glsl_to_tgsi_visitor::merge_registers(void)
5044 {
5045 int *last_reads = rzalloc_array(mem_ctx, int, this->next_temp);
5046 int *first_writes = rzalloc_array(mem_ctx, int, this->next_temp);
5047 struct rename_reg_pair *renames = rzalloc_array(mem_ctx, struct rename_reg_pair, this->next_temp);
5048 int i, j;
5049 int num_renames = 0;
5050
5051 /* Read the indices of the last read and first write to each temp register
5052 * into an array so that we don't have to traverse the instruction list as
5053 * much. */
5054 for (i = 0; i < this->next_temp; i++) {
5055 last_reads[i] = -1;
5056 first_writes[i] = -1;
5057 }
5058 get_last_temp_read_first_temp_write(last_reads, first_writes);
5059
5060 /* Start looking for registers with non-overlapping usages that can be
5061 * merged together. */
5062 for (i = 0; i < this->next_temp; i++) {
5063 /* Don't touch unused registers. */
5064 if (last_reads[i] < 0 || first_writes[i] < 0) continue;
5065
5066 for (j = 0; j < this->next_temp; j++) {
5067 /* Don't touch unused registers. */
5068 if (last_reads[j] < 0 || first_writes[j] < 0) continue;
5069
5070 /* We can merge the two registers if the first write to j is after or
5071 * in the same instruction as the last read from i. Note that the
5072 * register at index i will always be used earlier or at the same time
5073 * as the register at index j. */
5074 if (first_writes[i] <= first_writes[j] &&
5075 last_reads[i] <= first_writes[j]) {
5076 renames[num_renames].old_reg = j;
5077 renames[num_renames].new_reg = i;
5078 num_renames++;
5079
5080 /* Update the first_writes and last_reads arrays with the new
5081 * values for the merged register index, and mark the newly unused
5082 * register index as such. */
5083 assert(last_reads[j] >= last_reads[i]);
5084 last_reads[i] = last_reads[j];
5085 first_writes[j] = -1;
5086 last_reads[j] = -1;
5087 }
5088 }
5089 }
5090
5091 rename_temp_registers(num_renames, renames);
5092 ralloc_free(renames);
5093 ralloc_free(last_reads);
5094 ralloc_free(first_writes);
5095 }
5096
5097 /* Reassign indices to temporary registers by reusing unused indices created
5098 * by optimization passes. */
5099 void
5100 glsl_to_tgsi_visitor::renumber_registers(void)
5101 {
5102 int i = 0;
5103 int new_index = 0;
5104 int *first_reads = rzalloc_array(mem_ctx, int, this->next_temp);
5105 struct rename_reg_pair *renames = rzalloc_array(mem_ctx, struct rename_reg_pair, this->next_temp);
5106 int num_renames = 0;
5107 for (i = 0; i < this->next_temp; i++) {
5108 first_reads[i] = -1;
5109 }
5110 get_first_temp_read(first_reads);
5111
5112 for (i = 0; i < this->next_temp; i++) {
5113 if (first_reads[i] < 0) continue;
5114 if (i != new_index) {
5115 renames[num_renames].old_reg = i;
5116 renames[num_renames].new_reg = new_index;
5117 num_renames++;
5118 }
5119 new_index++;
5120 }
5121
5122 rename_temp_registers(num_renames, renames);
5123 this->next_temp = new_index;
5124 ralloc_free(renames);
5125 ralloc_free(first_reads);
5126 }
5127
5128 /* ------------------------- TGSI conversion stuff -------------------------- */
5129 struct label {
5130 unsigned branch_target;
5131 unsigned token;
5132 };
5133
5134 /**
5135 * Intermediate state used during shader translation.
5136 */
5137 struct st_translate {
5138 struct ureg_program *ureg;
5139
5140 unsigned temps_size;
5141 struct ureg_dst *temps;
5142
5143 struct ureg_dst *arrays;
5144 unsigned num_temp_arrays;
5145 struct ureg_src *constants;
5146 int num_constants;
5147 struct ureg_src *immediates;
5148 int num_immediates;
5149 struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
5150 struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
5151 struct ureg_dst address[3];
5152 struct ureg_src samplers[PIPE_MAX_SAMPLERS];
5153 struct ureg_src buffers[PIPE_MAX_SHADER_BUFFERS];
5154 struct ureg_src images[PIPE_MAX_SHADER_IMAGES];
5155 struct ureg_src systemValues[SYSTEM_VALUE_MAX];
5156 struct ureg_src shared_memory;
5157 struct tgsi_texture_offset tex_offsets[MAX_GLSL_TEXTURE_OFFSET];
5158 unsigned *array_sizes;
5159 struct array_decl *input_arrays;
5160 struct array_decl *output_arrays;
5161
5162 const GLuint *inputMapping;
5163 const GLuint *outputMapping;
5164
5165 /* For every instruction that contains a label (eg CALL), keep
5166 * details so that we can go back afterwards and emit the correct
5167 * tgsi instruction number for each label.
5168 */
5169 struct label *labels;
5170 unsigned labels_size;
5171 unsigned labels_count;
5172
5173 /* Keep a record of the tgsi instruction number that each mesa
5174 * instruction starts at, will be used to fix up labels after
5175 * translation.
5176 */
5177 unsigned *insn;
5178 unsigned insn_size;
5179 unsigned insn_count;
5180
5181 unsigned procType; /**< PIPE_SHADER_VERTEX/FRAGMENT */
5182
5183 boolean error;
5184 };
5185
5186 /** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
5187 unsigned
5188 _mesa_sysval_to_semantic(unsigned sysval)
5189 {
5190 switch (sysval) {
5191 /* Vertex shader */
5192 case SYSTEM_VALUE_VERTEX_ID:
5193 return TGSI_SEMANTIC_VERTEXID;
5194 case SYSTEM_VALUE_INSTANCE_ID:
5195 return TGSI_SEMANTIC_INSTANCEID;
5196 case SYSTEM_VALUE_VERTEX_ID_ZERO_BASE:
5197 return TGSI_SEMANTIC_VERTEXID_NOBASE;
5198 case SYSTEM_VALUE_BASE_VERTEX:
5199 return TGSI_SEMANTIC_BASEVERTEX;
5200 case SYSTEM_VALUE_BASE_INSTANCE:
5201 return TGSI_SEMANTIC_BASEINSTANCE;
5202 case SYSTEM_VALUE_DRAW_ID:
5203 return TGSI_SEMANTIC_DRAWID;
5204
5205 /* Geometry shader */
5206 case SYSTEM_VALUE_INVOCATION_ID:
5207 return TGSI_SEMANTIC_INVOCATIONID;
5208
5209 /* Fragment shader */
5210 case SYSTEM_VALUE_FRAG_COORD:
5211 return TGSI_SEMANTIC_POSITION;
5212 case SYSTEM_VALUE_FRONT_FACE:
5213 return TGSI_SEMANTIC_FACE;
5214 case SYSTEM_VALUE_SAMPLE_ID:
5215 return TGSI_SEMANTIC_SAMPLEID;
5216 case SYSTEM_VALUE_SAMPLE_POS:
5217 return TGSI_SEMANTIC_SAMPLEPOS;
5218 case SYSTEM_VALUE_SAMPLE_MASK_IN:
5219 return TGSI_SEMANTIC_SAMPLEMASK;
5220 case SYSTEM_VALUE_HELPER_INVOCATION:
5221 return TGSI_SEMANTIC_HELPER_INVOCATION;
5222
5223 /* Tessellation shader */
5224 case SYSTEM_VALUE_TESS_COORD:
5225 return TGSI_SEMANTIC_TESSCOORD;
5226 case SYSTEM_VALUE_VERTICES_IN:
5227 return TGSI_SEMANTIC_VERTICESIN;
5228 case SYSTEM_VALUE_PRIMITIVE_ID:
5229 return TGSI_SEMANTIC_PRIMID;
5230 case SYSTEM_VALUE_TESS_LEVEL_OUTER:
5231 return TGSI_SEMANTIC_TESSOUTER;
5232 case SYSTEM_VALUE_TESS_LEVEL_INNER:
5233 return TGSI_SEMANTIC_TESSINNER;
5234
5235 /* Compute shader */
5236 case SYSTEM_VALUE_LOCAL_INVOCATION_ID:
5237 return TGSI_SEMANTIC_THREAD_ID;
5238 case SYSTEM_VALUE_WORK_GROUP_ID:
5239 return TGSI_SEMANTIC_BLOCK_ID;
5240 case SYSTEM_VALUE_NUM_WORK_GROUPS:
5241 return TGSI_SEMANTIC_GRID_SIZE;
5242
5243 /* Unhandled */
5244 case SYSTEM_VALUE_LOCAL_INVOCATION_INDEX:
5245 case SYSTEM_VALUE_GLOBAL_INVOCATION_ID:
5246 case SYSTEM_VALUE_VERTEX_CNT:
5247 default:
5248 assert(!"Unexpected SYSTEM_VALUE_ enum");
5249 return TGSI_SEMANTIC_COUNT;
5250 }
5251 }
5252
5253
5254 /**
5255 * Make note of a branch to a label in the TGSI code.
5256 * After we've emitted all instructions, we'll go over the list
5257 * of labels built here and patch the TGSI code with the actual
5258 * location of each label.
5259 */
5260 static unsigned *get_label(struct st_translate *t, unsigned branch_target)
5261 {
5262 unsigned i;
5263
5264 if (t->labels_count + 1 >= t->labels_size) {
5265 t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
5266 t->labels = (struct label *)realloc(t->labels,
5267 t->labels_size * sizeof(struct label));
5268 if (t->labels == NULL) {
5269 static unsigned dummy;
5270 t->error = TRUE;
5271 return &dummy;
5272 }
5273 }
5274
5275 i = t->labels_count++;
5276 t->labels[i].branch_target = branch_target;
5277 return &t->labels[i].token;
5278 }
5279
5280 /**
5281 * Called prior to emitting the TGSI code for each instruction.
5282 * Allocate additional space for instructions if needed.
5283 * Update the insn[] array so the next glsl_to_tgsi_instruction points to
5284 * the next TGSI instruction.
5285 */
5286 static void set_insn_start(struct st_translate *t, unsigned start)
5287 {
5288 if (t->insn_count + 1 >= t->insn_size) {
5289 t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
5290 t->insn = (unsigned *)realloc(t->insn, t->insn_size * sizeof(t->insn[0]));
5291 if (t->insn == NULL) {
5292 t->error = TRUE;
5293 return;
5294 }
5295 }
5296
5297 t->insn[t->insn_count++] = start;
5298 }
5299
5300 /**
5301 * Map a glsl_to_tgsi constant/immediate to a TGSI immediate.
5302 */
5303 static struct ureg_src
5304 emit_immediate(struct st_translate *t,
5305 gl_constant_value values[4],
5306 int type, int size)
5307 {
5308 struct ureg_program *ureg = t->ureg;
5309
5310 switch(type)
5311 {
5312 case GL_FLOAT:
5313 return ureg_DECL_immediate(ureg, &values[0].f, size);
5314 case GL_DOUBLE:
5315 return ureg_DECL_immediate_f64(ureg, (double *)&values[0].f, size);
5316 case GL_INT:
5317 return ureg_DECL_immediate_int(ureg, &values[0].i, size);
5318 case GL_UNSIGNED_INT:
5319 case GL_BOOL:
5320 return ureg_DECL_immediate_uint(ureg, &values[0].u, size);
5321 default:
5322 assert(!"should not get here - type must be float, int, uint, or bool");
5323 return ureg_src_undef();
5324 }
5325 }
5326
5327 /**
5328 * Map a glsl_to_tgsi dst register to a TGSI ureg_dst register.
5329 */
5330 static struct ureg_dst
5331 dst_register(struct st_translate *t, gl_register_file file, unsigned index,
5332 unsigned array_id)
5333 {
5334 unsigned array;
5335
5336 switch(file) {
5337 case PROGRAM_UNDEFINED:
5338 return ureg_dst_undef();
5339
5340 case PROGRAM_TEMPORARY:
5341 /* Allocate space for temporaries on demand. */
5342 if (index >= t->temps_size) {
5343 const int inc = align(index - t->temps_size + 1, 4096);
5344
5345 t->temps = (struct ureg_dst*)
5346 realloc(t->temps,
5347 (t->temps_size + inc) * sizeof(struct ureg_dst));
5348 if (!t->temps)
5349 return ureg_dst_undef();
5350
5351 memset(t->temps + t->temps_size, 0, inc * sizeof(struct ureg_dst));
5352 t->temps_size += inc;
5353 }
5354
5355 if (ureg_dst_is_undef(t->temps[index]))
5356 t->temps[index] = ureg_DECL_local_temporary(t->ureg);
5357
5358 return t->temps[index];
5359
5360 case PROGRAM_ARRAY:
5361 array = index >> 16;
5362
5363 assert(array < t->num_temp_arrays);
5364
5365 if (ureg_dst_is_undef(t->arrays[array]))
5366 t->arrays[array] = ureg_DECL_array_temporary(
5367 t->ureg, t->array_sizes[array], TRUE);
5368
5369 return ureg_dst_array_offset(t->arrays[array],
5370 (int)(index & 0xFFFF) - 0x8000);
5371
5372 case PROGRAM_OUTPUT:
5373 if (!array_id) {
5374 if (t->procType == PIPE_SHADER_FRAGMENT)
5375 assert(index < 2 * FRAG_RESULT_MAX);
5376 else if (t->procType == PIPE_SHADER_TESS_CTRL ||
5377 t->procType == PIPE_SHADER_TESS_EVAL)
5378 assert(index < VARYING_SLOT_TESS_MAX);
5379 else
5380 assert(index < VARYING_SLOT_MAX);
5381
5382 assert(t->outputMapping[index] < ARRAY_SIZE(t->outputs));
5383 assert(t->outputs[t->outputMapping[index]].File != TGSI_FILE_NULL);
5384 return t->outputs[t->outputMapping[index]];
5385 }
5386 else {
5387 struct array_decl *decl = &t->output_arrays[array_id-1];
5388 unsigned mesa_index = decl->mesa_index;
5389 int slot = t->outputMapping[mesa_index];
5390
5391 assert(slot != -1 && t->outputs[slot].File == TGSI_FILE_OUTPUT);
5392 assert(t->outputs[slot].ArrayID == array_id);
5393 return ureg_dst_array_offset(t->outputs[slot], index - mesa_index);
5394 }
5395
5396 case PROGRAM_ADDRESS:
5397 return t->address[index];
5398
5399 default:
5400 assert(!"unknown dst register file");
5401 return ureg_dst_undef();
5402 }
5403 }
5404
5405 /**
5406 * Map a glsl_to_tgsi src register to a TGSI ureg_src register.
5407 */
5408 static struct ureg_src
5409 src_register(struct st_translate *t, const st_src_reg *reg)
5410 {
5411 int index = reg->index;
5412 int double_reg2 = reg->double_reg2 ? 1 : 0;
5413
5414 switch(reg->file) {
5415 case PROGRAM_UNDEFINED:
5416 return ureg_imm4f(t->ureg, 0, 0, 0, 0);
5417
5418 case PROGRAM_TEMPORARY:
5419 case PROGRAM_ARRAY:
5420 case PROGRAM_OUTPUT:
5421 return ureg_src(dst_register(t, reg->file, reg->index, reg->array_id));
5422
5423 case PROGRAM_UNIFORM:
5424 assert(reg->index >= 0);
5425 return reg->index < t->num_constants ?
5426 t->constants[reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
5427 case PROGRAM_STATE_VAR:
5428 case PROGRAM_CONSTANT: /* ie, immediate */
5429 if (reg->has_index2)
5430 return ureg_src_register(TGSI_FILE_CONSTANT, reg->index);
5431 else
5432 return reg->index >= 0 && reg->index < t->num_constants ?
5433 t->constants[reg->index] : ureg_imm4f(t->ureg, 0, 0, 0, 0);
5434
5435 case PROGRAM_IMMEDIATE:
5436 assert(reg->index >= 0 && reg->index < t->num_immediates);
5437 return t->immediates[reg->index];
5438
5439 case PROGRAM_INPUT:
5440 /* GLSL inputs are 64-bit containers, so we have to
5441 * map back to the original index and add the offset after
5442 * mapping. */
5443 index -= double_reg2;
5444 if (!reg->array_id) {
5445 assert(t->inputMapping[index] < ARRAY_SIZE(t->inputs));
5446 assert(t->inputs[t->inputMapping[index]].File != TGSI_FILE_NULL);
5447 return t->inputs[t->inputMapping[index] + double_reg2];
5448 }
5449 else {
5450 struct array_decl *decl = &t->input_arrays[reg->array_id-1];
5451 unsigned mesa_index = decl->mesa_index;
5452 int slot = t->inputMapping[mesa_index];
5453
5454 assert(slot != -1 && t->inputs[slot].File == TGSI_FILE_INPUT);
5455 assert(t->inputs[slot].ArrayID == reg->array_id);
5456 return ureg_src_array_offset(t->inputs[slot], index + double_reg2 - mesa_index);
5457 }
5458
5459 case PROGRAM_ADDRESS:
5460 return ureg_src(t->address[reg->index]);
5461
5462 case PROGRAM_SYSTEM_VALUE:
5463 assert(reg->index < (int) ARRAY_SIZE(t->systemValues));
5464 return t->systemValues[reg->index];
5465
5466 default:
5467 assert(!"unknown src register file");
5468 return ureg_src_undef();
5469 }
5470 }
5471
5472 /**
5473 * Create a TGSI ureg_dst register from an st_dst_reg.
5474 */
5475 static struct ureg_dst
5476 translate_dst(struct st_translate *t,
5477 const st_dst_reg *dst_reg,
5478 bool saturate)
5479 {
5480 struct ureg_dst dst = dst_register(t, dst_reg->file, dst_reg->index,
5481 dst_reg->array_id);
5482
5483 if (dst.File == TGSI_FILE_NULL)
5484 return dst;
5485
5486 dst = ureg_writemask(dst, dst_reg->writemask);
5487
5488 if (saturate)
5489 dst = ureg_saturate(dst);
5490
5491 if (dst_reg->reladdr != NULL) {
5492 assert(dst_reg->file != PROGRAM_TEMPORARY);
5493 dst = ureg_dst_indirect(dst, ureg_src(t->address[0]));
5494 }
5495
5496 if (dst_reg->has_index2) {
5497 if (dst_reg->reladdr2)
5498 dst = ureg_dst_dimension_indirect(dst, ureg_src(t->address[1]),
5499 dst_reg->index2D);
5500 else
5501 dst = ureg_dst_dimension(dst, dst_reg->index2D);
5502 }
5503
5504 return dst;
5505 }
5506
5507 /**
5508 * Create a TGSI ureg_src register from an st_src_reg.
5509 */
5510 static struct ureg_src
5511 translate_src(struct st_translate *t, const st_src_reg *src_reg)
5512 {
5513 struct ureg_src src = src_register(t, src_reg);
5514
5515 if (src_reg->has_index2) {
5516 /* 2D indexes occur with geometry shader inputs (attrib, vertex)
5517 * and UBO constant buffers (buffer, position).
5518 */
5519 if (src_reg->reladdr2)
5520 src = ureg_src_dimension_indirect(src, ureg_src(t->address[1]),
5521 src_reg->index2D);
5522 else
5523 src = ureg_src_dimension(src, src_reg->index2D);
5524 }
5525
5526 src = ureg_swizzle(src,
5527 GET_SWZ(src_reg->swizzle, 0) & 0x3,
5528 GET_SWZ(src_reg->swizzle, 1) & 0x3,
5529 GET_SWZ(src_reg->swizzle, 2) & 0x3,
5530 GET_SWZ(src_reg->swizzle, 3) & 0x3);
5531
5532 if ((src_reg->negate & 0xf) == NEGATE_XYZW)
5533 src = ureg_negate(src);
5534
5535 if (src_reg->reladdr != NULL) {
5536 assert(src_reg->file != PROGRAM_TEMPORARY);
5537 src = ureg_src_indirect(src, ureg_src(t->address[0]));
5538 }
5539
5540 return src;
5541 }
5542
5543 static struct tgsi_texture_offset
5544 translate_tex_offset(struct st_translate *t,
5545 const st_src_reg *in_offset, int idx)
5546 {
5547 struct tgsi_texture_offset offset;
5548 struct ureg_src imm_src;
5549 struct ureg_dst dst;
5550 int array;
5551
5552 switch (in_offset->file) {
5553 case PROGRAM_IMMEDIATE:
5554 assert(in_offset->index >= 0 && in_offset->index < t->num_immediates);
5555 imm_src = t->immediates[in_offset->index];
5556
5557 offset.File = imm_src.File;
5558 offset.Index = imm_src.Index;
5559 offset.SwizzleX = imm_src.SwizzleX;
5560 offset.SwizzleY = imm_src.SwizzleY;
5561 offset.SwizzleZ = imm_src.SwizzleZ;
5562 offset.Padding = 0;
5563 break;
5564 case PROGRAM_INPUT:
5565 imm_src = t->inputs[t->inputMapping[in_offset->index]];
5566 offset.File = imm_src.File;
5567 offset.Index = imm_src.Index;
5568 offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5569 offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5570 offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5571 offset.Padding = 0;
5572 break;
5573 case PROGRAM_TEMPORARY:
5574 imm_src = ureg_src(t->temps[in_offset->index]);
5575 offset.File = imm_src.File;
5576 offset.Index = imm_src.Index;
5577 offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5578 offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5579 offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5580 offset.Padding = 0;
5581 break;
5582 case PROGRAM_ARRAY:
5583 array = in_offset->index >> 16;
5584
5585 assert(array >= 0);
5586 assert(array < (int)t->num_temp_arrays);
5587
5588 dst = t->arrays[array];
5589 offset.File = dst.File;
5590 offset.Index = dst.Index + (in_offset->index & 0xFFFF) - 0x8000;
5591 offset.SwizzleX = GET_SWZ(in_offset->swizzle, 0);
5592 offset.SwizzleY = GET_SWZ(in_offset->swizzle, 1);
5593 offset.SwizzleZ = GET_SWZ(in_offset->swizzle, 2);
5594 offset.Padding = 0;
5595 break;
5596 default:
5597 break;
5598 }
5599 return offset;
5600 }
5601
5602 static void
5603 compile_tgsi_instruction(struct st_translate *t,
5604 const glsl_to_tgsi_instruction *inst)
5605 {
5606 struct ureg_program *ureg = t->ureg;
5607 int i;
5608 struct ureg_dst dst[2];
5609 struct ureg_src src[4];
5610 struct tgsi_texture_offset texoffsets[MAX_GLSL_TEXTURE_OFFSET];
5611
5612 int num_dst;
5613 int num_src;
5614 unsigned tex_target = 0;
5615
5616 num_dst = num_inst_dst_regs(inst);
5617 num_src = num_inst_src_regs(inst);
5618
5619 for (i = 0; i < num_dst; i++)
5620 dst[i] = translate_dst(t,
5621 &inst->dst[i],
5622 inst->saturate);
5623
5624 for (i = 0; i < num_src; i++)
5625 src[i] = translate_src(t, &inst->src[i]);
5626
5627 switch(inst->op) {
5628 case TGSI_OPCODE_BGNLOOP:
5629 case TGSI_OPCODE_CAL:
5630 case TGSI_OPCODE_ELSE:
5631 case TGSI_OPCODE_ENDLOOP:
5632 case TGSI_OPCODE_IF:
5633 case TGSI_OPCODE_UIF:
5634 assert(num_dst == 0);
5635 ureg_label_insn(ureg,
5636 inst->op,
5637 src, num_src,
5638 get_label(t,
5639 inst->op == TGSI_OPCODE_CAL ? inst->function->sig_id : 0));
5640 return;
5641
5642 case TGSI_OPCODE_TEX:
5643 case TGSI_OPCODE_TXB:
5644 case TGSI_OPCODE_TXD:
5645 case TGSI_OPCODE_TXL:
5646 case TGSI_OPCODE_TXP:
5647 case TGSI_OPCODE_TXQ:
5648 case TGSI_OPCODE_TXQS:
5649 case TGSI_OPCODE_TXF:
5650 case TGSI_OPCODE_TEX2:
5651 case TGSI_OPCODE_TXB2:
5652 case TGSI_OPCODE_TXL2:
5653 case TGSI_OPCODE_TG4:
5654 case TGSI_OPCODE_LODQ:
5655 src[num_src] = t->samplers[inst->sampler.index];
5656 assert(src[num_src].File != TGSI_FILE_NULL);
5657 if (inst->sampler.reladdr)
5658 src[num_src] =
5659 ureg_src_indirect(src[num_src], ureg_src(t->address[2]));
5660 num_src++;
5661 for (i = 0; i < (int)inst->tex_offset_num_offset; i++) {
5662 texoffsets[i] = translate_tex_offset(t, &inst->tex_offsets[i], i);
5663 }
5664 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5665
5666 ureg_tex_insn(ureg,
5667 inst->op,
5668 dst, num_dst,
5669 tex_target,
5670 texoffsets, inst->tex_offset_num_offset,
5671 src, num_src);
5672 return;
5673
5674 case TGSI_OPCODE_RESQ:
5675 case TGSI_OPCODE_LOAD:
5676 case TGSI_OPCODE_ATOMUADD:
5677 case TGSI_OPCODE_ATOMXCHG:
5678 case TGSI_OPCODE_ATOMCAS:
5679 case TGSI_OPCODE_ATOMAND:
5680 case TGSI_OPCODE_ATOMOR:
5681 case TGSI_OPCODE_ATOMXOR:
5682 case TGSI_OPCODE_ATOMUMIN:
5683 case TGSI_OPCODE_ATOMUMAX:
5684 case TGSI_OPCODE_ATOMIMIN:
5685 case TGSI_OPCODE_ATOMIMAX:
5686 for (i = num_src - 1; i >= 0; i--)
5687 src[i + 1] = src[i];
5688 num_src++;
5689 if (inst->buffer.file == PROGRAM_MEMORY) {
5690 src[0] = t->shared_memory;
5691 } else if (inst->buffer.file == PROGRAM_BUFFER) {
5692 src[0] = t->buffers[inst->buffer.index];
5693 } else {
5694 src[0] = t->images[inst->buffer.index];
5695 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5696 }
5697 if (inst->buffer.reladdr)
5698 src[0] = ureg_src_indirect(src[0], ureg_src(t->address[2]));
5699 assert(src[0].File != TGSI_FILE_NULL);
5700 ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
5701 inst->buffer_access,
5702 tex_target, inst->image_format);
5703 break;
5704
5705 case TGSI_OPCODE_STORE:
5706 if (inst->buffer.file == PROGRAM_MEMORY) {
5707 dst[0] = ureg_dst(t->shared_memory);
5708 } else if (inst->buffer.file == PROGRAM_BUFFER) {
5709 dst[0] = ureg_dst(t->buffers[inst->buffer.index]);
5710 } else {
5711 dst[0] = ureg_dst(t->images[inst->buffer.index]);
5712 tex_target = st_translate_texture_target(inst->tex_target, inst->tex_shadow);
5713 }
5714 dst[0] = ureg_writemask(dst[0], inst->dst[0].writemask);
5715 if (inst->buffer.reladdr)
5716 dst[0] = ureg_dst_indirect(dst[0], ureg_src(t->address[2]));
5717 assert(dst[0].File != TGSI_FILE_NULL);
5718 ureg_memory_insn(ureg, inst->op, dst, num_dst, src, num_src,
5719 inst->buffer_access,
5720 tex_target, inst->image_format);
5721 break;
5722
5723 case TGSI_OPCODE_SCS:
5724 dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY);
5725 ureg_insn(ureg, inst->op, dst, num_dst, src, num_src);
5726 break;
5727
5728 default:
5729 ureg_insn(ureg,
5730 inst->op,
5731 dst, num_dst,
5732 src, num_src);
5733 break;
5734 }
5735 }
5736
5737 /**
5738 * Emit the TGSI instructions for inverting and adjusting WPOS.
5739 * This code is unavoidable because it also depends on whether
5740 * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
5741 */
5742 static void
5743 emit_wpos_adjustment(struct gl_context *ctx,
5744 struct st_translate *t,
5745 int wpos_transform_const,
5746 boolean invert,
5747 GLfloat adjX, GLfloat adjY[2])
5748 {
5749 struct ureg_program *ureg = t->ureg;
5750
5751 assert(wpos_transform_const >= 0);
5752
5753 /* Fragment program uses fragment position input.
5754 * Need to replace instances of INPUT[WPOS] with temp T
5755 * where T = INPUT[WPOS] is inverted by Y.
5756 */
5757 struct ureg_src wpostrans = ureg_DECL_constant(ureg, wpos_transform_const);
5758 struct ureg_dst wpos_temp = ureg_DECL_temporary( ureg );
5759 struct ureg_src *wpos =
5760 ctx->Const.GLSLFragCoordIsSysVal ?
5761 &t->systemValues[SYSTEM_VALUE_FRAG_COORD] :
5762 &t->inputs[t->inputMapping[VARYING_SLOT_POS]];
5763 struct ureg_src wpos_input = *wpos;
5764
5765 /* First, apply the coordinate shift: */
5766 if (adjX || adjY[0] || adjY[1]) {
5767 if (adjY[0] != adjY[1]) {
5768 /* Adjust the y coordinate by adjY[1] or adjY[0] respectively
5769 * depending on whether inversion is actually going to be applied
5770 * or not, which is determined by testing against the inversion
5771 * state variable used below, which will be either +1 or -1.
5772 */
5773 struct ureg_dst adj_temp = ureg_DECL_local_temporary(ureg);
5774
5775 ureg_CMP(ureg, adj_temp,
5776 ureg_scalar(wpostrans, invert ? 2 : 0),
5777 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f),
5778 ureg_imm4f(ureg, adjX, adjY[1], 0.0f, 0.0f));
5779 ureg_ADD(ureg, wpos_temp, wpos_input, ureg_src(adj_temp));
5780 } else {
5781 ureg_ADD(ureg, wpos_temp, wpos_input,
5782 ureg_imm4f(ureg, adjX, adjY[0], 0.0f, 0.0f));
5783 }
5784 wpos_input = ureg_src(wpos_temp);
5785 } else {
5786 /* MOV wpos_temp, input[wpos]
5787 */
5788 ureg_MOV( ureg, wpos_temp, wpos_input );
5789 }
5790
5791 /* Now the conditional y flip: STATE_FB_WPOS_Y_TRANSFORM.xy/zw will be
5792 * inversion/identity, or the other way around if we're drawing to an FBO.
5793 */
5794 if (invert) {
5795 /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
5796 */
5797 ureg_MAD( ureg,
5798 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
5799 wpos_input,
5800 ureg_scalar(wpostrans, 0),
5801 ureg_scalar(wpostrans, 1));
5802 } else {
5803 /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
5804 */
5805 ureg_MAD( ureg,
5806 ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
5807 wpos_input,
5808 ureg_scalar(wpostrans, 2),
5809 ureg_scalar(wpostrans, 3));
5810 }
5811
5812 /* Use wpos_temp as position input from here on:
5813 */
5814 *wpos = ureg_src(wpos_temp);
5815 }
5816
5817
5818 /**
5819 * Emit fragment position/ooordinate code.
5820 */
5821 static void
5822 emit_wpos(struct st_context *st,
5823 struct st_translate *t,
5824 const struct gl_program *program,
5825 struct ureg_program *ureg,
5826 int wpos_transform_const)
5827 {
5828 const struct gl_fragment_program *fp =
5829 (const struct gl_fragment_program *) program;
5830 struct pipe_screen *pscreen = st->pipe->screen;
5831 GLfloat adjX = 0.0f;
5832 GLfloat adjY[2] = { 0.0f, 0.0f };
5833 boolean invert = FALSE;
5834
5835 /* Query the pixel center conventions supported by the pipe driver and set
5836 * adjX, adjY to help out if it cannot handle the requested one internally.
5837 *
5838 * The bias of the y-coordinate depends on whether y-inversion takes place
5839 * (adjY[1]) or not (adjY[0]), which is in turn dependent on whether we are
5840 * drawing to an FBO (causes additional inversion), and whether the pipe
5841 * driver origin and the requested origin differ (the latter condition is
5842 * stored in the 'invert' variable).
5843 *
5844 * For height = 100 (i = integer, h = half-integer, l = lower, u = upper):
5845 *
5846 * center shift only:
5847 * i -> h: +0.5
5848 * h -> i: -0.5
5849 *
5850 * inversion only:
5851 * l,i -> u,i: ( 0.0 + 1.0) * -1 + 100 = 99
5852 * l,h -> u,h: ( 0.5 + 0.0) * -1 + 100 = 99.5
5853 * u,i -> l,i: (99.0 + 1.0) * -1 + 100 = 0
5854 * u,h -> l,h: (99.5 + 0.0) * -1 + 100 = 0.5
5855 *
5856 * inversion and center shift:
5857 * l,i -> u,h: ( 0.0 + 0.5) * -1 + 100 = 99.5
5858 * l,h -> u,i: ( 0.5 + 0.5) * -1 + 100 = 99
5859 * u,i -> l,h: (99.0 + 0.5) * -1 + 100 = 0.5
5860 * u,h -> l,i: (99.5 + 0.5) * -1 + 100 = 0
5861 */
5862 if (fp->OriginUpperLeft) {
5863 /* Fragment shader wants origin in upper-left */
5864 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
5865 /* the driver supports upper-left origin */
5866 }
5867 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
5868 /* the driver supports lower-left origin, need to invert Y */
5869 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
5870 TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
5871 invert = TRUE;
5872 }
5873 else
5874 assert(0);
5875 }
5876 else {
5877 /* Fragment shader wants origin in lower-left */
5878 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
5879 /* the driver supports lower-left origin */
5880 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_ORIGIN,
5881 TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
5882 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
5883 /* the driver supports upper-left origin, need to invert Y */
5884 invert = TRUE;
5885 else
5886 assert(0);
5887 }
5888
5889 if (fp->PixelCenterInteger) {
5890 /* Fragment shader wants pixel center integer */
5891 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
5892 /* the driver supports pixel center integer */
5893 adjY[1] = 1.0f;
5894 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
5895 TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
5896 }
5897 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
5898 /* the driver supports pixel center half integer, need to bias X,Y */
5899 adjX = -0.5f;
5900 adjY[0] = -0.5f;
5901 adjY[1] = 0.5f;
5902 }
5903 else
5904 assert(0);
5905 }
5906 else {
5907 /* Fragment shader wants pixel center half integer */
5908 if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
5909 /* the driver supports pixel center half integer */
5910 }
5911 else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
5912 /* the driver supports pixel center integer, need to bias X,Y */
5913 adjX = adjY[0] = adjY[1] = 0.5f;
5914 ureg_property(ureg, TGSI_PROPERTY_FS_COORD_PIXEL_CENTER,
5915 TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
5916 }
5917 else
5918 assert(0);
5919 }
5920
5921 /* we invert after adjustment so that we avoid the MOV to temporary,
5922 * and reuse the adjustment ADD instead */
5923 emit_wpos_adjustment(st->ctx, t, wpos_transform_const, invert, adjX, adjY);
5924 }
5925
5926 /**
5927 * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
5928 * TGSI uses +1 for front, -1 for back.
5929 * This function converts the TGSI value to the GL value. Simply clamping/
5930 * saturating the value to [0,1] does the job.
5931 */
5932 static void
5933 emit_face_var(struct gl_context *ctx, struct st_translate *t)
5934 {
5935 struct ureg_program *ureg = t->ureg;
5936 struct ureg_dst face_temp = ureg_DECL_temporary(ureg);
5937 struct ureg_src face_input = t->inputs[t->inputMapping[VARYING_SLOT_FACE]];
5938
5939 if (ctx->Const.NativeIntegers) {
5940 ureg_FSGE(ureg, face_temp, face_input, ureg_imm1f(ureg, 0));
5941 }
5942 else {
5943 /* MOV_SAT face_temp, input[face] */
5944 ureg_MOV(ureg, ureg_saturate(face_temp), face_input);
5945 }
5946
5947 /* Use face_temp as face input from here on: */
5948 t->inputs[t->inputMapping[VARYING_SLOT_FACE]] = ureg_src(face_temp);
5949 }
5950
5951 static bool
5952 find_array(unsigned attr, struct array_decl *arrays, unsigned count,
5953 unsigned *array_id, unsigned *array_size)
5954 {
5955 unsigned i;
5956
5957 for (i = 0; i < count; i++) {
5958 struct array_decl *decl = &arrays[i];
5959
5960 if (attr == decl->mesa_index) {
5961 *array_id = decl->array_id;
5962 *array_size = decl->array_size;
5963 assert(*array_size);
5964 return true;
5965 }
5966 }
5967 return false;
5968 }
5969
5970 static void
5971 emit_compute_block_size(const struct gl_program *program,
5972 struct ureg_program *ureg) {
5973 const struct gl_compute_program *cp =
5974 (const struct gl_compute_program *)program;
5975
5976 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH,
5977 cp->LocalSize[0]);
5978 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT,
5979 cp->LocalSize[1]);
5980 ureg_property(ureg, TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH,
5981 cp->LocalSize[2]);
5982 }
5983
5984 /**
5985 * Translate intermediate IR (glsl_to_tgsi_instruction) to TGSI format.
5986 * \param program the program to translate
5987 * \param numInputs number of input registers used
5988 * \param inputMapping maps Mesa fragment program inputs to TGSI generic
5989 * input indexes
5990 * \param inputSemanticName the TGSI_SEMANTIC flag for each input
5991 * \param inputSemanticIndex the semantic index (ex: which texcoord) for
5992 * each input
5993 * \param interpMode the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
5994 * \param interpLocation the TGSI_INTERPOLATE_LOC_* location for each input
5995 * \param numOutputs number of output registers used
5996 * \param outputMapping maps Mesa fragment program outputs to TGSI
5997 * generic outputs
5998 * \param outputSemanticName the TGSI_SEMANTIC flag for each output
5999 * \param outputSemanticIndex the semantic index (ex: which texcoord) for
6000 * each output
6001 *
6002 * \return PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
6003 */
6004 extern "C" enum pipe_error
6005 st_translate_program(
6006 struct gl_context *ctx,
6007 uint procType,
6008 struct ureg_program *ureg,
6009 glsl_to_tgsi_visitor *program,
6010 const struct gl_program *proginfo,
6011 GLuint numInputs,
6012 const GLuint inputMapping[],
6013 const GLuint inputSlotToAttr[],
6014 const ubyte inputSemanticName[],
6015 const ubyte inputSemanticIndex[],
6016 const GLuint interpMode[],
6017 const GLuint interpLocation[],
6018 GLuint numOutputs,
6019 const GLuint outputMapping[],
6020 const GLuint outputSlotToAttr[],
6021 const ubyte outputSemanticName[],
6022 const ubyte outputSemanticIndex[])
6023 {
6024 struct st_translate *t;
6025 unsigned i;
6026 struct gl_program_constants *frag_const =
6027 &ctx->Const.Program[MESA_SHADER_FRAGMENT];
6028 enum pipe_error ret = PIPE_OK;
6029
6030 assert(numInputs <= ARRAY_SIZE(t->inputs));
6031 assert(numOutputs <= ARRAY_SIZE(t->outputs));
6032
6033 t = CALLOC_STRUCT(st_translate);
6034 if (!t) {
6035 ret = PIPE_ERROR_OUT_OF_MEMORY;
6036 goto out;
6037 }
6038
6039 t->procType = procType;
6040 t->inputMapping = inputMapping;
6041 t->outputMapping = outputMapping;
6042 t->ureg = ureg;
6043 t->num_temp_arrays = program->next_array;
6044 if (t->num_temp_arrays)
6045 t->arrays = (struct ureg_dst*)
6046 calloc(t->num_temp_arrays, sizeof(t->arrays[0]));
6047
6048 /*
6049 * Declare input attributes.
6050 */
6051 switch (procType) {
6052 case PIPE_SHADER_FRAGMENT:
6053 for (i = 0; i < numInputs; i++) {
6054 unsigned array_id = 0;
6055 unsigned array_size;
6056
6057 if (find_array(inputSlotToAttr[i], program->input_arrays,
6058 program->num_input_arrays, &array_id, &array_size)) {
6059 /* We've found an array. Declare it so. */
6060 t->inputs[i] = ureg_DECL_fs_input_cyl_centroid(ureg,
6061 inputSemanticName[i], inputSemanticIndex[i],
6062 interpMode[i], 0, interpLocation[i],
6063 array_id, array_size);
6064
6065 GLuint base_attr = inputSlotToAttr[i];
6066 while (i + 1 < numInputs &&
6067 inputSlotToAttr[i + 1] < base_attr + array_size)
6068 ++i;
6069 }
6070 else {
6071 t->inputs[i] = ureg_DECL_fs_input_cyl_centroid(ureg,
6072 inputSemanticName[i], inputSemanticIndex[i],
6073 interpMode[i], 0, interpLocation[i], 0, 1);
6074 }
6075 }
6076 break;
6077 case PIPE_SHADER_GEOMETRY:
6078 case PIPE_SHADER_TESS_EVAL:
6079 case PIPE_SHADER_TESS_CTRL:
6080 for (i = 0; i < numInputs; i++) {
6081 unsigned array_id = 0;
6082 unsigned array_size;
6083
6084 if (find_array(inputSlotToAttr[i], program->input_arrays,
6085 program->num_input_arrays, &array_id, &array_size)) {
6086 /* We've found an array. Declare it so. */
6087 t->inputs[i] = ureg_DECL_input(ureg, inputSemanticName[i],
6088 inputSemanticIndex[i],
6089 array_id, array_size);
6090 i += array_size - 1;
6091 }
6092 else {
6093 t->inputs[i] = ureg_DECL_input(ureg, inputSemanticName[i],
6094 inputSemanticIndex[i], 0, 1);
6095 }
6096 }
6097 break;
6098 case PIPE_SHADER_VERTEX:
6099 for (i = 0; i < numInputs; i++) {
6100 t->inputs[i] = ureg_DECL_vs_input(ureg, i);
6101 }
6102 break;
6103 case PIPE_SHADER_COMPUTE:
6104 break;
6105 default:
6106 assert(0);
6107 }
6108
6109 /*
6110 * Declare output attributes.
6111 */
6112 switch (procType) {
6113 case PIPE_SHADER_FRAGMENT:
6114 case PIPE_SHADER_COMPUTE:
6115 break;
6116 case PIPE_SHADER_GEOMETRY:
6117 case PIPE_SHADER_TESS_EVAL:
6118 case PIPE_SHADER_TESS_CTRL:
6119 case PIPE_SHADER_VERTEX:
6120 for (i = 0; i < numOutputs; i++) {
6121 unsigned array_id = 0;
6122 unsigned array_size;
6123
6124 if (find_array(outputSlotToAttr[i], program->output_arrays,
6125 program->num_output_arrays, &array_id, &array_size)) {
6126 /* We've found an array. Declare it so. */
6127 t->outputs[i] = ureg_DECL_output_array(ureg,
6128 outputSemanticName[i],
6129 outputSemanticIndex[i],
6130 array_id, array_size);
6131 i += array_size - 1;
6132 }
6133 else {
6134 t->outputs[i] = ureg_DECL_output(ureg,
6135 outputSemanticName[i],
6136 outputSemanticIndex[i]);
6137 }
6138 }
6139 break;
6140 default:
6141 assert(0);
6142 }
6143
6144 if (procType == PIPE_SHADER_FRAGMENT) {
6145 if (program->shader->info.EarlyFragmentTests)
6146 ureg_property(ureg, TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL, 1);
6147
6148 if (proginfo->InputsRead & VARYING_BIT_POS) {
6149 /* Must do this after setting up t->inputs. */
6150 emit_wpos(st_context(ctx), t, proginfo, ureg,
6151 program->wpos_transform_const);
6152 }
6153
6154 if (proginfo->InputsRead & VARYING_BIT_FACE)
6155 emit_face_var(ctx, t);
6156
6157 for (i = 0; i < numOutputs; i++) {
6158 switch (outputSemanticName[i]) {
6159 case TGSI_SEMANTIC_POSITION:
6160 t->outputs[i] = ureg_DECL_output(ureg,
6161 TGSI_SEMANTIC_POSITION, /* Z/Depth */
6162 outputSemanticIndex[i]);
6163 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Z);
6164 break;
6165 case TGSI_SEMANTIC_STENCIL:
6166 t->outputs[i] = ureg_DECL_output(ureg,
6167 TGSI_SEMANTIC_STENCIL, /* Stencil */
6168 outputSemanticIndex[i]);
6169 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_Y);
6170 break;
6171 case TGSI_SEMANTIC_COLOR:
6172 t->outputs[i] = ureg_DECL_output(ureg,
6173 TGSI_SEMANTIC_COLOR,
6174 outputSemanticIndex[i]);
6175 break;
6176 case TGSI_SEMANTIC_SAMPLEMASK:
6177 t->outputs[i] = ureg_DECL_output(ureg,
6178 TGSI_SEMANTIC_SAMPLEMASK,
6179 outputSemanticIndex[i]);
6180 /* TODO: If we ever support more than 32 samples, this will have
6181 * to become an array.
6182 */
6183 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6184 break;
6185 default:
6186 assert(!"fragment shader outputs must be POSITION/STENCIL/COLOR");
6187 ret = PIPE_ERROR_BAD_INPUT;
6188 goto out;
6189 }
6190 }
6191 }
6192 else if (procType == PIPE_SHADER_VERTEX) {
6193 for (i = 0; i < numOutputs; i++) {
6194 if (outputSemanticName[i] == TGSI_SEMANTIC_FOG) {
6195 /* force register to contain a fog coordinate in the form (F, 0, 0, 1). */
6196 ureg_MOV(ureg,
6197 ureg_writemask(t->outputs[i], TGSI_WRITEMASK_YZW),
6198 ureg_imm4f(ureg, 0.0f, 0.0f, 0.0f, 1.0f));
6199 t->outputs[i] = ureg_writemask(t->outputs[i], TGSI_WRITEMASK_X);
6200 }
6201 }
6202 }
6203
6204 if (procType == PIPE_SHADER_COMPUTE) {
6205 emit_compute_block_size(proginfo, ureg);
6206 }
6207
6208 /* Declare address register.
6209 */
6210 if (program->num_address_regs > 0) {
6211 assert(program->num_address_regs <= 3);
6212 for (int i = 0; i < program->num_address_regs; i++)
6213 t->address[i] = ureg_DECL_address(ureg);
6214 }
6215
6216 /* Declare misc input registers
6217 */
6218 {
6219 GLbitfield sysInputs = proginfo->SystemValuesRead;
6220
6221 for (i = 0; sysInputs; i++) {
6222 if (sysInputs & (1 << i)) {
6223 unsigned semName = _mesa_sysval_to_semantic(i);
6224
6225 t->systemValues[i] = ureg_DECL_system_value(ureg, semName, 0);
6226
6227 if (semName == TGSI_SEMANTIC_INSTANCEID ||
6228 semName == TGSI_SEMANTIC_VERTEXID) {
6229 /* From Gallium perspective, these system values are always
6230 * integer, and require native integer support. However, if
6231 * native integer is supported on the vertex stage but not the
6232 * pixel stage (e.g, i915g + draw), Mesa will generate IR that
6233 * assumes these system values are floats. To resolve the
6234 * inconsistency, we insert a U2F.
6235 */
6236 struct st_context *st = st_context(ctx);
6237 struct pipe_screen *pscreen = st->pipe->screen;
6238 assert(procType == PIPE_SHADER_VERTEX);
6239 assert(pscreen->get_shader_param(pscreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS));
6240 (void) pscreen;
6241 if (!ctx->Const.NativeIntegers) {
6242 struct ureg_dst temp = ureg_DECL_local_temporary(t->ureg);
6243 ureg_U2F( t->ureg, ureg_writemask(temp, TGSI_WRITEMASK_X), t->systemValues[i]);
6244 t->systemValues[i] = ureg_scalar(ureg_src(temp), 0);
6245 }
6246 }
6247
6248 if (procType == PIPE_SHADER_FRAGMENT &&
6249 semName == TGSI_SEMANTIC_POSITION)
6250 emit_wpos(st_context(ctx), t, proginfo, ureg,
6251 program->wpos_transform_const);
6252
6253 sysInputs &= ~(1 << i);
6254 }
6255 }
6256 }
6257
6258 t->array_sizes = program->array_sizes;
6259 t->input_arrays = program->input_arrays;
6260 t->output_arrays = program->output_arrays;
6261
6262 /* Emit constants and uniforms. TGSI uses a single index space for these,
6263 * so we put all the translated regs in t->constants.
6264 */
6265 if (proginfo->Parameters) {
6266 t->constants = (struct ureg_src *)
6267 calloc(proginfo->Parameters->NumParameters, sizeof(t->constants[0]));
6268 if (t->constants == NULL) {
6269 ret = PIPE_ERROR_OUT_OF_MEMORY;
6270 goto out;
6271 }
6272 t->num_constants = proginfo->Parameters->NumParameters;
6273
6274 for (i = 0; i < proginfo->Parameters->NumParameters; i++) {
6275 switch (proginfo->Parameters->Parameters[i].Type) {
6276 case PROGRAM_STATE_VAR:
6277 case PROGRAM_UNIFORM:
6278 t->constants[i] = ureg_DECL_constant(ureg, i);
6279 break;
6280
6281 /* Emit immediates for PROGRAM_CONSTANT only when there's no indirect
6282 * addressing of the const buffer.
6283 * FIXME: Be smarter and recognize param arrays:
6284 * indirect addressing is only valid within the referenced
6285 * array.
6286 */
6287 case PROGRAM_CONSTANT:
6288 if (program->indirect_addr_consts)
6289 t->constants[i] = ureg_DECL_constant(ureg, i);
6290 else
6291 t->constants[i] = emit_immediate(t,
6292 proginfo->Parameters->ParameterValues[i],
6293 proginfo->Parameters->Parameters[i].DataType,
6294 4);
6295 break;
6296 default:
6297 break;
6298 }
6299 }
6300 }
6301
6302 if (program->shader) {
6303 unsigned num_ubos = program->shader->NumUniformBlocks;
6304
6305 for (i = 0; i < num_ubos; i++) {
6306 unsigned size = program->shader->UniformBlocks[i]->UniformBufferSize;
6307 unsigned num_const_vecs = (size + 15) / 16;
6308 unsigned first, last;
6309 assert(num_const_vecs > 0);
6310 first = 0;
6311 last = num_const_vecs > 0 ? num_const_vecs - 1 : 0;
6312 ureg_DECL_constant2D(t->ureg, first, last, i + 1);
6313 }
6314 }
6315
6316 /* Emit immediate values.
6317 */
6318 t->immediates = (struct ureg_src *)
6319 calloc(program->num_immediates, sizeof(struct ureg_src));
6320 if (t->immediates == NULL) {
6321 ret = PIPE_ERROR_OUT_OF_MEMORY;
6322 goto out;
6323 }
6324 t->num_immediates = program->num_immediates;
6325
6326 i = 0;
6327 foreach_in_list(immediate_storage, imm, &program->immediates) {
6328 assert(i < program->num_immediates);
6329 t->immediates[i++] = emit_immediate(t, imm->values, imm->type, imm->size32);
6330 }
6331 assert(i == program->num_immediates);
6332
6333 /* texture samplers */
6334 for (i = 0; i < frag_const->MaxTextureImageUnits; i++) {
6335 if (program->samplers_used & (1u << i)) {
6336 unsigned type;
6337
6338 t->samplers[i] = ureg_DECL_sampler(ureg, i);
6339
6340 switch (program->sampler_types[i]) {
6341 case GLSL_TYPE_INT:
6342 type = TGSI_RETURN_TYPE_SINT;
6343 break;
6344 case GLSL_TYPE_UINT:
6345 type = TGSI_RETURN_TYPE_UINT;
6346 break;
6347 case GLSL_TYPE_FLOAT:
6348 type = TGSI_RETURN_TYPE_FLOAT;
6349 break;
6350 default:
6351 unreachable("not reached");
6352 }
6353
6354 ureg_DECL_sampler_view( ureg, i, program->sampler_targets[i],
6355 type, type, type, type );
6356 }
6357 }
6358
6359 for (i = 0; i < frag_const->MaxAtomicBuffers; i++) {
6360 if (program->buffers_used & (1 << i)) {
6361 t->buffers[i] = ureg_DECL_buffer(ureg, i, true);
6362 }
6363 }
6364
6365 for (; i < frag_const->MaxAtomicBuffers + frag_const->MaxShaderStorageBlocks;
6366 i++) {
6367 if (program->buffers_used & (1 << i)) {
6368 t->buffers[i] = ureg_DECL_buffer(ureg, i, false);
6369 }
6370 }
6371
6372 if (program->use_shared_memory)
6373 t->shared_memory = ureg_DECL_memory(ureg, TGSI_MEMORY_TYPE_SHARED);
6374
6375 for (i = 0; i < program->shader->NumImages; i++) {
6376 if (program->images_used & (1 << i)) {
6377 t->images[i] = ureg_DECL_image(ureg, i,
6378 program->image_targets[i],
6379 program->image_formats[i],
6380 true, false);
6381 }
6382 }
6383
6384 /* Emit each instruction in turn:
6385 */
6386 foreach_in_list(glsl_to_tgsi_instruction, inst, &program->instructions) {
6387 set_insn_start(t, ureg_get_instruction_number(ureg));
6388 compile_tgsi_instruction(t, inst);
6389 }
6390
6391 /* Fix up all emitted labels:
6392 */
6393 for (i = 0; i < t->labels_count; i++) {
6394 ureg_fixup_label(ureg, t->labels[i].token,
6395 t->insn[t->labels[i].branch_target]);
6396 }
6397
6398 /* Set the next shader stage hint for VS and TES. */
6399 switch (procType) {
6400 case PIPE_SHADER_VERTEX:
6401 case PIPE_SHADER_TESS_EVAL:
6402 if (program->shader_program->SeparateShader)
6403 break;
6404
6405 for (i = program->shader->Stage+1; i <= MESA_SHADER_FRAGMENT; i++) {
6406 if (program->shader_program->_LinkedShaders[i]) {
6407 unsigned next;
6408
6409 switch (i) {
6410 case MESA_SHADER_TESS_CTRL:
6411 next = PIPE_SHADER_TESS_CTRL;
6412 break;
6413 case MESA_SHADER_TESS_EVAL:
6414 next = PIPE_SHADER_TESS_EVAL;
6415 break;
6416 case MESA_SHADER_GEOMETRY:
6417 next = PIPE_SHADER_GEOMETRY;
6418 break;
6419 case MESA_SHADER_FRAGMENT:
6420 next = PIPE_SHADER_FRAGMENT;
6421 break;
6422 default:
6423 assert(0);
6424 continue;
6425 }
6426
6427 ureg_set_next_shader_processor(ureg, next);
6428 break;
6429 }
6430 }
6431 break;
6432 }
6433
6434 out:
6435 if (t) {
6436 free(t->arrays);
6437 free(t->temps);
6438 free(t->insn);
6439 free(t->labels);
6440 free(t->constants);
6441 t->num_constants = 0;
6442 free(t->immediates);
6443 t->num_immediates = 0;
6444
6445 if (t->error) {
6446 debug_printf("%s: translate error flag set\n", __func__);
6447 }
6448
6449 FREE(t);
6450 }
6451
6452 return ret;
6453 }
6454 /* ----------------------------- End TGSI code ------------------------------ */
6455
6456
6457 /**
6458 * Convert a shader's GLSL IR into a Mesa gl_program, although without
6459 * generating Mesa IR.
6460 */
6461 static struct gl_program *
6462 get_mesa_program_tgsi(struct gl_context *ctx,
6463 struct gl_shader_program *shader_program,
6464 struct gl_linked_shader *shader)
6465 {
6466 glsl_to_tgsi_visitor* v;
6467 struct gl_program *prog;
6468 GLenum target = _mesa_shader_stage_to_program(shader->Stage);
6469 bool progress;
6470 struct gl_shader_compiler_options *options =
6471 &ctx->Const.ShaderCompilerOptions[shader->Stage];
6472 struct pipe_screen *pscreen = ctx->st->pipe->screen;
6473 enum pipe_shader_type ptarget = st_shader_stage_to_ptarget(shader->Stage);
6474
6475 validate_ir_tree(shader->ir);
6476
6477 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
6478 if (!prog)
6479 return NULL;
6480 prog->Parameters = _mesa_new_parameter_list();
6481 v = new glsl_to_tgsi_visitor();
6482 v->ctx = ctx;
6483 v->prog = prog;
6484 v->shader_program = shader_program;
6485 v->shader = shader;
6486 v->options = options;
6487 v->glsl_version = ctx->Const.GLSLVersion;
6488 v->native_integers = ctx->Const.NativeIntegers;
6489
6490 v->have_sqrt = pscreen->get_shader_param(pscreen, ptarget,
6491 PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED);
6492 v->have_fma = pscreen->get_shader_param(pscreen, ptarget,
6493 PIPE_SHADER_CAP_TGSI_FMA_SUPPORTED);
6494
6495 _mesa_copy_linked_program_data(shader->Stage, shader_program, prog);
6496 _mesa_generate_parameters_list_for_uniforms(shader_program, shader,
6497 prog->Parameters);
6498
6499 /* Remove reads from output registers. */
6500 lower_output_reads(shader->Stage, shader->ir);
6501
6502 /* Emit intermediate IR for main(). */
6503 visit_exec_list(shader->ir, v);
6504
6505 /* Now emit bodies for any functions that were used. */
6506 do {
6507 progress = GL_FALSE;
6508
6509 foreach_in_list(function_entry, entry, &v->function_signatures) {
6510 if (!entry->bgn_inst) {
6511 v->current_function = entry;
6512
6513 entry->bgn_inst = v->emit_asm(NULL, TGSI_OPCODE_BGNSUB);
6514 entry->bgn_inst->function = entry;
6515
6516 visit_exec_list(&entry->sig->body, v);
6517
6518 glsl_to_tgsi_instruction *last;
6519 last = (glsl_to_tgsi_instruction *)v->instructions.get_tail();
6520 if (last->op != TGSI_OPCODE_RET)
6521 v->emit_asm(NULL, TGSI_OPCODE_RET);
6522
6523 glsl_to_tgsi_instruction *end;
6524 end = v->emit_asm(NULL, TGSI_OPCODE_ENDSUB);
6525 end->function = entry;
6526
6527 progress = GL_TRUE;
6528 }
6529 }
6530 } while (progress);
6531
6532 #if 0
6533 /* Print out some information (for debugging purposes) used by the
6534 * optimization passes. */
6535 {
6536 int i;
6537 int *first_writes = rzalloc_array(v->mem_ctx, int, v->next_temp);
6538 int *first_reads = rzalloc_array(v->mem_ctx, int, v->next_temp);
6539 int *last_writes = rzalloc_array(v->mem_ctx, int, v->next_temp);
6540 int *last_reads = rzalloc_array(v->mem_ctx, int, v->next_temp);
6541
6542 for (i = 0; i < v->next_temp; i++) {
6543 first_writes[i] = -1;
6544 first_reads[i] = -1;
6545 last_writes[i] = -1;
6546 last_reads[i] = -1;
6547 }
6548 v->get_first_temp_read(first_reads);
6549 v->get_last_temp_read_first_temp_write(last_reads, first_writes);
6550 v->get_last_temp_write(last_writes);
6551 for (i = 0; i < v->next_temp; i++)
6552 printf("Temp %d: FR=%3d FW=%3d LR=%3d LW=%3d\n", i, first_reads[i],
6553 first_writes[i],
6554 last_reads[i],
6555 last_writes[i]);
6556 ralloc_free(first_writes);
6557 ralloc_free(first_reads);
6558 ralloc_free(last_writes);
6559 ralloc_free(last_reads);
6560 }
6561 #endif
6562
6563 /* Perform optimizations on the instructions in the glsl_to_tgsi_visitor. */
6564 v->simplify_cmp();
6565
6566 if (shader->Stage != MESA_SHADER_TESS_CTRL &&
6567 shader->Stage != MESA_SHADER_TESS_EVAL)
6568 v->copy_propagate();
6569
6570 while (v->eliminate_dead_code());
6571
6572 v->merge_two_dsts();
6573 v->merge_registers();
6574 v->renumber_registers();
6575
6576 /* Write the END instruction. */
6577 v->emit_asm(NULL, TGSI_OPCODE_END);
6578
6579 if (ctx->_Shader->Flags & GLSL_DUMP) {
6580 _mesa_log("\n");
6581 _mesa_log("GLSL IR for linked %s program %d:\n",
6582 _mesa_shader_stage_to_string(shader->Stage),
6583 shader_program->Name);
6584 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
6585 _mesa_log("\n\n");
6586 }
6587
6588 prog->Instructions = NULL;
6589 prog->NumInstructions = 0;
6590
6591 do_set_program_inouts(shader->ir, prog, shader->Stage);
6592 shrink_array_declarations(v->input_arrays, v->num_input_arrays,
6593 prog->InputsRead, prog->DoubleInputsRead, prog->PatchInputsRead);
6594 shrink_array_declarations(v->output_arrays, v->num_output_arrays,
6595 prog->OutputsWritten, 0ULL, prog->PatchOutputsWritten);
6596 count_resources(v, prog);
6597
6598 /* The GLSL IR won't be needed anymore. */
6599 ralloc_free(shader->ir);
6600 shader->ir = NULL;
6601
6602 /* This must be done before the uniform storage is associated. */
6603 if (shader->Stage == MESA_SHADER_FRAGMENT &&
6604 (prog->InputsRead & VARYING_BIT_POS ||
6605 prog->SystemValuesRead & (1 << SYSTEM_VALUE_FRAG_COORD))) {
6606 static const gl_state_index wposTransformState[STATE_LENGTH] = {
6607 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
6608 };
6609
6610 v->wpos_transform_const = _mesa_add_state_reference(prog->Parameters,
6611 wposTransformState);
6612 }
6613
6614 _mesa_reference_program(ctx, &shader->Program, prog);
6615
6616 /* Avoid reallocation of the program parameter list, because the uniform
6617 * storage is only associated with the original parameter list.
6618 * This should be enough for Bitmap and DrawPixels constants.
6619 */
6620 _mesa_reserve_parameter_storage(prog->Parameters, 8);
6621
6622 /* This has to be done last. Any operation the can cause
6623 * prog->ParameterValues to get reallocated (e.g., anything that adds a
6624 * program constant) has to happen before creating this linkage.
6625 */
6626 _mesa_associate_uniform_storage(ctx, shader_program, prog->Parameters);
6627 if (!shader_program->LinkStatus) {
6628 free_glsl_to_tgsi_visitor(v);
6629 return NULL;
6630 }
6631
6632 struct st_vertex_program *stvp;
6633 struct st_fragment_program *stfp;
6634 struct st_geometry_program *stgp;
6635 struct st_tessctrl_program *sttcp;
6636 struct st_tesseval_program *sttep;
6637 struct st_compute_program *stcp;
6638
6639 switch (shader->Stage) {
6640 case MESA_SHADER_VERTEX:
6641 stvp = (struct st_vertex_program *)prog;
6642 stvp->glsl_to_tgsi = v;
6643 break;
6644 case MESA_SHADER_FRAGMENT:
6645 stfp = (struct st_fragment_program *)prog;
6646 stfp->glsl_to_tgsi = v;
6647 break;
6648 case MESA_SHADER_GEOMETRY:
6649 stgp = (struct st_geometry_program *)prog;
6650 stgp->glsl_to_tgsi = v;
6651 break;
6652 case MESA_SHADER_TESS_CTRL:
6653 sttcp = (struct st_tessctrl_program *)prog;
6654 sttcp->glsl_to_tgsi = v;
6655 break;
6656 case MESA_SHADER_TESS_EVAL:
6657 sttep = (struct st_tesseval_program *)prog;
6658 sttep->glsl_to_tgsi = v;
6659 break;
6660 case MESA_SHADER_COMPUTE:
6661 stcp = (struct st_compute_program *)prog;
6662 stcp->glsl_to_tgsi = v;
6663 break;
6664 default:
6665 assert(!"should not be reached");
6666 return NULL;
6667 }
6668
6669 return prog;
6670 }
6671
6672 static void
6673 set_affected_state_flags(uint64_t *states,
6674 struct gl_program *prog,
6675 struct gl_linked_shader *shader,
6676 uint64_t new_constants,
6677 uint64_t new_sampler_views,
6678 uint64_t new_samplers,
6679 uint64_t new_images,
6680 uint64_t new_ubos,
6681 uint64_t new_ssbos,
6682 uint64_t new_atomics)
6683 {
6684 if (prog->Parameters->NumParameters)
6685 *states |= new_constants;
6686
6687 if (shader->num_samplers)
6688 *states |= new_sampler_views | new_samplers;
6689
6690 if (shader->NumImages)
6691 *states |= new_images;
6692
6693 if (shader->NumUniformBlocks)
6694 *states |= new_ubos;
6695
6696 if (shader->NumShaderStorageBlocks)
6697 *states |= new_ssbos;
6698
6699 if (shader->NumAtomicBuffers)
6700 *states |= new_atomics;
6701 }
6702
6703 static struct gl_program *
6704 get_mesa_program(struct gl_context *ctx,
6705 struct gl_shader_program *shader_program,
6706 struct gl_linked_shader *shader)
6707 {
6708 struct pipe_screen *pscreen = ctx->st->pipe->screen;
6709 enum pipe_shader_type ptarget = st_shader_stage_to_ptarget(shader->Stage);
6710 enum pipe_shader_ir preferred_ir = (enum pipe_shader_ir)
6711 pscreen->get_shader_param(pscreen, ptarget, PIPE_SHADER_CAP_PREFERRED_IR);
6712 struct gl_program *prog = NULL;
6713
6714 if (preferred_ir == PIPE_SHADER_IR_NIR) {
6715 /* TODO only for GLSL VS/FS for now: */
6716 switch (shader->Stage) {
6717 case MESA_SHADER_VERTEX:
6718 case MESA_SHADER_FRAGMENT:
6719 prog = st_nir_get_mesa_program(ctx, shader_program, shader);
6720 default:
6721 break;
6722 }
6723 } else {
6724 prog = get_mesa_program_tgsi(ctx, shader_program, shader);
6725 }
6726
6727 if (prog) {
6728 uint64_t *states;
6729
6730 /* This determines which states will be updated when the shader is
6731 * bound.
6732 */
6733 switch (shader->Stage) {
6734 case MESA_SHADER_VERTEX:
6735 states = &((struct st_vertex_program*)prog)->affected_states;
6736
6737 *states = ST_NEW_VS_STATE |
6738 ST_NEW_RASTERIZER |
6739 ST_NEW_VERTEX_ARRAYS;
6740
6741 set_affected_state_flags(states, prog, shader,
6742 ST_NEW_VS_CONSTANTS,
6743 ST_NEW_VS_SAMPLER_VIEWS,
6744 ST_NEW_RENDER_SAMPLERS,
6745 ST_NEW_VS_IMAGES,
6746 ST_NEW_VS_UBOS,
6747 ST_NEW_VS_SSBOS,
6748 ST_NEW_VS_ATOMICS);
6749 break;
6750
6751 case MESA_SHADER_TESS_CTRL:
6752 states = &((struct st_tessctrl_program*)prog)->affected_states;
6753
6754 *states = ST_NEW_TCS_STATE;
6755
6756 set_affected_state_flags(states, prog, shader,
6757 ST_NEW_TCS_CONSTANTS,
6758 ST_NEW_TCS_SAMPLER_VIEWS,
6759 ST_NEW_RENDER_SAMPLERS,
6760 ST_NEW_TCS_IMAGES,
6761 ST_NEW_TCS_UBOS,
6762 ST_NEW_TCS_SSBOS,
6763 ST_NEW_TCS_ATOMICS);
6764 break;
6765
6766 case MESA_SHADER_TESS_EVAL:
6767 states = &((struct st_tesseval_program*)prog)->affected_states;
6768
6769 *states = ST_NEW_TES_STATE |
6770 ST_NEW_RASTERIZER;
6771
6772 set_affected_state_flags(states, prog, shader,
6773 ST_NEW_TES_CONSTANTS,
6774 ST_NEW_TES_SAMPLER_VIEWS,
6775 ST_NEW_RENDER_SAMPLERS,
6776 ST_NEW_TES_IMAGES,
6777 ST_NEW_TES_UBOS,
6778 ST_NEW_TES_SSBOS,
6779 ST_NEW_TES_ATOMICS);
6780 break;
6781
6782 case MESA_SHADER_GEOMETRY:
6783 states = &((struct st_geometry_program*)prog)->affected_states;
6784
6785 *states = ST_NEW_GS_STATE |
6786 ST_NEW_RASTERIZER;
6787
6788 set_affected_state_flags(states, prog, shader,
6789 ST_NEW_GS_CONSTANTS,
6790 ST_NEW_GS_SAMPLER_VIEWS,
6791 ST_NEW_RENDER_SAMPLERS,
6792 ST_NEW_GS_IMAGES,
6793 ST_NEW_GS_UBOS,
6794 ST_NEW_GS_SSBOS,
6795 ST_NEW_GS_ATOMICS);
6796 break;
6797
6798 case MESA_SHADER_FRAGMENT:
6799 states = &((struct st_fragment_program*)prog)->affected_states;
6800
6801 /* gl_FragCoord and glDrawPixels always use constants. */
6802 *states = ST_NEW_FS_STATE |
6803 ST_NEW_SAMPLE_SHADING |
6804 ST_NEW_FS_CONSTANTS;
6805
6806 set_affected_state_flags(states, prog, shader,
6807 ST_NEW_FS_CONSTANTS,
6808 ST_NEW_FS_SAMPLER_VIEWS,
6809 ST_NEW_RENDER_SAMPLERS,
6810 ST_NEW_FS_IMAGES,
6811 ST_NEW_FS_UBOS,
6812 ST_NEW_FS_SSBOS,
6813 ST_NEW_FS_ATOMICS);
6814 break;
6815
6816 case MESA_SHADER_COMPUTE:
6817 states = &((struct st_compute_program*)prog)->affected_states;
6818
6819 *states = ST_NEW_CS_STATE;
6820
6821 set_affected_state_flags(states, prog, shader,
6822 ST_NEW_CS_CONSTANTS,
6823 ST_NEW_CS_SAMPLER_VIEWS,
6824 ST_NEW_CS_SAMPLERS,
6825 ST_NEW_CS_IMAGES,
6826 ST_NEW_CS_UBOS,
6827 ST_NEW_CS_SSBOS,
6828 ST_NEW_CS_ATOMICS);
6829 break;
6830
6831 default:
6832 unreachable("unhandled shader stage");
6833 }
6834 }
6835
6836 return prog;
6837 }
6838
6839
6840 extern "C" {
6841
6842 /**
6843 * Link a shader.
6844 * Called via ctx->Driver.LinkShader()
6845 * This actually involves converting GLSL IR into an intermediate TGSI-like IR
6846 * with code lowering and other optimizations.
6847 */
6848 GLboolean
6849 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
6850 {
6851 struct pipe_screen *pscreen = ctx->st->pipe->screen;
6852 assert(prog->LinkStatus);
6853
6854 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
6855 if (prog->_LinkedShaders[i] == NULL)
6856 continue;
6857
6858 bool progress;
6859 exec_list *ir = prog->_LinkedShaders[i]->ir;
6860 gl_shader_stage stage = prog->_LinkedShaders[i]->Stage;
6861 const struct gl_shader_compiler_options *options =
6862 &ctx->Const.ShaderCompilerOptions[stage];
6863 enum pipe_shader_type ptarget = st_shader_stage_to_ptarget(stage);
6864 bool have_dround = pscreen->get_shader_param(pscreen, ptarget,
6865 PIPE_SHADER_CAP_TGSI_DROUND_SUPPORTED);
6866 bool have_dfrexp = pscreen->get_shader_param(pscreen, ptarget,
6867 PIPE_SHADER_CAP_TGSI_DFRACEXP_DLDEXP_SUPPORTED);
6868
6869 /* If there are forms of indirect addressing that the driver
6870 * cannot handle, perform the lowering pass.
6871 */
6872 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput ||
6873 options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
6874 lower_variable_index_to_cond_assign(prog->_LinkedShaders[i]->Stage, ir,
6875 options->EmitNoIndirectInput,
6876 options->EmitNoIndirectOutput,
6877 options->EmitNoIndirectTemp,
6878 options->EmitNoIndirectUniform);
6879 }
6880
6881 if (ctx->Extensions.ARB_shading_language_packing) {
6882 unsigned lower_inst = LOWER_PACK_SNORM_2x16 |
6883 LOWER_UNPACK_SNORM_2x16 |
6884 LOWER_PACK_UNORM_2x16 |
6885 LOWER_UNPACK_UNORM_2x16 |
6886 LOWER_PACK_SNORM_4x8 |
6887 LOWER_UNPACK_SNORM_4x8 |
6888 LOWER_UNPACK_UNORM_4x8 |
6889 LOWER_PACK_UNORM_4x8;
6890
6891 if (ctx->Extensions.ARB_gpu_shader5)
6892 lower_inst |= LOWER_PACK_USE_BFI |
6893 LOWER_PACK_USE_BFE;
6894 if (!ctx->st->has_half_float_packing)
6895 lower_inst |= LOWER_PACK_HALF_2x16 |
6896 LOWER_UNPACK_HALF_2x16;
6897
6898 lower_packing_builtins(ir, lower_inst);
6899 }
6900
6901 if (!pscreen->get_param(pscreen, PIPE_CAP_TEXTURE_GATHER_OFFSETS))
6902 lower_offset_arrays(ir);
6903 do_mat_op_to_vec(ir);
6904 lower_instructions(ir,
6905 MOD_TO_FLOOR |
6906 DIV_TO_MUL_RCP |
6907 EXP_TO_EXP2 |
6908 LOG_TO_LOG2 |
6909 LDEXP_TO_ARITH |
6910 (have_dfrexp ? 0 : DFREXP_DLDEXP_TO_ARITH) |
6911 CARRY_TO_ARITH |
6912 BORROW_TO_ARITH |
6913 (have_dround ? 0 : DOPS_TO_DFRAC) |
6914 (options->EmitNoPow ? POW_TO_EXP2 : 0) |
6915 (!ctx->Const.NativeIntegers ? INT_DIV_TO_MUL_RCP : 0) |
6916 (options->EmitNoSat ? SAT_TO_CLAMP : 0) |
6917 /* Assume that if ARB_gpu_shader5 is not supported
6918 * then all of the extended integer functions need
6919 * lowering. It may be necessary to add some caps
6920 * for individual instructions.
6921 */
6922 (!ctx->Extensions.ARB_gpu_shader5
6923 ? BIT_COUNT_TO_MATH |
6924 EXTRACT_TO_SHIFTS |
6925 INSERT_TO_SHIFTS |
6926 REVERSE_TO_SHIFTS |
6927 FIND_LSB_TO_FLOAT_CAST |
6928 FIND_MSB_TO_FLOAT_CAST |
6929 IMUL_HIGH_TO_MUL
6930 : 0));
6931
6932 do_vec_index_to_cond_assign(ir);
6933 lower_vector_insert(ir, true);
6934 lower_quadop_vector(ir, false);
6935 lower_noise(ir);
6936 if (options->MaxIfDepth == 0) {
6937 lower_discard(ir);
6938 }
6939
6940 do {
6941 progress = false;
6942
6943 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
6944
6945 progress = do_common_optimization(ir, true, true, options,
6946 ctx->Const.NativeIntegers)
6947 || progress;
6948
6949 progress = lower_if_to_cond_assign(ir, options->MaxIfDepth) || progress;
6950
6951 } while (progress);
6952
6953 validate_ir_tree(ir);
6954 }
6955
6956 build_program_resource_list(ctx, prog);
6957
6958 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
6959 struct gl_program *linked_prog;
6960
6961 if (prog->_LinkedShaders[i] == NULL)
6962 continue;
6963
6964 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
6965
6966 if (linked_prog) {
6967 _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
6968 linked_prog);
6969 if (!ctx->Driver.ProgramStringNotify(ctx,
6970 _mesa_shader_stage_to_program(i),
6971 linked_prog)) {
6972 _mesa_reference_program(ctx, &prog->_LinkedShaders[i]->Program,
6973 NULL);
6974 _mesa_reference_program(ctx, &linked_prog, NULL);
6975 return GL_FALSE;
6976 }
6977 }
6978
6979 _mesa_reference_program(ctx, &linked_prog, NULL);
6980 }
6981
6982 return GL_TRUE;
6983 }
6984
6985 void
6986 st_translate_stream_output_info(glsl_to_tgsi_visitor *glsl_to_tgsi,
6987 const GLuint outputMapping[],
6988 struct pipe_stream_output_info *so)
6989 {
6990 struct gl_transform_feedback_info *info =
6991 &glsl_to_tgsi->shader_program->LinkedTransformFeedback;
6992 st_translate_stream_output_info2(info, outputMapping, so);
6993 }
6994
6995 void
6996 st_translate_stream_output_info2(struct gl_transform_feedback_info *info,
6997 const GLuint outputMapping[],
6998 struct pipe_stream_output_info *so)
6999 {
7000 unsigned i;
7001
7002 for (i = 0; i < info->NumOutputs; i++) {
7003 so->output[i].register_index =
7004 outputMapping[info->Outputs[i].OutputRegister];
7005 so->output[i].start_component = info->Outputs[i].ComponentOffset;
7006 so->output[i].num_components = info->Outputs[i].NumComponents;
7007 so->output[i].output_buffer = info->Outputs[i].OutputBuffer;
7008 so->output[i].dst_offset = info->Outputs[i].DstOffset;
7009 so->output[i].stream = info->Outputs[i].StreamId;
7010 }
7011
7012 for (i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
7013 so->stride[i] = info->Buffers[i].Stride;
7014 }
7015 so->num_outputs = info->NumOutputs;
7016 }
7017
7018 } /* extern "C" */