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