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