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