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