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