ir_to_mesa: Add several assertions about sizes of arrays
[mesa.git] / src / mesa / program / ir_to_mesa.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 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 * DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file ir_to_mesa.cpp
28 *
29 * Translate GLSL IR to Mesa's gl_program representation.
30 */
31
32 #include <stdio.h>
33 #include "main/compiler.h"
34 #include "ir.h"
35 #include "ir_visitor.h"
36 #include "ir_print_visitor.h"
37 #include "ir_expression_flattening.h"
38 #include "glsl_types.h"
39 #include "glsl_parser_extras.h"
40 #include "../glsl/program.h"
41 #include "ir_optimization.h"
42 #include "ast.h"
43
44 extern "C" {
45 #include "main/mtypes.h"
46 #include "main/shaderapi.h"
47 #include "main/shaderobj.h"
48 #include "main/uniforms.h"
49 #include "program/hash_table.h"
50 #include "program/prog_instruction.h"
51 #include "program/prog_optimize.h"
52 #include "program/prog_print.h"
53 #include "program/program.h"
54 #include "program/prog_uniform.h"
55 #include "program/prog_parameter.h"
56 #include "program/sampler.h"
57 }
58
59 static int swizzle_for_size(int size);
60
61 /**
62 * This struct is a corresponding struct to Mesa prog_src_register, with
63 * wider fields.
64 */
65 typedef struct ir_to_mesa_src_reg {
66 ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
67 {
68 this->file = (gl_register_file) file;
69 this->index = index;
70 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
71 this->swizzle = swizzle_for_size(type->vector_elements);
72 else
73 this->swizzle = SWIZZLE_XYZW;
74 this->negate = 0;
75 this->reladdr = NULL;
76 }
77
78 ir_to_mesa_src_reg()
79 {
80 this->file = PROGRAM_UNDEFINED;
81 this->index = 0;
82 this->swizzle = 0;
83 this->negate = 0;
84 this->reladdr = NULL;
85 }
86
87 gl_register_file file; /**< PROGRAM_* from Mesa */
88 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
89 GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
90 int negate; /**< NEGATE_XYZW mask from mesa */
91 /** Register index should be offset by the integer in this reg. */
92 ir_to_mesa_src_reg *reladdr;
93 } ir_to_mesa_src_reg;
94
95 typedef struct ir_to_mesa_dst_reg {
96 int file; /**< PROGRAM_* from Mesa */
97 int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
98 int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
99 GLuint cond_mask:4;
100 /** Register index should be offset by the integer in this reg. */
101 ir_to_mesa_src_reg *reladdr;
102 } ir_to_mesa_dst_reg;
103
104 extern ir_to_mesa_src_reg ir_to_mesa_undef;
105
106 class ir_to_mesa_instruction : public exec_node {
107 public:
108 /* Callers of this talloc-based new need not call delete. It's
109 * easier to just talloc_free 'ctx' (or any of its ancestors). */
110 static void* operator new(size_t size, void *ctx)
111 {
112 void *node;
113
114 node = talloc_zero_size(ctx, size);
115 assert(node != NULL);
116
117 return node;
118 }
119
120 enum prog_opcode op;
121 ir_to_mesa_dst_reg dst_reg;
122 ir_to_mesa_src_reg src_reg[3];
123 /** Pointer to the ir source this tree came from for debugging */
124 ir_instruction *ir;
125 GLboolean cond_update;
126 bool saturate;
127 int sampler; /**< sampler index */
128 int tex_target; /**< One of TEXTURE_*_INDEX */
129 GLboolean tex_shadow;
130
131 class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
132 };
133
134 class variable_storage : public exec_node {
135 public:
136 variable_storage(ir_variable *var, gl_register_file file, int index)
137 : file(file), index(index), var(var)
138 {
139 /* empty */
140 }
141
142 gl_register_file file;
143 int index;
144 ir_variable *var; /* variable that maps to this, if any */
145 };
146
147 class function_entry : public exec_node {
148 public:
149 ir_function_signature *sig;
150
151 /**
152 * identifier of this function signature used by the program.
153 *
154 * At the point that Mesa instructions for function calls are
155 * generated, we don't know the address of the first instruction of
156 * the function body. So we make the BranchTarget that is called a
157 * small integer and rewrite them during set_branchtargets().
158 */
159 int sig_id;
160
161 /**
162 * Pointer to first instruction of the function body.
163 *
164 * Set during function body emits after main() is processed.
165 */
166 ir_to_mesa_instruction *bgn_inst;
167
168 /**
169 * Index of the first instruction of the function body in actual
170 * Mesa IR.
171 *
172 * Set after convertion from ir_to_mesa_instruction to prog_instruction.
173 */
174 int inst;
175
176 /** Storage for the return value. */
177 ir_to_mesa_src_reg return_reg;
178 };
179
180 class ir_to_mesa_visitor : public ir_visitor {
181 public:
182 ir_to_mesa_visitor();
183 ~ir_to_mesa_visitor();
184
185 function_entry *current_function;
186
187 struct gl_context *ctx;
188 struct gl_program *prog;
189 struct gl_shader_program *shader_program;
190 struct gl_shader_compiler_options *options;
191
192 int next_temp;
193
194 variable_storage *find_variable_storage(ir_variable *var);
195
196 function_entry *get_function_signature(ir_function_signature *sig);
197
198 ir_to_mesa_src_reg get_temp(const glsl_type *type);
199 void reladdr_to_temp(ir_instruction *ir,
200 ir_to_mesa_src_reg *reg, int *num_reladdr);
201
202 struct ir_to_mesa_src_reg src_reg_for_float(float val);
203
204 /**
205 * \name Visit methods
206 *
207 * As typical for the visitor pattern, there must be one \c visit method for
208 * each concrete subclass of \c ir_instruction. Virtual base classes within
209 * the hierarchy should not have \c visit methods.
210 */
211 /*@{*/
212 virtual void visit(ir_variable *);
213 virtual void visit(ir_loop *);
214 virtual void visit(ir_loop_jump *);
215 virtual void visit(ir_function_signature *);
216 virtual void visit(ir_function *);
217 virtual void visit(ir_expression *);
218 virtual void visit(ir_swizzle *);
219 virtual void visit(ir_dereference_variable *);
220 virtual void visit(ir_dereference_array *);
221 virtual void visit(ir_dereference_record *);
222 virtual void visit(ir_assignment *);
223 virtual void visit(ir_constant *);
224 virtual void visit(ir_call *);
225 virtual void visit(ir_return *);
226 virtual void visit(ir_discard *);
227 virtual void visit(ir_texture *);
228 virtual void visit(ir_if *);
229 /*@}*/
230
231 struct ir_to_mesa_src_reg result;
232
233 /** List of variable_storage */
234 exec_list variables;
235
236 /** List of function_entry */
237 exec_list function_signatures;
238 int next_signature_id;
239
240 /** List of ir_to_mesa_instruction */
241 exec_list instructions;
242
243 ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
244 enum prog_opcode op);
245
246 ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
247 enum prog_opcode op,
248 ir_to_mesa_dst_reg dst,
249 ir_to_mesa_src_reg src0);
250
251 ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
252 enum prog_opcode op,
253 ir_to_mesa_dst_reg dst,
254 ir_to_mesa_src_reg src0,
255 ir_to_mesa_src_reg src1);
256
257 ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
258 enum prog_opcode op,
259 ir_to_mesa_dst_reg dst,
260 ir_to_mesa_src_reg src0,
261 ir_to_mesa_src_reg src1,
262 ir_to_mesa_src_reg src2);
263
264 /**
265 * Emit the correct dot-product instruction for the type of arguments
266 *
267 * \sa ir_to_mesa_emit_op2
268 */
269 void ir_to_mesa_emit_dp(ir_instruction *ir,
270 ir_to_mesa_dst_reg dst,
271 ir_to_mesa_src_reg src0,
272 ir_to_mesa_src_reg src1,
273 unsigned elements);
274
275 void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
276 enum prog_opcode op,
277 ir_to_mesa_dst_reg dst,
278 ir_to_mesa_src_reg src0);
279
280 void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
281 enum prog_opcode op,
282 ir_to_mesa_dst_reg dst,
283 ir_to_mesa_src_reg src0,
284 ir_to_mesa_src_reg src1);
285
286 void emit_scs(ir_instruction *ir, enum prog_opcode op,
287 ir_to_mesa_dst_reg dst,
288 const ir_to_mesa_src_reg &src);
289
290 GLboolean try_emit_mad(ir_expression *ir,
291 int mul_operand);
292 GLboolean try_emit_sat(ir_expression *ir);
293
294 void emit_swz(ir_expression *ir);
295
296 bool process_move_condition(ir_rvalue *ir);
297
298 void copy_propagate(void);
299
300 void *mem_ctx;
301 };
302
303 ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
304
305 ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
306 PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
307 };
308
309 ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
310 PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
311 };
312
313 static void
314 fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
315
316 static void
317 fail_link(struct gl_shader_program *prog, const char *fmt, ...)
318 {
319 va_list args;
320 va_start(args, fmt);
321 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, args);
322 va_end(args);
323
324 prog->LinkStatus = GL_FALSE;
325 }
326
327 static int
328 swizzle_for_size(int size)
329 {
330 int size_swizzles[4] = {
331 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
332 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
333 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
334 MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
335 };
336
337 assert((size >= 1) && (size <= 4));
338 return size_swizzles[size - 1];
339 }
340
341 ir_to_mesa_instruction *
342 ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
343 enum prog_opcode op,
344 ir_to_mesa_dst_reg dst,
345 ir_to_mesa_src_reg src0,
346 ir_to_mesa_src_reg src1,
347 ir_to_mesa_src_reg src2)
348 {
349 ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
350 int num_reladdr = 0;
351
352 /* If we have to do relative addressing, we want to load the ARL
353 * reg directly for one of the regs, and preload the other reladdr
354 * sources into temps.
355 */
356 num_reladdr += dst.reladdr != NULL;
357 num_reladdr += src0.reladdr != NULL;
358 num_reladdr += src1.reladdr != NULL;
359 num_reladdr += src2.reladdr != NULL;
360
361 reladdr_to_temp(ir, &src2, &num_reladdr);
362 reladdr_to_temp(ir, &src1, &num_reladdr);
363 reladdr_to_temp(ir, &src0, &num_reladdr);
364
365 if (dst.reladdr) {
366 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
367 *dst.reladdr);
368
369 num_reladdr--;
370 }
371 assert(num_reladdr == 0);
372
373 inst->op = op;
374 inst->dst_reg = dst;
375 inst->src_reg[0] = src0;
376 inst->src_reg[1] = src1;
377 inst->src_reg[2] = src2;
378 inst->ir = ir;
379
380 inst->function = NULL;
381
382 this->instructions.push_tail(inst);
383
384 return inst;
385 }
386
387
388 ir_to_mesa_instruction *
389 ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
390 enum prog_opcode op,
391 ir_to_mesa_dst_reg dst,
392 ir_to_mesa_src_reg src0,
393 ir_to_mesa_src_reg src1)
394 {
395 return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
396 }
397
398 ir_to_mesa_instruction *
399 ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
400 enum prog_opcode op,
401 ir_to_mesa_dst_reg dst,
402 ir_to_mesa_src_reg src0)
403 {
404 assert(dst.writemask != 0);
405 return ir_to_mesa_emit_op3(ir, op, dst,
406 src0, ir_to_mesa_undef, ir_to_mesa_undef);
407 }
408
409 ir_to_mesa_instruction *
410 ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
411 enum prog_opcode op)
412 {
413 return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
414 ir_to_mesa_undef,
415 ir_to_mesa_undef,
416 ir_to_mesa_undef);
417 }
418
419 void
420 ir_to_mesa_visitor::ir_to_mesa_emit_dp(ir_instruction *ir,
421 ir_to_mesa_dst_reg dst,
422 ir_to_mesa_src_reg src0,
423 ir_to_mesa_src_reg src1,
424 unsigned elements)
425 {
426 static const gl_inst_opcode dot_opcodes[] = {
427 OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
428 };
429
430 ir_to_mesa_emit_op3(ir, dot_opcodes[elements - 2],
431 dst, src0, src1, ir_to_mesa_undef);
432 }
433
434 inline ir_to_mesa_dst_reg
435 ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
436 {
437 ir_to_mesa_dst_reg dst_reg;
438
439 dst_reg.file = reg.file;
440 dst_reg.index = reg.index;
441 dst_reg.writemask = WRITEMASK_XYZW;
442 dst_reg.cond_mask = COND_TR;
443 dst_reg.reladdr = reg.reladdr;
444
445 return dst_reg;
446 }
447
448 inline ir_to_mesa_src_reg
449 ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
450 {
451 return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
452 }
453
454 /**
455 * Emits Mesa scalar opcodes to produce unique answers across channels.
456 *
457 * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
458 * channel determines the result across all channels. So to do a vec4
459 * of this operation, we want to emit a scalar per source channel used
460 * to produce dest channels.
461 */
462 void
463 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
464 enum prog_opcode op,
465 ir_to_mesa_dst_reg dst,
466 ir_to_mesa_src_reg orig_src0,
467 ir_to_mesa_src_reg orig_src1)
468 {
469 int i, j;
470 int done_mask = ~dst.writemask;
471
472 /* Mesa RCP is a scalar operation splatting results to all channels,
473 * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
474 * dst channels.
475 */
476 for (i = 0; i < 4; i++) {
477 GLuint this_mask = (1 << i);
478 ir_to_mesa_instruction *inst;
479 ir_to_mesa_src_reg src0 = orig_src0;
480 ir_to_mesa_src_reg src1 = orig_src1;
481
482 if (done_mask & this_mask)
483 continue;
484
485 GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
486 GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
487 for (j = i + 1; j < 4; j++) {
488 /* If there is another enabled component in the destination that is
489 * derived from the same inputs, generate its value on this pass as
490 * well.
491 */
492 if (!(done_mask & (1 << j)) &&
493 GET_SWZ(src0.swizzle, j) == src0_swiz &&
494 GET_SWZ(src1.swizzle, j) == src1_swiz) {
495 this_mask |= (1 << j);
496 }
497 }
498 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
499 src0_swiz, src0_swiz);
500 src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
501 src1_swiz, src1_swiz);
502
503 inst = ir_to_mesa_emit_op2(ir, op,
504 dst,
505 src0,
506 src1);
507 inst->dst_reg.writemask = this_mask;
508 done_mask |= this_mask;
509 }
510 }
511
512 void
513 ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
514 enum prog_opcode op,
515 ir_to_mesa_dst_reg dst,
516 ir_to_mesa_src_reg src0)
517 {
518 ir_to_mesa_src_reg undef = ir_to_mesa_undef;
519
520 undef.swizzle = SWIZZLE_XXXX;
521
522 ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
523 }
524
525 /**
526 * Emit an OPCODE_SCS instruction
527 *
528 * The \c SCS opcode functions a bit differently than the other Mesa (or
529 * ARB_fragment_program) opcodes. Instead of splatting its result across all
530 * four components of the destination, it writes one value to the \c x
531 * component and another value to the \c y component.
532 *
533 * \param ir IR instruction being processed
534 * \param op Either \c OPCODE_SIN or \c OPCODE_COS depending on which
535 * value is desired.
536 * \param dst Destination register
537 * \param src Source register
538 */
539 void
540 ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
541 ir_to_mesa_dst_reg dst,
542 const ir_to_mesa_src_reg &src)
543 {
544 /* Vertex programs cannot use the SCS opcode.
545 */
546 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
547 ir_to_mesa_emit_scalar_op1(ir, op, dst, src);
548 return;
549 }
550
551 const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
552 const unsigned scs_mask = (1U << component);
553 int done_mask = ~dst.writemask;
554 ir_to_mesa_src_reg tmp;
555
556 assert(op == OPCODE_SIN || op == OPCODE_COS);
557
558 /* If there are compnents in the destination that differ from the component
559 * that will be written by the SCS instrution, we'll need a temporary.
560 */
561 if (scs_mask != unsigned(dst.writemask)) {
562 tmp = get_temp(glsl_type::vec4_type);
563 }
564
565 for (unsigned i = 0; i < 4; i++) {
566 unsigned this_mask = (1U << i);
567 ir_to_mesa_src_reg src0 = src;
568
569 if ((done_mask & this_mask) != 0)
570 continue;
571
572 /* The source swizzle specified which component of the source generates
573 * sine / cosine for the current component in the destination. The SCS
574 * instruction requires that this value be swizzle to the X component.
575 * Replace the current swizzle with a swizzle that puts the source in
576 * the X component.
577 */
578 unsigned src0_swiz = GET_SWZ(src.swizzle, i);
579
580 src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
581 src0_swiz, src0_swiz);
582 for (unsigned j = i + 1; j < 4; j++) {
583 /* If there is another enabled component in the destination that is
584 * derived from the same inputs, generate its value on this pass as
585 * well.
586 */
587 if (!(done_mask & (1 << j)) &&
588 GET_SWZ(src0.swizzle, j) == src0_swiz) {
589 this_mask |= (1 << j);
590 }
591 }
592
593 if (this_mask != scs_mask) {
594 ir_to_mesa_instruction *inst;
595 ir_to_mesa_dst_reg tmp_dst = ir_to_mesa_dst_reg_from_src(tmp);
596
597 /* Emit the SCS instruction.
598 */
599 inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, tmp_dst, src0);
600 inst->dst_reg.writemask = scs_mask;
601
602 /* Move the result of the SCS instruction to the desired location in
603 * the destination.
604 */
605 tmp.swizzle = MAKE_SWIZZLE4(component, component,
606 component, component);
607 inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, tmp);
608 inst->dst_reg.writemask = this_mask;
609 } else {
610 /* Emit the SCS instruction to write directly to the destination.
611 */
612 ir_to_mesa_instruction *inst =
613 ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, src0);
614 inst->dst_reg.writemask = scs_mask;
615 }
616
617 done_mask |= this_mask;
618 }
619 }
620
621 struct ir_to_mesa_src_reg
622 ir_to_mesa_visitor::src_reg_for_float(float val)
623 {
624 ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
625
626 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
627 &val, 1, &src_reg.swizzle);
628
629 return src_reg;
630 }
631
632 static int
633 type_size(const struct glsl_type *type)
634 {
635 unsigned int i;
636 int size;
637
638 switch (type->base_type) {
639 case GLSL_TYPE_UINT:
640 case GLSL_TYPE_INT:
641 case GLSL_TYPE_FLOAT:
642 case GLSL_TYPE_BOOL:
643 if (type->is_matrix()) {
644 return type->matrix_columns;
645 } else {
646 /* Regardless of size of vector, it gets a vec4. This is bad
647 * packing for things like floats, but otherwise arrays become a
648 * mess. Hopefully a later pass over the code can pack scalars
649 * down if appropriate.
650 */
651 return 1;
652 }
653 case GLSL_TYPE_ARRAY:
654 assert(type->length > 0);
655 return type_size(type->fields.array) * type->length;
656 case GLSL_TYPE_STRUCT:
657 size = 0;
658 for (i = 0; i < type->length; i++) {
659 size += type_size(type->fields.structure[i].type);
660 }
661 return size;
662 case GLSL_TYPE_SAMPLER:
663 /* Samplers take up one slot in UNIFORMS[], but they're baked in
664 * at link time.
665 */
666 return 1;
667 default:
668 assert(0);
669 return 0;
670 }
671 }
672
673 /**
674 * In the initial pass of codegen, we assign temporary numbers to
675 * intermediate results. (not SSA -- variable assignments will reuse
676 * storage). Actual register allocation for the Mesa VM occurs in a
677 * pass over the Mesa IR later.
678 */
679 ir_to_mesa_src_reg
680 ir_to_mesa_visitor::get_temp(const glsl_type *type)
681 {
682 ir_to_mesa_src_reg src_reg;
683 int swizzle[4];
684 int i;
685
686 src_reg.file = PROGRAM_TEMPORARY;
687 src_reg.index = next_temp;
688 src_reg.reladdr = NULL;
689 next_temp += type_size(type);
690
691 if (type->is_array() || type->is_record()) {
692 src_reg.swizzle = SWIZZLE_NOOP;
693 } else {
694 for (i = 0; i < type->vector_elements; i++)
695 swizzle[i] = i;
696 for (; i < 4; i++)
697 swizzle[i] = type->vector_elements - 1;
698 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
699 swizzle[2], swizzle[3]);
700 }
701 src_reg.negate = 0;
702
703 return src_reg;
704 }
705
706 variable_storage *
707 ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
708 {
709
710 variable_storage *entry;
711
712 foreach_iter(exec_list_iterator, iter, this->variables) {
713 entry = (variable_storage *)iter.get();
714
715 if (entry->var == var)
716 return entry;
717 }
718
719 return NULL;
720 }
721
722 void
723 ir_to_mesa_visitor::visit(ir_variable *ir)
724 {
725 if (strcmp(ir->name, "gl_FragCoord") == 0) {
726 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
727
728 fp->OriginUpperLeft = ir->origin_upper_left;
729 fp->PixelCenterInteger = ir->pixel_center_integer;
730 }
731
732 if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
733 unsigned int i;
734 const struct gl_builtin_uniform_desc *statevar;
735
736 for (i = 0; _mesa_builtin_uniform_desc[i].name; i++) {
737 if (strcmp(ir->name, _mesa_builtin_uniform_desc[i].name) == 0)
738 break;
739 }
740
741 if (!_mesa_builtin_uniform_desc[i].name) {
742 fail_link(this->shader_program,
743 "Failed to find builtin uniform `%s'\n", ir->name);
744 return;
745 }
746
747 statevar = &_mesa_builtin_uniform_desc[i];
748
749 int array_count;
750 if (ir->type->is_array()) {
751 array_count = ir->type->length;
752 } else {
753 array_count = 1;
754 }
755
756 /* Check if this statevar's setup in the STATE file exactly
757 * matches how we'll want to reference it as a
758 * struct/array/whatever. If not, then we need to move it into
759 * temporary storage and hope that it'll get copy-propagated
760 * out.
761 */
762 for (i = 0; i < statevar->num_elements; i++) {
763 if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
764 break;
765 }
766 }
767
768 struct variable_storage *storage;
769 ir_to_mesa_dst_reg dst;
770 if (i == statevar->num_elements) {
771 /* We'll set the index later. */
772 storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
773 this->variables.push_tail(storage);
774
775 dst = ir_to_mesa_undef_dst;
776 } else {
777 storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
778 this->next_temp);
779 this->variables.push_tail(storage);
780 this->next_temp += type_size(ir->type);
781
782 dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
783 storage->index,
784 NULL));
785 }
786
787
788 for (int a = 0; a < array_count; a++) {
789 for (unsigned int i = 0; i < statevar->num_elements; i++) {
790 struct gl_builtin_uniform_element *element = &statevar->elements[i];
791 int tokens[STATE_LENGTH];
792
793 memcpy(tokens, element->tokens, sizeof(element->tokens));
794 if (ir->type->is_array()) {
795 tokens[1] = a;
796 }
797
798 int index = _mesa_add_state_reference(this->prog->Parameters,
799 (gl_state_index *)tokens);
800
801 if (storage->file == PROGRAM_STATE_VAR) {
802 if (storage->index == -1) {
803 storage->index = index;
804 } else {
805 assert(index ==
806 (int)(storage->index + a * statevar->num_elements + i));
807 }
808 } else {
809 ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
810 src.swizzle = element->swizzle;
811 ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
812 /* even a float takes up a whole vec4 reg in a struct/array. */
813 dst.index++;
814 }
815 }
816 }
817 if (storage->file == PROGRAM_TEMPORARY &&
818 dst.index != storage->index + type_size(ir->type)) {
819 fail_link(this->shader_program,
820 "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
821 ir->name, dst.index - storage->index,
822 type_size(ir->type));
823 }
824 }
825 }
826
827 void
828 ir_to_mesa_visitor::visit(ir_loop *ir)
829 {
830 ir_dereference_variable *counter = NULL;
831
832 if (ir->counter != NULL)
833 counter = new(ir) ir_dereference_variable(ir->counter);
834
835 if (ir->from != NULL) {
836 assert(ir->counter != NULL);
837
838 ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
839
840 a->accept(this);
841 delete a;
842 }
843
844 ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
845
846 if (ir->to) {
847 ir_expression *e =
848 new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
849 counter, ir->to);
850 ir_if *if_stmt = new(ir) ir_if(e);
851
852 ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
853
854 if_stmt->then_instructions.push_tail(brk);
855
856 if_stmt->accept(this);
857
858 delete if_stmt;
859 delete e;
860 delete brk;
861 }
862
863 visit_exec_list(&ir->body_instructions, this);
864
865 if (ir->increment) {
866 ir_expression *e =
867 new(ir) ir_expression(ir_binop_add, counter->type,
868 counter, ir->increment);
869
870 ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
871
872 a->accept(this);
873 delete a;
874 delete e;
875 }
876
877 ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
878 }
879
880 void
881 ir_to_mesa_visitor::visit(ir_loop_jump *ir)
882 {
883 switch (ir->mode) {
884 case ir_loop_jump::jump_break:
885 ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
886 break;
887 case ir_loop_jump::jump_continue:
888 ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
889 break;
890 }
891 }
892
893
894 void
895 ir_to_mesa_visitor::visit(ir_function_signature *ir)
896 {
897 assert(0);
898 (void)ir;
899 }
900
901 void
902 ir_to_mesa_visitor::visit(ir_function *ir)
903 {
904 /* Ignore function bodies other than main() -- we shouldn't see calls to
905 * them since they should all be inlined before we get to ir_to_mesa.
906 */
907 if (strcmp(ir->name, "main") == 0) {
908 const ir_function_signature *sig;
909 exec_list empty;
910
911 sig = ir->matching_signature(&empty);
912
913 assert(sig);
914
915 foreach_iter(exec_list_iterator, iter, sig->body) {
916 ir_instruction *ir = (ir_instruction *)iter.get();
917
918 ir->accept(this);
919 }
920 }
921 }
922
923 GLboolean
924 ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
925 {
926 int nonmul_operand = 1 - mul_operand;
927 ir_to_mesa_src_reg a, b, c;
928
929 ir_expression *expr = ir->operands[mul_operand]->as_expression();
930 if (!expr || expr->operation != ir_binop_mul)
931 return false;
932
933 expr->operands[0]->accept(this);
934 a = this->result;
935 expr->operands[1]->accept(this);
936 b = this->result;
937 ir->operands[nonmul_operand]->accept(this);
938 c = this->result;
939
940 this->result = get_temp(ir->type);
941 ir_to_mesa_emit_op3(ir, OPCODE_MAD,
942 ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
943
944 return true;
945 }
946
947 GLboolean
948 ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
949 {
950 /* Saturates were only introduced to vertex programs in
951 * NV_vertex_program3, so don't give them to drivers in the VP.
952 */
953 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
954 return false;
955
956 ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
957 if (!sat_src)
958 return false;
959
960 sat_src->accept(this);
961 ir_to_mesa_src_reg src = this->result;
962
963 this->result = get_temp(ir->type);
964 ir_to_mesa_instruction *inst;
965 inst = ir_to_mesa_emit_op1(ir, OPCODE_MOV,
966 ir_to_mesa_dst_reg_from_src(this->result),
967 src);
968 inst->saturate = true;
969
970 return true;
971 }
972
973 void
974 ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
975 ir_to_mesa_src_reg *reg, int *num_reladdr)
976 {
977 if (!reg->reladdr)
978 return;
979
980 ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
981
982 if (*num_reladdr != 1) {
983 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
984
985 ir_to_mesa_emit_op1(ir, OPCODE_MOV,
986 ir_to_mesa_dst_reg_from_src(temp), *reg);
987 *reg = temp;
988 }
989
990 (*num_reladdr)--;
991 }
992
993 void
994 ir_to_mesa_visitor::emit_swz(ir_expression *ir)
995 {
996 /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
997 * This means that each of the operands is either an immediate value of -1,
998 * 0, or 1, or is a component from one source register (possibly with
999 * negation).
1000 */
1001 uint8_t components[4] = { 0 };
1002 bool negate[4] = { false };
1003 ir_variable *var = NULL;
1004
1005 for (unsigned i = 0; i < ir->type->vector_elements; i++) {
1006 ir_rvalue *op = ir->operands[i];
1007
1008 assert(op->type->is_scalar());
1009
1010 while (op != NULL) {
1011 switch (op->ir_type) {
1012 case ir_type_constant: {
1013
1014 assert(op->type->is_scalar());
1015
1016 const ir_constant *const c = op->as_constant();
1017 if (c->is_one()) {
1018 components[i] = SWIZZLE_ONE;
1019 } else if (c->is_zero()) {
1020 components[i] = SWIZZLE_ZERO;
1021 } else if (c->is_negative_one()) {
1022 components[i] = SWIZZLE_ONE;
1023 negate[i] = true;
1024 } else {
1025 assert(!"SWZ constant must be 0.0 or 1.0.");
1026 }
1027
1028 op = NULL;
1029 break;
1030 }
1031
1032 case ir_type_dereference_variable: {
1033 ir_dereference_variable *const deref =
1034 (ir_dereference_variable *) op;
1035
1036 assert((var == NULL) || (deref->var == var));
1037 components[i] = SWIZZLE_X;
1038 var = deref->var;
1039 op = NULL;
1040 break;
1041 }
1042
1043 case ir_type_expression: {
1044 ir_expression *const expr = (ir_expression *) op;
1045
1046 assert(expr->operation == ir_unop_neg);
1047 negate[i] = true;
1048
1049 op = expr->operands[0];
1050 break;
1051 }
1052
1053 case ir_type_swizzle: {
1054 ir_swizzle *const swiz = (ir_swizzle *) op;
1055
1056 components[i] = swiz->mask.x;
1057 op = swiz->val;
1058 break;
1059 }
1060
1061 default:
1062 assert(!"Should not get here.");
1063 return;
1064 }
1065 }
1066 }
1067
1068 assert(var != NULL);
1069
1070 ir_dereference_variable *const deref =
1071 new(mem_ctx) ir_dereference_variable(var);
1072
1073 this->result.file = PROGRAM_UNDEFINED;
1074 deref->accept(this);
1075 if (this->result.file == PROGRAM_UNDEFINED) {
1076 ir_print_visitor v;
1077 printf("Failed to get tree for expression operand:\n");
1078 deref->accept(&v);
1079 exit(1);
1080 }
1081
1082 ir_to_mesa_src_reg src;
1083
1084 src = this->result;
1085 src.swizzle = MAKE_SWIZZLE4(components[0],
1086 components[1],
1087 components[2],
1088 components[3]);
1089 src.negate = ((unsigned(negate[0]) << 0)
1090 | (unsigned(negate[1]) << 1)
1091 | (unsigned(negate[2]) << 2)
1092 | (unsigned(negate[3]) << 3));
1093
1094 /* Storage for our result. Ideally for an assignment we'd be using the
1095 * actual storage for the result here, instead.
1096 */
1097 const ir_to_mesa_src_reg result_src = get_temp(ir->type);
1098 ir_to_mesa_dst_reg result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1099
1100 /* Limit writes to the channels that will be used by result_src later.
1101 * This does limit this temp's use as a temporary for multi-instruction
1102 * sequences.
1103 */
1104 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1105
1106 ir_to_mesa_emit_op1(ir, OPCODE_SWZ, result_dst, src);
1107 this->result = result_src;
1108 }
1109
1110 void
1111 ir_to_mesa_visitor::visit(ir_expression *ir)
1112 {
1113 unsigned int operand;
1114 struct ir_to_mesa_src_reg op[Elements(ir->operands)];
1115 struct ir_to_mesa_src_reg result_src;
1116 struct ir_to_mesa_dst_reg result_dst;
1117
1118 /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
1119 */
1120 if (ir->operation == ir_binop_add) {
1121 if (try_emit_mad(ir, 1))
1122 return;
1123 if (try_emit_mad(ir, 0))
1124 return;
1125 }
1126 if (try_emit_sat(ir))
1127 return;
1128
1129 if (ir->operation == ir_quadop_vector) {
1130 this->emit_swz(ir);
1131 return;
1132 }
1133
1134 for (operand = 0; operand < ir->get_num_operands(); operand++) {
1135 this->result.file = PROGRAM_UNDEFINED;
1136 ir->operands[operand]->accept(this);
1137 if (this->result.file == PROGRAM_UNDEFINED) {
1138 ir_print_visitor v;
1139 printf("Failed to get tree for expression operand:\n");
1140 ir->operands[operand]->accept(&v);
1141 exit(1);
1142 }
1143 op[operand] = this->result;
1144
1145 /* Matrix expression operands should have been broken down to vector
1146 * operations already.
1147 */
1148 assert(!ir->operands[operand]->type->is_matrix());
1149 }
1150
1151 int vector_elements = ir->operands[0]->type->vector_elements;
1152 if (ir->operands[1]) {
1153 vector_elements = MAX2(vector_elements,
1154 ir->operands[1]->type->vector_elements);
1155 }
1156
1157 this->result.file = PROGRAM_UNDEFINED;
1158
1159 /* Storage for our result. Ideally for an assignment we'd be using
1160 * the actual storage for the result here, instead.
1161 */
1162 result_src = get_temp(ir->type);
1163 /* convenience for the emit functions below. */
1164 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
1165 /* Limit writes to the channels that will be used by result_src later.
1166 * This does limit this temp's use as a temporary for multi-instruction
1167 * sequences.
1168 */
1169 result_dst.writemask = (1 << ir->type->vector_elements) - 1;
1170
1171 switch (ir->operation) {
1172 case ir_unop_logic_not:
1173 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
1174 op[0], src_reg_for_float(0.0));
1175 break;
1176 case ir_unop_neg:
1177 op[0].negate = ~op[0].negate;
1178 result_src = op[0];
1179 break;
1180 case ir_unop_abs:
1181 ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
1182 break;
1183 case ir_unop_sign:
1184 ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
1185 break;
1186 case ir_unop_rcp:
1187 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
1188 break;
1189
1190 case ir_unop_exp2:
1191 ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
1192 break;
1193 case ir_unop_exp:
1194 case ir_unop_log:
1195 assert(!"not reached: should be handled by ir_explog_to_explog2");
1196 break;
1197 case ir_unop_log2:
1198 ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
1199 break;
1200 case ir_unop_sin:
1201 ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
1202 break;
1203 case ir_unop_cos:
1204 ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
1205 break;
1206 case ir_unop_sin_reduced:
1207 emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
1208 break;
1209 case ir_unop_cos_reduced:
1210 emit_scs(ir, OPCODE_COS, result_dst, op[0]);
1211 break;
1212
1213 case ir_unop_dFdx:
1214 ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
1215 break;
1216 case ir_unop_dFdy:
1217 ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
1218 break;
1219
1220 case ir_unop_noise: {
1221 const enum prog_opcode opcode =
1222 prog_opcode(OPCODE_NOISE1
1223 + (ir->operands[0]->type->vector_elements) - 1);
1224 assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
1225
1226 ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
1227 break;
1228 }
1229
1230 case ir_binop_add:
1231 ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
1232 break;
1233 case ir_binop_sub:
1234 ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
1235 break;
1236
1237 case ir_binop_mul:
1238 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
1239 break;
1240 case ir_binop_div:
1241 assert(!"not reached: should be handled by ir_div_to_mul_rcp");
1242 case ir_binop_mod:
1243 assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
1244 break;
1245
1246 case ir_binop_less:
1247 ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
1248 break;
1249 case ir_binop_greater:
1250 ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
1251 break;
1252 case ir_binop_lequal:
1253 ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
1254 break;
1255 case ir_binop_gequal:
1256 ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
1257 break;
1258 case ir_binop_equal:
1259 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1260 break;
1261 case ir_binop_nequal:
1262 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1263 break;
1264 case ir_binop_all_equal:
1265 /* "==" operator producing a scalar boolean. */
1266 if (ir->operands[0]->type->is_vector() ||
1267 ir->operands[1]->type->is_vector()) {
1268 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1269 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1270 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1271 ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
1272 ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
1273 result_dst, result_src, src_reg_for_float(0.0));
1274 } else {
1275 ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
1276 }
1277 break;
1278 case ir_binop_any_nequal:
1279 /* "!=" operator producing a scalar boolean. */
1280 if (ir->operands[0]->type->is_vector() ||
1281 ir->operands[1]->type->is_vector()) {
1282 ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
1283 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1284 ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
1285 ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
1286 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1287 result_dst, result_src, src_reg_for_float(0.0));
1288 } else {
1289 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1290 }
1291 break;
1292
1293 case ir_unop_any:
1294 assert(ir->operands[0]->type->is_vector());
1295 ir_to_mesa_emit_dp(ir, result_dst, op[0], op[0],
1296 ir->operands[0]->type->vector_elements);
1297 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1298 result_dst, result_src, src_reg_for_float(0.0));
1299 break;
1300
1301 case ir_binop_logic_xor:
1302 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
1303 break;
1304
1305 case ir_binop_logic_or:
1306 /* This could be a saturated add and skip the SNE. */
1307 ir_to_mesa_emit_op2(ir, OPCODE_ADD,
1308 result_dst,
1309 op[0], op[1]);
1310
1311 ir_to_mesa_emit_op2(ir, OPCODE_SNE,
1312 result_dst,
1313 result_src, src_reg_for_float(0.0));
1314 break;
1315
1316 case ir_binop_logic_and:
1317 /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
1318 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1319 result_dst,
1320 op[0], op[1]);
1321 break;
1322
1323 case ir_binop_dot:
1324 assert(ir->operands[0]->type->is_vector());
1325 assert(ir->operands[0]->type == ir->operands[1]->type);
1326 ir_to_mesa_emit_dp(ir, result_dst, op[0], op[1],
1327 ir->operands[0]->type->vector_elements);
1328 break;
1329
1330 case ir_unop_sqrt:
1331 /* sqrt(x) = x * rsq(x). */
1332 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1333 ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
1334 /* For incoming channels <= 0, set the result to 0. */
1335 op[0].negate = ~op[0].negate;
1336 ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
1337 op[0], result_src, src_reg_for_float(0.0));
1338 break;
1339 case ir_unop_rsq:
1340 ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
1341 break;
1342 case ir_unop_i2f:
1343 case ir_unop_b2f:
1344 case ir_unop_b2i:
1345 /* Mesa IR lacks types, ints are stored as truncated floats. */
1346 result_src = op[0];
1347 break;
1348 case ir_unop_f2i:
1349 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1350 break;
1351 case ir_unop_f2b:
1352 case ir_unop_i2b:
1353 ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
1354 op[0], src_reg_for_float(0.0));
1355 break;
1356 case ir_unop_trunc:
1357 ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
1358 break;
1359 case ir_unop_ceil:
1360 op[0].negate = ~op[0].negate;
1361 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1362 result_src.negate = ~result_src.negate;
1363 break;
1364 case ir_unop_floor:
1365 ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
1366 break;
1367 case ir_unop_fract:
1368 ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
1369 break;
1370
1371 case ir_binop_min:
1372 ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
1373 break;
1374 case ir_binop_max:
1375 ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
1376 break;
1377 case ir_binop_pow:
1378 ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
1379 break;
1380
1381 case ir_unop_bit_not:
1382 case ir_unop_u2f:
1383 case ir_binop_lshift:
1384 case ir_binop_rshift:
1385 case ir_binop_bit_and:
1386 case ir_binop_bit_xor:
1387 case ir_binop_bit_or:
1388 case ir_unop_round_even:
1389 assert(!"GLSL 1.30 features unsupported");
1390 break;
1391
1392 case ir_quadop_vector:
1393 /* This operation should have already been handled.
1394 */
1395 assert(!"Should not get here.");
1396 break;
1397 }
1398
1399 this->result = result_src;
1400 }
1401
1402
1403 void
1404 ir_to_mesa_visitor::visit(ir_swizzle *ir)
1405 {
1406 ir_to_mesa_src_reg src_reg;
1407 int i;
1408 int swizzle[4];
1409
1410 /* Note that this is only swizzles in expressions, not those on the left
1411 * hand side of an assignment, which do write masking. See ir_assignment
1412 * for that.
1413 */
1414
1415 ir->val->accept(this);
1416 src_reg = this->result;
1417 assert(src_reg.file != PROGRAM_UNDEFINED);
1418
1419 for (i = 0; i < 4; i++) {
1420 if (i < ir->type->vector_elements) {
1421 switch (i) {
1422 case 0:
1423 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
1424 break;
1425 case 1:
1426 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
1427 break;
1428 case 2:
1429 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
1430 break;
1431 case 3:
1432 swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
1433 break;
1434 }
1435 } else {
1436 /* If the type is smaller than a vec4, replicate the last
1437 * channel out.
1438 */
1439 swizzle[i] = swizzle[ir->type->vector_elements - 1];
1440 }
1441 }
1442
1443 src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
1444 swizzle[1],
1445 swizzle[2],
1446 swizzle[3]);
1447
1448 this->result = src_reg;
1449 }
1450
1451 void
1452 ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
1453 {
1454 variable_storage *entry = find_variable_storage(ir->var);
1455
1456 if (!entry) {
1457 switch (ir->var->mode) {
1458 case ir_var_uniform:
1459 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
1460 ir->var->location);
1461 this->variables.push_tail(entry);
1462 break;
1463 case ir_var_in:
1464 case ir_var_out:
1465 case ir_var_inout:
1466 case ir_var_system_value:
1467 /* The linker assigns locations for varyings and attributes,
1468 * including deprecated builtins (like gl_Color), user-assign
1469 * generic attributes (glBindVertexLocation), and
1470 * user-defined varyings.
1471 *
1472 * FINISHME: We would hit this path for function arguments. Fix!
1473 */
1474 assert(ir->var->location != -1);
1475 if (ir->var->mode == ir_var_in ||
1476 ir->var->mode == ir_var_inout) {
1477 entry = new(mem_ctx) variable_storage(ir->var,
1478 PROGRAM_INPUT,
1479 ir->var->location);
1480
1481 if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
1482 ir->var->location >= VERT_ATTRIB_GENERIC0) {
1483 _mesa_add_attribute(prog->Attributes,
1484 ir->var->name,
1485 _mesa_sizeof_glsl_type(ir->var->type->gl_type),
1486 ir->var->type->gl_type,
1487 ir->var->location - VERT_ATTRIB_GENERIC0);
1488 }
1489 } else if (ir->var->mode == ir_var_system_value) {
1490 entry = new(mem_ctx) variable_storage(ir->var,
1491 PROGRAM_SYSTEM_VALUE,
1492 ir->var->location);
1493 } else {
1494 entry = new(mem_ctx) variable_storage(ir->var,
1495 PROGRAM_OUTPUT,
1496 ir->var->location);
1497 }
1498
1499 break;
1500 case ir_var_auto:
1501 case ir_var_temporary:
1502 entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
1503 this->next_temp);
1504 this->variables.push_tail(entry);
1505
1506 next_temp += type_size(ir->var->type);
1507 break;
1508 }
1509
1510 if (!entry) {
1511 printf("Failed to make storage for %s\n", ir->var->name);
1512 exit(1);
1513 }
1514 }
1515
1516 this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
1517 }
1518
1519 void
1520 ir_to_mesa_visitor::visit(ir_dereference_array *ir)
1521 {
1522 ir_constant *index;
1523 ir_to_mesa_src_reg src_reg;
1524 int element_size = type_size(ir->type);
1525
1526 index = ir->array_index->constant_expression_value();
1527
1528 ir->array->accept(this);
1529 src_reg = this->result;
1530
1531 if (index) {
1532 src_reg.index += index->value.i[0] * element_size;
1533 } else {
1534 ir_to_mesa_src_reg array_base = this->result;
1535 /* Variable index array dereference. It eats the "vec4" of the
1536 * base of the array and an index that offsets the Mesa register
1537 * index.
1538 */
1539 ir->array_index->accept(this);
1540
1541 ir_to_mesa_src_reg index_reg;
1542
1543 if (element_size == 1) {
1544 index_reg = this->result;
1545 } else {
1546 index_reg = get_temp(glsl_type::float_type);
1547
1548 ir_to_mesa_emit_op2(ir, OPCODE_MUL,
1549 ir_to_mesa_dst_reg_from_src(index_reg),
1550 this->result, src_reg_for_float(element_size));
1551 }
1552
1553 src_reg.reladdr = talloc(mem_ctx, ir_to_mesa_src_reg);
1554 memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
1555 }
1556
1557 /* If the type is smaller than a vec4, replicate the last channel out. */
1558 if (ir->type->is_scalar() || ir->type->is_vector())
1559 src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
1560 else
1561 src_reg.swizzle = SWIZZLE_NOOP;
1562
1563 this->result = src_reg;
1564 }
1565
1566 void
1567 ir_to_mesa_visitor::visit(ir_dereference_record *ir)
1568 {
1569 unsigned int i;
1570 const glsl_type *struct_type = ir->record->type;
1571 int offset = 0;
1572
1573 ir->record->accept(this);
1574
1575 for (i = 0; i < struct_type->length; i++) {
1576 if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
1577 break;
1578 offset += type_size(struct_type->fields.structure[i].type);
1579 }
1580
1581 /* If the type is smaller than a vec4, replicate the last channel out. */
1582 if (ir->type->is_scalar() || ir->type->is_vector())
1583 this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
1584 else
1585 this->result.swizzle = SWIZZLE_NOOP;
1586
1587 this->result.index += offset;
1588 }
1589
1590 /**
1591 * We want to be careful in assignment setup to hit the actual storage
1592 * instead of potentially using a temporary like we might with the
1593 * ir_dereference handler.
1594 */
1595 static struct ir_to_mesa_dst_reg
1596 get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
1597 {
1598 /* The LHS must be a dereference. If the LHS is a variable indexed array
1599 * access of a vector, it must be separated into a series conditional moves
1600 * before reaching this point (see ir_vec_index_to_cond_assign).
1601 */
1602 assert(ir->as_dereference());
1603 ir_dereference_array *deref_array = ir->as_dereference_array();
1604 if (deref_array) {
1605 assert(!deref_array->array->type->is_vector());
1606 }
1607
1608 /* Use the rvalue deref handler for the most part. We'll ignore
1609 * swizzles in it and write swizzles using writemask, though.
1610 */
1611 ir->accept(v);
1612 return ir_to_mesa_dst_reg_from_src(v->result);
1613 }
1614
1615 /**
1616 * Process the condition of a conditional assignment
1617 *
1618 * Examines the condition of a conditional assignment to generate the optimal
1619 * first operand of a \c CMP instruction. If the condition is a relational
1620 * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
1621 * used as the source for the \c CMP instruction. Otherwise the comparison
1622 * is processed to a boolean result, and the boolean result is used as the
1623 * operand to the CMP instruction.
1624 */
1625 bool
1626 ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
1627 {
1628 ir_rvalue *src_ir = ir;
1629 bool negate = true;
1630 bool switch_order = false;
1631
1632 ir_expression *const expr = ir->as_expression();
1633 if ((expr != NULL) && (expr->get_num_operands() == 2)) {
1634 bool zero_on_left = false;
1635
1636 if (expr->operands[0]->is_zero()) {
1637 src_ir = expr->operands[1];
1638 zero_on_left = true;
1639 } else if (expr->operands[1]->is_zero()) {
1640 src_ir = expr->operands[0];
1641 zero_on_left = false;
1642 }
1643
1644 /* a is - 0 + - 0 +
1645 * (a < 0) T F F ( a < 0) T F F
1646 * (0 < a) F F T (-a < 0) F F T
1647 * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
1648 * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
1649 * (a > 0) F F T (-a < 0) F F T
1650 * (0 > a) T F F ( a < 0) T F F
1651 * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
1652 * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
1653 *
1654 * Note that exchanging the order of 0 and 'a' in the comparison simply
1655 * means that the value of 'a' should be negated.
1656 */
1657 if (src_ir != ir) {
1658 switch (expr->operation) {
1659 case ir_binop_less:
1660 switch_order = false;
1661 negate = zero_on_left;
1662 break;
1663
1664 case ir_binop_greater:
1665 switch_order = false;
1666 negate = !zero_on_left;
1667 break;
1668
1669 case ir_binop_lequal:
1670 switch_order = true;
1671 negate = !zero_on_left;
1672 break;
1673
1674 case ir_binop_gequal:
1675 switch_order = true;
1676 negate = zero_on_left;
1677 break;
1678
1679 default:
1680 /* This isn't the right kind of comparison afterall, so make sure
1681 * the whole condition is visited.
1682 */
1683 src_ir = ir;
1684 break;
1685 }
1686 }
1687 }
1688
1689 src_ir->accept(this);
1690
1691 /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
1692 * condition we produced is 0.0 or 1.0. By flipping the sign, we can
1693 * choose which value OPCODE_CMP produces without an extra instruction
1694 * computing the condition.
1695 */
1696 if (negate)
1697 this->result.negate = ~this->result.negate;
1698
1699 return switch_order;
1700 }
1701
1702 void
1703 ir_to_mesa_visitor::visit(ir_assignment *ir)
1704 {
1705 struct ir_to_mesa_dst_reg l;
1706 struct ir_to_mesa_src_reg r;
1707 int i;
1708
1709 ir->rhs->accept(this);
1710 r = this->result;
1711
1712 l = get_assignment_lhs(ir->lhs, this);
1713
1714 /* FINISHME: This should really set to the correct maximal writemask for each
1715 * FINISHME: component written (in the loops below). This case can only
1716 * FINISHME: occur for matrices, arrays, and structures.
1717 */
1718 if (ir->write_mask == 0) {
1719 assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
1720 l.writemask = WRITEMASK_XYZW;
1721 } else if (ir->lhs->type->is_scalar()) {
1722 /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
1723 * FINISHME: W component of fragment shader output zero, work correctly.
1724 */
1725 l.writemask = WRITEMASK_XYZW;
1726 } else {
1727 int swizzles[4];
1728 int first_enabled_chan = 0;
1729 int rhs_chan = 0;
1730
1731 assert(ir->lhs->type->is_vector());
1732 l.writemask = ir->write_mask;
1733
1734 for (int i = 0; i < 4; i++) {
1735 if (l.writemask & (1 << i)) {
1736 first_enabled_chan = GET_SWZ(r.swizzle, i);
1737 break;
1738 }
1739 }
1740
1741 /* Swizzle a small RHS vector into the channels being written.
1742 *
1743 * glsl ir treats write_mask as dictating how many channels are
1744 * present on the RHS while Mesa IR treats write_mask as just
1745 * showing which channels of the vec4 RHS get written.
1746 */
1747 for (int i = 0; i < 4; i++) {
1748 if (l.writemask & (1 << i))
1749 swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
1750 else
1751 swizzles[i] = first_enabled_chan;
1752 }
1753 r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
1754 swizzles[2], swizzles[3]);
1755 }
1756
1757 assert(l.file != PROGRAM_UNDEFINED);
1758 assert(r.file != PROGRAM_UNDEFINED);
1759
1760 if (ir->condition) {
1761 const bool switch_order = this->process_move_condition(ir->condition);
1762 ir_to_mesa_src_reg condition = this->result;
1763
1764 for (i = 0; i < type_size(ir->lhs->type); i++) {
1765 if (switch_order) {
1766 ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
1767 condition, ir_to_mesa_src_reg_from_dst(l), r);
1768 } else {
1769 ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
1770 condition, r, ir_to_mesa_src_reg_from_dst(l));
1771 }
1772
1773 l.index++;
1774 r.index++;
1775 }
1776 } else {
1777 for (i = 0; i < type_size(ir->lhs->type); i++) {
1778 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1779 l.index++;
1780 r.index++;
1781 }
1782 }
1783 }
1784
1785
1786 void
1787 ir_to_mesa_visitor::visit(ir_constant *ir)
1788 {
1789 ir_to_mesa_src_reg src_reg;
1790 GLfloat stack_vals[4] = { 0 };
1791 GLfloat *values = stack_vals;
1792 unsigned int i;
1793
1794 /* Unfortunately, 4 floats is all we can get into
1795 * _mesa_add_unnamed_constant. So, make a temp to store an
1796 * aggregate constant and move each constant value into it. If we
1797 * get lucky, copy propagation will eliminate the extra moves.
1798 */
1799
1800 if (ir->type->base_type == GLSL_TYPE_STRUCT) {
1801 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1802 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1803
1804 foreach_iter(exec_list_iterator, iter, ir->components) {
1805 ir_constant *field_value = (ir_constant *)iter.get();
1806 int size = type_size(field_value->type);
1807
1808 assert(size > 0);
1809
1810 field_value->accept(this);
1811 src_reg = this->result;
1812
1813 for (i = 0; i < (unsigned int)size; i++) {
1814 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1815
1816 src_reg.index++;
1817 temp.index++;
1818 }
1819 }
1820 this->result = temp_base;
1821 return;
1822 }
1823
1824 if (ir->type->is_array()) {
1825 ir_to_mesa_src_reg temp_base = get_temp(ir->type);
1826 ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
1827 int size = type_size(ir->type->fields.array);
1828
1829 assert(size > 0);
1830
1831 for (i = 0; i < ir->type->length; i++) {
1832 ir->array_elements[i]->accept(this);
1833 src_reg = this->result;
1834 for (int j = 0; j < size; j++) {
1835 ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
1836
1837 src_reg.index++;
1838 temp.index++;
1839 }
1840 }
1841 this->result = temp_base;
1842 return;
1843 }
1844
1845 if (ir->type->is_matrix()) {
1846 ir_to_mesa_src_reg mat = get_temp(ir->type);
1847 ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
1848
1849 for (i = 0; i < ir->type->matrix_columns; i++) {
1850 assert(ir->type->base_type == GLSL_TYPE_FLOAT);
1851 values = &ir->value.f[i * ir->type->vector_elements];
1852
1853 src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
1854 src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1855 values,
1856 ir->type->vector_elements,
1857 &src_reg.swizzle);
1858 ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
1859
1860 mat_column.index++;
1861 }
1862
1863 this->result = mat;
1864 return;
1865 }
1866
1867 src_reg.file = PROGRAM_CONSTANT;
1868 switch (ir->type->base_type) {
1869 case GLSL_TYPE_FLOAT:
1870 values = &ir->value.f[0];
1871 break;
1872 case GLSL_TYPE_UINT:
1873 for (i = 0; i < ir->type->vector_elements; i++) {
1874 values[i] = ir->value.u[i];
1875 }
1876 break;
1877 case GLSL_TYPE_INT:
1878 for (i = 0; i < ir->type->vector_elements; i++) {
1879 values[i] = ir->value.i[i];
1880 }
1881 break;
1882 case GLSL_TYPE_BOOL:
1883 for (i = 0; i < ir->type->vector_elements; i++) {
1884 values[i] = ir->value.b[i];
1885 }
1886 break;
1887 default:
1888 assert(!"Non-float/uint/int/bool constant");
1889 }
1890
1891 this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
1892 this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
1893 values,
1894 ir->type->vector_elements,
1895 &this->result.swizzle);
1896 }
1897
1898 function_entry *
1899 ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
1900 {
1901 function_entry *entry;
1902
1903 foreach_iter(exec_list_iterator, iter, this->function_signatures) {
1904 entry = (function_entry *)iter.get();
1905
1906 if (entry->sig == sig)
1907 return entry;
1908 }
1909
1910 entry = talloc(mem_ctx, function_entry);
1911 entry->sig = sig;
1912 entry->sig_id = this->next_signature_id++;
1913 entry->bgn_inst = NULL;
1914
1915 /* Allocate storage for all the parameters. */
1916 foreach_iter(exec_list_iterator, iter, sig->parameters) {
1917 ir_variable *param = (ir_variable *)iter.get();
1918 variable_storage *storage;
1919
1920 storage = find_variable_storage(param);
1921 assert(!storage);
1922
1923 storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
1924 this->next_temp);
1925 this->variables.push_tail(storage);
1926
1927 this->next_temp += type_size(param->type);
1928 }
1929
1930 if (!sig->return_type->is_void()) {
1931 entry->return_reg = get_temp(sig->return_type);
1932 } else {
1933 entry->return_reg = ir_to_mesa_undef;
1934 }
1935
1936 this->function_signatures.push_tail(entry);
1937 return entry;
1938 }
1939
1940 void
1941 ir_to_mesa_visitor::visit(ir_call *ir)
1942 {
1943 ir_to_mesa_instruction *call_inst;
1944 ir_function_signature *sig = ir->get_callee();
1945 function_entry *entry = get_function_signature(sig);
1946 int i;
1947
1948 /* Process in parameters. */
1949 exec_list_iterator sig_iter = sig->parameters.iterator();
1950 foreach_iter(exec_list_iterator, iter, *ir) {
1951 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1952 ir_variable *param = (ir_variable *)sig_iter.get();
1953
1954 if (param->mode == ir_var_in ||
1955 param->mode == ir_var_inout) {
1956 variable_storage *storage = find_variable_storage(param);
1957 assert(storage);
1958
1959 param_rval->accept(this);
1960 ir_to_mesa_src_reg r = this->result;
1961
1962 ir_to_mesa_dst_reg l;
1963 l.file = storage->file;
1964 l.index = storage->index;
1965 l.reladdr = NULL;
1966 l.writemask = WRITEMASK_XYZW;
1967 l.cond_mask = COND_TR;
1968
1969 for (i = 0; i < type_size(param->type); i++) {
1970 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
1971 l.index++;
1972 r.index++;
1973 }
1974 }
1975
1976 sig_iter.next();
1977 }
1978 assert(!sig_iter.has_next());
1979
1980 /* Emit call instruction */
1981 call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
1982 ir_to_mesa_undef_dst, ir_to_mesa_undef);
1983 call_inst->function = entry;
1984
1985 /* Process out parameters. */
1986 sig_iter = sig->parameters.iterator();
1987 foreach_iter(exec_list_iterator, iter, *ir) {
1988 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
1989 ir_variable *param = (ir_variable *)sig_iter.get();
1990
1991 if (param->mode == ir_var_out ||
1992 param->mode == ir_var_inout) {
1993 variable_storage *storage = find_variable_storage(param);
1994 assert(storage);
1995
1996 ir_to_mesa_src_reg r;
1997 r.file = storage->file;
1998 r.index = storage->index;
1999 r.reladdr = NULL;
2000 r.swizzle = SWIZZLE_NOOP;
2001 r.negate = 0;
2002
2003 param_rval->accept(this);
2004 ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
2005
2006 for (i = 0; i < type_size(param->type); i++) {
2007 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
2008 l.index++;
2009 r.index++;
2010 }
2011 }
2012
2013 sig_iter.next();
2014 }
2015 assert(!sig_iter.has_next());
2016
2017 /* Process return value. */
2018 this->result = entry->return_reg;
2019 }
2020
2021 void
2022 ir_to_mesa_visitor::visit(ir_texture *ir)
2023 {
2024 ir_to_mesa_src_reg result_src, coord, lod_info, projector;
2025 ir_to_mesa_dst_reg result_dst, coord_dst;
2026 ir_to_mesa_instruction *inst = NULL;
2027 prog_opcode opcode = OPCODE_NOP;
2028
2029 ir->coordinate->accept(this);
2030
2031 /* Put our coords in a temp. We'll need to modify them for shadow,
2032 * projection, or LOD, so the only case we'd use it as is is if
2033 * we're doing plain old texturing. Mesa IR optimization should
2034 * handle cleaning up our mess in that case.
2035 */
2036 coord = get_temp(glsl_type::vec4_type);
2037 coord_dst = ir_to_mesa_dst_reg_from_src(coord);
2038 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
2039 this->result);
2040
2041 if (ir->projector) {
2042 ir->projector->accept(this);
2043 projector = this->result;
2044 }
2045
2046 /* Storage for our result. Ideally for an assignment we'd be using
2047 * the actual storage for the result here, instead.
2048 */
2049 result_src = get_temp(glsl_type::vec4_type);
2050 result_dst = ir_to_mesa_dst_reg_from_src(result_src);
2051
2052 switch (ir->op) {
2053 case ir_tex:
2054 opcode = OPCODE_TEX;
2055 break;
2056 case ir_txb:
2057 opcode = OPCODE_TXB;
2058 ir->lod_info.bias->accept(this);
2059 lod_info = this->result;
2060 break;
2061 case ir_txl:
2062 opcode = OPCODE_TXL;
2063 ir->lod_info.lod->accept(this);
2064 lod_info = this->result;
2065 break;
2066 case ir_txd:
2067 case ir_txf:
2068 assert(!"GLSL 1.30 features unsupported");
2069 break;
2070 }
2071
2072 if (ir->projector) {
2073 if (opcode == OPCODE_TEX) {
2074 /* Slot the projector in as the last component of the coord. */
2075 coord_dst.writemask = WRITEMASK_W;
2076 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
2077 coord_dst.writemask = WRITEMASK_XYZW;
2078 opcode = OPCODE_TXP;
2079 } else {
2080 ir_to_mesa_src_reg coord_w = coord;
2081 coord_w.swizzle = SWIZZLE_WWWW;
2082
2083 /* For the other TEX opcodes there's no projective version
2084 * since the last slot is taken up by lod info. Do the
2085 * projective divide now.
2086 */
2087 coord_dst.writemask = WRITEMASK_W;
2088 ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
2089
2090 coord_dst.writemask = WRITEMASK_XYZ;
2091 ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
2092
2093 coord_dst.writemask = WRITEMASK_XYZW;
2094 coord.swizzle = SWIZZLE_XYZW;
2095 }
2096 }
2097
2098 if (ir->shadow_comparitor) {
2099 /* Slot the shadow value in as the second to last component of the
2100 * coord.
2101 */
2102 ir->shadow_comparitor->accept(this);
2103 coord_dst.writemask = WRITEMASK_Z;
2104 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
2105 coord_dst.writemask = WRITEMASK_XYZW;
2106 }
2107
2108 if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
2109 /* Mesa IR stores lod or lod bias in the last channel of the coords. */
2110 coord_dst.writemask = WRITEMASK_W;
2111 ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
2112 coord_dst.writemask = WRITEMASK_XYZW;
2113 }
2114
2115 inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
2116
2117 if (ir->shadow_comparitor)
2118 inst->tex_shadow = GL_TRUE;
2119
2120 inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
2121 this->shader_program,
2122 this->prog);
2123
2124 const glsl_type *sampler_type = ir->sampler->type;
2125
2126 switch (sampler_type->sampler_dimensionality) {
2127 case GLSL_SAMPLER_DIM_1D:
2128 inst->tex_target = (sampler_type->sampler_array)
2129 ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
2130 break;
2131 case GLSL_SAMPLER_DIM_2D:
2132 inst->tex_target = (sampler_type->sampler_array)
2133 ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
2134 break;
2135 case GLSL_SAMPLER_DIM_3D:
2136 inst->tex_target = TEXTURE_3D_INDEX;
2137 break;
2138 case GLSL_SAMPLER_DIM_CUBE:
2139 inst->tex_target = TEXTURE_CUBE_INDEX;
2140 break;
2141 case GLSL_SAMPLER_DIM_RECT:
2142 inst->tex_target = TEXTURE_RECT_INDEX;
2143 break;
2144 case GLSL_SAMPLER_DIM_BUF:
2145 assert(!"FINISHME: Implement ARB_texture_buffer_object");
2146 break;
2147 default:
2148 assert(!"Should not get here.");
2149 }
2150
2151 this->result = result_src;
2152 }
2153
2154 void
2155 ir_to_mesa_visitor::visit(ir_return *ir)
2156 {
2157 if (ir->get_value()) {
2158 ir_to_mesa_dst_reg l;
2159 int i;
2160
2161 assert(current_function);
2162
2163 ir->get_value()->accept(this);
2164 ir_to_mesa_src_reg r = this->result;
2165
2166 l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
2167
2168 for (i = 0; i < type_size(current_function->sig->return_type); i++) {
2169 ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
2170 l.index++;
2171 r.index++;
2172 }
2173 }
2174
2175 ir_to_mesa_emit_op0(ir, OPCODE_RET);
2176 }
2177
2178 void
2179 ir_to_mesa_visitor::visit(ir_discard *ir)
2180 {
2181 struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
2182
2183 if (ir->condition) {
2184 ir->condition->accept(this);
2185 this->result.negate = ~this->result.negate;
2186 ir_to_mesa_emit_op1(ir, OPCODE_KIL, ir_to_mesa_undef_dst, this->result);
2187 } else {
2188 ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
2189 }
2190
2191 fp->UsesKill = GL_TRUE;
2192 }
2193
2194 void
2195 ir_to_mesa_visitor::visit(ir_if *ir)
2196 {
2197 ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
2198 ir_to_mesa_instruction *prev_inst;
2199
2200 prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2201
2202 ir->condition->accept(this);
2203 assert(this->result.file != PROGRAM_UNDEFINED);
2204
2205 if (this->options->EmitCondCodes) {
2206 cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
2207
2208 /* See if we actually generated any instruction for generating
2209 * the condition. If not, then cook up a move to a temp so we
2210 * have something to set cond_update on.
2211 */
2212 if (cond_inst == prev_inst) {
2213 ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
2214 cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
2215 ir_to_mesa_dst_reg_from_src(temp),
2216 result);
2217 }
2218 cond_inst->cond_update = GL_TRUE;
2219
2220 if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
2221 if_inst->dst_reg.cond_mask = COND_NE;
2222 } else {
2223 if_inst = ir_to_mesa_emit_op1(ir->condition,
2224 OPCODE_IF, ir_to_mesa_undef_dst,
2225 this->result);
2226 }
2227
2228 this->instructions.push_tail(if_inst);
2229
2230 visit_exec_list(&ir->then_instructions, this);
2231
2232 if (!ir->else_instructions.is_empty()) {
2233 else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
2234 visit_exec_list(&ir->else_instructions, this);
2235 }
2236
2237 if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
2238 ir_to_mesa_undef_dst, ir_to_mesa_undef);
2239 }
2240
2241 ir_to_mesa_visitor::ir_to_mesa_visitor()
2242 {
2243 result.file = PROGRAM_UNDEFINED;
2244 next_temp = 1;
2245 next_signature_id = 1;
2246 current_function = NULL;
2247 mem_ctx = talloc_new(NULL);
2248 }
2249
2250 ir_to_mesa_visitor::~ir_to_mesa_visitor()
2251 {
2252 talloc_free(mem_ctx);
2253 }
2254
2255 static struct prog_src_register
2256 mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
2257 {
2258 struct prog_src_register mesa_reg;
2259
2260 mesa_reg.File = reg.file;
2261 assert(reg.index < (1 << INST_INDEX_BITS));
2262 mesa_reg.Index = reg.index;
2263 mesa_reg.Swizzle = reg.swizzle;
2264 mesa_reg.RelAddr = reg.reladdr != NULL;
2265 mesa_reg.Negate = reg.negate;
2266 mesa_reg.Abs = 0;
2267 mesa_reg.HasIndex2 = GL_FALSE;
2268 mesa_reg.RelAddr2 = 0;
2269 mesa_reg.Index2 = 0;
2270
2271 return mesa_reg;
2272 }
2273
2274 static void
2275 set_branchtargets(ir_to_mesa_visitor *v,
2276 struct prog_instruction *mesa_instructions,
2277 int num_instructions)
2278 {
2279 int if_count = 0, loop_count = 0;
2280 int *if_stack, *loop_stack;
2281 int if_stack_pos = 0, loop_stack_pos = 0;
2282 int i, j;
2283
2284 for (i = 0; i < num_instructions; i++) {
2285 switch (mesa_instructions[i].Opcode) {
2286 case OPCODE_IF:
2287 if_count++;
2288 break;
2289 case OPCODE_BGNLOOP:
2290 loop_count++;
2291 break;
2292 case OPCODE_BRK:
2293 case OPCODE_CONT:
2294 mesa_instructions[i].BranchTarget = -1;
2295 break;
2296 default:
2297 break;
2298 }
2299 }
2300
2301 if_stack = talloc_zero_array(v->mem_ctx, int, if_count);
2302 loop_stack = talloc_zero_array(v->mem_ctx, int, loop_count);
2303
2304 for (i = 0; i < num_instructions; i++) {
2305 switch (mesa_instructions[i].Opcode) {
2306 case OPCODE_IF:
2307 if_stack[if_stack_pos] = i;
2308 if_stack_pos++;
2309 break;
2310 case OPCODE_ELSE:
2311 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2312 if_stack[if_stack_pos - 1] = i;
2313 break;
2314 case OPCODE_ENDIF:
2315 mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
2316 if_stack_pos--;
2317 break;
2318 case OPCODE_BGNLOOP:
2319 loop_stack[loop_stack_pos] = i;
2320 loop_stack_pos++;
2321 break;
2322 case OPCODE_ENDLOOP:
2323 loop_stack_pos--;
2324 /* Rewrite any breaks/conts at this nesting level (haven't
2325 * already had a BranchTarget assigned) to point to the end
2326 * of the loop.
2327 */
2328 for (j = loop_stack[loop_stack_pos]; j < i; j++) {
2329 if (mesa_instructions[j].Opcode == OPCODE_BRK ||
2330 mesa_instructions[j].Opcode == OPCODE_CONT) {
2331 if (mesa_instructions[j].BranchTarget == -1) {
2332 mesa_instructions[j].BranchTarget = i;
2333 }
2334 }
2335 }
2336 /* The loop ends point at each other. */
2337 mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
2338 mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
2339 break;
2340 case OPCODE_CAL:
2341 foreach_iter(exec_list_iterator, iter, v->function_signatures) {
2342 function_entry *entry = (function_entry *)iter.get();
2343
2344 if (entry->sig_id == mesa_instructions[i].BranchTarget) {
2345 mesa_instructions[i].BranchTarget = entry->inst;
2346 break;
2347 }
2348 }
2349 break;
2350 default:
2351 break;
2352 }
2353 }
2354 }
2355
2356 static void
2357 print_program(struct prog_instruction *mesa_instructions,
2358 ir_instruction **mesa_instruction_annotation,
2359 int num_instructions)
2360 {
2361 ir_instruction *last_ir = NULL;
2362 int i;
2363 int indent = 0;
2364
2365 for (i = 0; i < num_instructions; i++) {
2366 struct prog_instruction *mesa_inst = mesa_instructions + i;
2367 ir_instruction *ir = mesa_instruction_annotation[i];
2368
2369 fprintf(stdout, "%3d: ", i);
2370
2371 if (last_ir != ir && ir) {
2372 int j;
2373
2374 for (j = 0; j < indent; j++) {
2375 fprintf(stdout, " ");
2376 }
2377 ir->print();
2378 printf("\n");
2379 last_ir = ir;
2380
2381 fprintf(stdout, " "); /* line number spacing. */
2382 }
2383
2384 indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
2385 PROG_PRINT_DEBUG, NULL);
2386 }
2387 }
2388
2389 static void
2390 count_resources(struct gl_program *prog)
2391 {
2392 unsigned int i;
2393
2394 prog->SamplersUsed = 0;
2395
2396 for (i = 0; i < prog->NumInstructions; i++) {
2397 struct prog_instruction *inst = &prog->Instructions[i];
2398
2399 if (_mesa_is_tex_instruction(inst->Opcode)) {
2400 prog->SamplerTargets[inst->TexSrcUnit] =
2401 (gl_texture_index)inst->TexSrcTarget;
2402 prog->SamplersUsed |= 1 << inst->TexSrcUnit;
2403 if (inst->TexShadow) {
2404 prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
2405 }
2406 }
2407 }
2408
2409 _mesa_update_shader_textures_used(prog);
2410 }
2411
2412 struct uniform_sort {
2413 struct gl_uniform *u;
2414 int pos;
2415 };
2416
2417 /* The shader_program->Uniforms list is almost sorted in increasing
2418 * uniform->{Frag,Vert}Pos locations, but not quite when there are
2419 * uniforms shared between targets. We need to add parameters in
2420 * increasing order for the targets.
2421 */
2422 static int
2423 sort_uniforms(const void *a, const void *b)
2424 {
2425 struct uniform_sort *u1 = (struct uniform_sort *)a;
2426 struct uniform_sort *u2 = (struct uniform_sort *)b;
2427
2428 return u1->pos - u2->pos;
2429 }
2430
2431 /* Add the uniforms to the parameters. The linker chose locations
2432 * in our parameters lists (which weren't created yet), which the
2433 * uniforms code will use to poke values into our parameters list
2434 * when uniforms are updated.
2435 */
2436 static void
2437 add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
2438 struct gl_shader *shader,
2439 struct gl_program *prog)
2440 {
2441 unsigned int i;
2442 unsigned int next_sampler = 0, num_uniforms = 0;
2443 struct uniform_sort *sorted_uniforms;
2444
2445 sorted_uniforms = talloc_array(NULL, struct uniform_sort,
2446 shader_program->Uniforms->NumUniforms);
2447
2448 for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
2449 struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
2450 int parameter_index = -1;
2451
2452 switch (shader->Type) {
2453 case GL_VERTEX_SHADER:
2454 parameter_index = uniform->VertPos;
2455 break;
2456 case GL_FRAGMENT_SHADER:
2457 parameter_index = uniform->FragPos;
2458 break;
2459 case GL_GEOMETRY_SHADER:
2460 parameter_index = uniform->GeomPos;
2461 break;
2462 }
2463
2464 /* Only add uniforms used in our target. */
2465 if (parameter_index != -1) {
2466 sorted_uniforms[num_uniforms].pos = parameter_index;
2467 sorted_uniforms[num_uniforms].u = uniform;
2468 num_uniforms++;
2469 }
2470 }
2471
2472 qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
2473 sort_uniforms);
2474
2475 for (i = 0; i < num_uniforms; i++) {
2476 struct gl_uniform *uniform = sorted_uniforms[i].u;
2477 int parameter_index = sorted_uniforms[i].pos;
2478 const glsl_type *type = uniform->Type;
2479 unsigned int size;
2480
2481 if (type->is_vector() ||
2482 type->is_scalar()) {
2483 size = type->vector_elements;
2484 } else {
2485 size = type_size(type) * 4;
2486 }
2487
2488 gl_register_file file;
2489 if (type->is_sampler() ||
2490 (type->is_array() && type->fields.array->is_sampler())) {
2491 file = PROGRAM_SAMPLER;
2492 } else {
2493 file = PROGRAM_UNIFORM;
2494 }
2495
2496 GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
2497 uniform->Name);
2498
2499 if (index < 0) {
2500 index = _mesa_add_parameter(prog->Parameters, file,
2501 uniform->Name, size, type->gl_type,
2502 NULL, NULL, 0x0);
2503
2504 /* Sampler uniform values are stored in prog->SamplerUnits,
2505 * and the entry in that array is selected by this index we
2506 * store in ParameterValues[].
2507 */
2508 if (file == PROGRAM_SAMPLER) {
2509 for (unsigned int j = 0; j < size / 4; j++)
2510 prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
2511 }
2512
2513 /* The location chosen in the Parameters list here (returned
2514 * from _mesa_add_uniform) has to match what the linker chose.
2515 */
2516 if (index != parameter_index) {
2517 fail_link(shader_program, "Allocation of uniform `%s' to target "
2518 "failed (%d vs %d)\n",
2519 uniform->Name, index, parameter_index);
2520 }
2521 }
2522 }
2523
2524 talloc_free(sorted_uniforms);
2525 }
2526
2527 static void
2528 set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
2529 struct gl_shader_program *shader_program,
2530 const char *name, const glsl_type *type,
2531 ir_constant *val)
2532 {
2533 if (type->is_record()) {
2534 ir_constant *field_constant;
2535
2536 field_constant = (ir_constant *)val->components.get_head();
2537
2538 for (unsigned int i = 0; i < type->length; i++) {
2539 const glsl_type *field_type = type->fields.structure[i].type;
2540 const char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
2541 type->fields.structure[i].name);
2542 set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
2543 field_type, field_constant);
2544 field_constant = (ir_constant *)field_constant->next;
2545 }
2546 return;
2547 }
2548
2549 int loc = _mesa_get_uniform_location(ctx, shader_program, name);
2550
2551 if (loc == -1) {
2552 fail_link(shader_program,
2553 "Couldn't find uniform for initializer %s\n", name);
2554 return;
2555 }
2556
2557 for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
2558 ir_constant *element;
2559 const glsl_type *element_type;
2560 if (type->is_array()) {
2561 element = val->array_elements[i];
2562 element_type = type->fields.array;
2563 } else {
2564 element = val;
2565 element_type = type;
2566 }
2567
2568 void *values;
2569
2570 if (element_type->base_type == GLSL_TYPE_BOOL) {
2571 int *conv = talloc_array(mem_ctx, int, element_type->components());
2572 for (unsigned int j = 0; j < element_type->components(); j++) {
2573 conv[j] = element->value.b[j];
2574 }
2575 values = (void *)conv;
2576 element_type = glsl_type::get_instance(GLSL_TYPE_INT,
2577 element_type->vector_elements,
2578 1);
2579 } else {
2580 values = &element->value;
2581 }
2582
2583 if (element_type->is_matrix()) {
2584 _mesa_uniform_matrix(ctx, shader_program,
2585 element_type->matrix_columns,
2586 element_type->vector_elements,
2587 loc, 1, GL_FALSE, (GLfloat *)values);
2588 loc += element_type->matrix_columns;
2589 } else {
2590 _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
2591 values, element_type->gl_type);
2592 loc += type_size(element_type);
2593 }
2594 }
2595 }
2596
2597 static void
2598 set_uniform_initializers(struct gl_context *ctx,
2599 struct gl_shader_program *shader_program)
2600 {
2601 void *mem_ctx = NULL;
2602
2603 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2604 struct gl_shader *shader = shader_program->_LinkedShaders[i];
2605
2606 if (shader == NULL)
2607 continue;
2608
2609 foreach_iter(exec_list_iterator, iter, *shader->ir) {
2610 ir_instruction *ir = (ir_instruction *)iter.get();
2611 ir_variable *var = ir->as_variable();
2612
2613 if (!var || var->mode != ir_var_uniform || !var->constant_value)
2614 continue;
2615
2616 if (!mem_ctx)
2617 mem_ctx = talloc_new(NULL);
2618
2619 set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
2620 var->type, var->constant_value);
2621 }
2622 }
2623
2624 talloc_free(mem_ctx);
2625 }
2626
2627 /*
2628 * On a basic block basis, tracks available PROGRAM_TEMPORARY register
2629 * channels for copy propagation and updates following instructions to
2630 * use the original versions.
2631 *
2632 * The ir_to_mesa_visitor lazily produces code assuming that this pass
2633 * will occur. As an example, a TXP production before this pass:
2634 *
2635 * 0: MOV TEMP[1], INPUT[4].xyyy;
2636 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2637 * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
2638 *
2639 * and after:
2640 *
2641 * 0: MOV TEMP[1], INPUT[4].xyyy;
2642 * 1: MOV TEMP[1].w, INPUT[4].wwww;
2643 * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
2644 *
2645 * which allows for dead code elimination on TEMP[1]'s writes.
2646 */
2647 void
2648 ir_to_mesa_visitor::copy_propagate(void)
2649 {
2650 ir_to_mesa_instruction **acp = talloc_zero_array(mem_ctx,
2651 ir_to_mesa_instruction *,
2652 this->next_temp * 4);
2653
2654 foreach_iter(exec_list_iterator, iter, this->instructions) {
2655 ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2656
2657 assert(inst->dst_reg.file != PROGRAM_TEMPORARY
2658 || inst->dst_reg.index < this->next_temp);
2659
2660 /* First, do any copy propagation possible into the src regs. */
2661 for (int r = 0; r < 3; r++) {
2662 ir_to_mesa_instruction *first = NULL;
2663 bool good = true;
2664 int acp_base = inst->src_reg[r].index * 4;
2665
2666 if (inst->src_reg[r].file != PROGRAM_TEMPORARY ||
2667 inst->src_reg[r].reladdr)
2668 continue;
2669
2670 /* See if we can find entries in the ACP consisting of MOVs
2671 * from the same src register for all the swizzled channels
2672 * of this src register reference.
2673 */
2674 for (int i = 0; i < 4; i++) {
2675 int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
2676 ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
2677
2678 if (!copy_chan) {
2679 good = false;
2680 break;
2681 }
2682
2683 if (!first) {
2684 first = copy_chan;
2685 } else {
2686 if (first->src_reg[0].file != copy_chan->src_reg[0].file ||
2687 first->src_reg[0].index != copy_chan->src_reg[0].index) {
2688 good = false;
2689 break;
2690 }
2691 }
2692 }
2693
2694 if (good) {
2695 /* We've now validated that we can copy-propagate to
2696 * replace this src register reference. Do it.
2697 */
2698 inst->src_reg[r].file = first->src_reg[0].file;
2699 inst->src_reg[r].index = first->src_reg[0].index;
2700
2701 int swizzle = 0;
2702 for (int i = 0; i < 4; i++) {
2703 int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
2704 ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
2705 swizzle |= (GET_SWZ(copy_inst->src_reg[0].swizzle, src_chan) <<
2706 (3 * i));
2707 }
2708 inst->src_reg[r].swizzle = swizzle;
2709 }
2710 }
2711
2712 switch (inst->op) {
2713 case OPCODE_BGNLOOP:
2714 case OPCODE_ENDLOOP:
2715 case OPCODE_ELSE:
2716 case OPCODE_ENDIF:
2717 /* End of a basic block, clear the ACP entirely. */
2718 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2719 break;
2720
2721 default:
2722 /* Continuing the block, clear any written channels from
2723 * the ACP.
2724 */
2725 if (inst->dst_reg.file == PROGRAM_TEMPORARY) {
2726 if (inst->dst_reg.reladdr) {
2727 memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
2728 } else {
2729 for (int i = 0; i < 4; i++) {
2730 if (inst->dst_reg.writemask & (1 << i)) {
2731 acp[4 * inst->dst_reg.index + i] = NULL;
2732 }
2733 }
2734 }
2735 }
2736 break;
2737 }
2738
2739 /* If this is a copy, add it to the ACP. */
2740 if (inst->op == OPCODE_MOV &&
2741 inst->dst_reg.file == PROGRAM_TEMPORARY &&
2742 !inst->dst_reg.reladdr &&
2743 !inst->saturate &&
2744 !inst->src_reg[0].reladdr &&
2745 !inst->src_reg[0].negate) {
2746 for (int i = 0; i < 4; i++) {
2747 if (inst->dst_reg.writemask & (1 << i)) {
2748 acp[4 * inst->dst_reg.index + i] = inst;
2749 }
2750 }
2751 }
2752 }
2753
2754 talloc_free(acp);
2755 }
2756
2757
2758 /**
2759 * Convert a shader's GLSL IR into a Mesa gl_program.
2760 */
2761 static struct gl_program *
2762 get_mesa_program(struct gl_context *ctx,
2763 struct gl_shader_program *shader_program,
2764 struct gl_shader *shader)
2765 {
2766 ir_to_mesa_visitor v;
2767 struct prog_instruction *mesa_instructions, *mesa_inst;
2768 ir_instruction **mesa_instruction_annotation;
2769 int i;
2770 struct gl_program *prog;
2771 GLenum target;
2772 const char *target_string;
2773 GLboolean progress;
2774 struct gl_shader_compiler_options *options =
2775 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
2776
2777 switch (shader->Type) {
2778 case GL_VERTEX_SHADER:
2779 target = GL_VERTEX_PROGRAM_ARB;
2780 target_string = "vertex";
2781 break;
2782 case GL_FRAGMENT_SHADER:
2783 target = GL_FRAGMENT_PROGRAM_ARB;
2784 target_string = "fragment";
2785 break;
2786 case GL_GEOMETRY_SHADER:
2787 target = GL_GEOMETRY_PROGRAM_NV;
2788 target_string = "geometry";
2789 break;
2790 default:
2791 assert(!"should not be reached");
2792 return NULL;
2793 }
2794
2795 validate_ir_tree(shader->ir);
2796
2797 prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
2798 if (!prog)
2799 return NULL;
2800 prog->Parameters = _mesa_new_parameter_list();
2801 prog->Varying = _mesa_new_parameter_list();
2802 prog->Attributes = _mesa_new_parameter_list();
2803 v.ctx = ctx;
2804 v.prog = prog;
2805 v.shader_program = shader_program;
2806 v.options = options;
2807
2808 add_uniforms_to_parameters_list(shader_program, shader, prog);
2809
2810 /* Emit Mesa IR for main(). */
2811 visit_exec_list(shader->ir, &v);
2812 v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
2813
2814 /* Now emit bodies for any functions that were used. */
2815 do {
2816 progress = GL_FALSE;
2817
2818 foreach_iter(exec_list_iterator, iter, v.function_signatures) {
2819 function_entry *entry = (function_entry *)iter.get();
2820
2821 if (!entry->bgn_inst) {
2822 v.current_function = entry;
2823
2824 entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
2825 entry->bgn_inst->function = entry;
2826
2827 visit_exec_list(&entry->sig->body, &v);
2828
2829 ir_to_mesa_instruction *last;
2830 last = (ir_to_mesa_instruction *)v.instructions.get_tail();
2831 if (last->op != OPCODE_RET)
2832 v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
2833
2834 ir_to_mesa_instruction *end;
2835 end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
2836 end->function = entry;
2837
2838 progress = GL_TRUE;
2839 }
2840 }
2841 } while (progress);
2842
2843 prog->NumTemporaries = v.next_temp;
2844
2845 int num_instructions = 0;
2846 foreach_iter(exec_list_iterator, iter, v.instructions) {
2847 num_instructions++;
2848 }
2849
2850 mesa_instructions =
2851 (struct prog_instruction *)calloc(num_instructions,
2852 sizeof(*mesa_instructions));
2853 mesa_instruction_annotation = talloc_array(v.mem_ctx, ir_instruction *,
2854 num_instructions);
2855
2856 v.copy_propagate();
2857
2858 /* Convert ir_mesa_instructions into prog_instructions.
2859 */
2860 mesa_inst = mesa_instructions;
2861 i = 0;
2862 foreach_iter(exec_list_iterator, iter, v.instructions) {
2863 const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
2864
2865 mesa_inst->Opcode = inst->op;
2866 mesa_inst->CondUpdate = inst->cond_update;
2867 if (inst->saturate)
2868 mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
2869 mesa_inst->DstReg.File = inst->dst_reg.file;
2870 mesa_inst->DstReg.Index = inst->dst_reg.index;
2871 mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
2872 mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
2873 mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
2874 mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
2875 mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
2876 mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
2877 mesa_inst->TexSrcUnit = inst->sampler;
2878 mesa_inst->TexSrcTarget = inst->tex_target;
2879 mesa_inst->TexShadow = inst->tex_shadow;
2880 mesa_instruction_annotation[i] = inst->ir;
2881
2882 /* Set IndirectRegisterFiles. */
2883 if (mesa_inst->DstReg.RelAddr)
2884 prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
2885
2886 /* Update program's bitmask of indirectly accessed register files */
2887 for (unsigned src = 0; src < 3; src++)
2888 if (mesa_inst->SrcReg[src].RelAddr)
2889 prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
2890
2891 if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
2892 fail_link(shader_program, "Couldn't flatten if statement\n");
2893 }
2894
2895 switch (mesa_inst->Opcode) {
2896 case OPCODE_BGNSUB:
2897 inst->function->inst = i;
2898 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2899 break;
2900 case OPCODE_ENDSUB:
2901 mesa_inst->Comment = strdup(inst->function->sig->function_name());
2902 break;
2903 case OPCODE_CAL:
2904 mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
2905 break;
2906 case OPCODE_ARL:
2907 prog->NumAddressRegs = 1;
2908 break;
2909 default:
2910 break;
2911 }
2912
2913 mesa_inst++;
2914 i++;
2915
2916 if (!shader_program->LinkStatus)
2917 break;
2918 }
2919
2920 if (!shader_program->LinkStatus) {
2921 free(mesa_instructions);
2922 _mesa_reference_program(ctx, &shader->Program, NULL);
2923 return NULL;
2924 }
2925
2926 set_branchtargets(&v, mesa_instructions, num_instructions);
2927
2928 if (ctx->Shader.Flags & GLSL_DUMP) {
2929 printf("\n");
2930 printf("GLSL IR for linked %s program %d:\n", target_string,
2931 shader_program->Name);
2932 _mesa_print_ir(shader->ir, NULL);
2933 printf("\n");
2934 printf("\n");
2935 printf("Mesa IR for linked %s program %d:\n", target_string,
2936 shader_program->Name);
2937 print_program(mesa_instructions, mesa_instruction_annotation,
2938 num_instructions);
2939 }
2940
2941 prog->Instructions = mesa_instructions;
2942 prog->NumInstructions = num_instructions;
2943
2944 do_set_program_inouts(shader->ir, prog);
2945 count_resources(prog);
2946
2947 _mesa_reference_program(ctx, &shader->Program, prog);
2948
2949 if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
2950 _mesa_optimize_program(ctx, prog);
2951 }
2952
2953 return prog;
2954 }
2955
2956 extern "C" {
2957
2958 /**
2959 * Called via ctx->Driver.CompilerShader().
2960 * This is a no-op.
2961 * XXX can we remove the ctx->Driver.CompileShader() hook?
2962 */
2963 GLboolean
2964 _mesa_ir_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
2965 {
2966 assert(shader->CompileStatus);
2967 (void) ctx;
2968
2969 return GL_TRUE;
2970 }
2971
2972
2973 /**
2974 * Link a shader.
2975 * Called via ctx->Driver.LinkShader()
2976 * This actually involves converting GLSL IR into Mesa gl_programs with
2977 * code lowering and other optimizations.
2978 */
2979 GLboolean
2980 _mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
2981 {
2982 assert(prog->LinkStatus);
2983
2984 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2985 if (prog->_LinkedShaders[i] == NULL)
2986 continue;
2987
2988 bool progress;
2989 exec_list *ir = prog->_LinkedShaders[i]->ir;
2990 const struct gl_shader_compiler_options *options =
2991 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
2992
2993 do {
2994 progress = false;
2995
2996 /* Lowering */
2997 do_mat_op_to_vec(ir);
2998 lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
2999 | LOG_TO_LOG2
3000 | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
3001
3002 progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
3003
3004 progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
3005
3006 progress = lower_quadop_vector(ir, true) || progress;
3007
3008 if (options->EmitNoIfs) {
3009 progress = lower_discard(ir) || progress;
3010 progress = lower_if_to_cond_assign(ir) || progress;
3011 }
3012
3013 if (options->EmitNoNoise)
3014 progress = lower_noise(ir) || progress;
3015
3016 /* If there are forms of indirect addressing that the driver
3017 * cannot handle, perform the lowering pass.
3018 */
3019 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
3020 || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
3021 progress =
3022 lower_variable_index_to_cond_assign(ir,
3023 options->EmitNoIndirectInput,
3024 options->EmitNoIndirectOutput,
3025 options->EmitNoIndirectTemp,
3026 options->EmitNoIndirectUniform)
3027 || progress;
3028
3029 progress = do_vec_index_to_cond_assign(ir) || progress;
3030 } while (progress);
3031
3032 validate_ir_tree(ir);
3033 }
3034
3035 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
3036 struct gl_program *linked_prog;
3037
3038 if (prog->_LinkedShaders[i] == NULL)
3039 continue;
3040
3041 linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
3042
3043 if (linked_prog) {
3044 bool ok = true;
3045
3046 switch (prog->_LinkedShaders[i]->Type) {
3047 case GL_VERTEX_SHADER:
3048 _mesa_reference_vertprog(ctx, &prog->VertexProgram,
3049 (struct gl_vertex_program *)linked_prog);
3050 ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
3051 linked_prog);
3052 break;
3053 case GL_FRAGMENT_SHADER:
3054 _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
3055 (struct gl_fragment_program *)linked_prog);
3056 ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
3057 linked_prog);
3058 break;
3059 case GL_GEOMETRY_SHADER:
3060 _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
3061 (struct gl_geometry_program *)linked_prog);
3062 ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
3063 linked_prog);
3064 break;
3065 }
3066 if (!ok) {
3067 return GL_FALSE;
3068 }
3069 }
3070
3071 _mesa_reference_program(ctx, &linked_prog, NULL);
3072 }
3073
3074 return GL_TRUE;
3075 }
3076
3077
3078 /**
3079 * Compile a GLSL shader. Called via glCompileShader().
3080 */
3081 void
3082 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
3083 {
3084 struct _mesa_glsl_parse_state *state =
3085 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
3086
3087 const char *source = shader->Source;
3088 /* Check if the user called glCompileShader without first calling
3089 * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
3090 */
3091 if (source == NULL) {
3092 shader->CompileStatus = GL_FALSE;
3093 return;
3094 }
3095
3096 state->error = preprocess(state, &source, &state->info_log,
3097 &ctx->Extensions, ctx->API);
3098
3099 if (ctx->Shader.Flags & GLSL_DUMP) {
3100 printf("GLSL source for shader %d:\n", shader->Name);
3101 printf("%s\n", shader->Source);
3102 }
3103
3104 if (!state->error) {
3105 _mesa_glsl_lexer_ctor(state, source);
3106 _mesa_glsl_parse(state);
3107 _mesa_glsl_lexer_dtor(state);
3108 }
3109
3110 talloc_free(shader->ir);
3111 shader->ir = new(shader) exec_list;
3112 if (!state->error && !state->translation_unit.is_empty())
3113 _mesa_ast_to_hir(shader->ir, state);
3114
3115 if (!state->error && !shader->ir->is_empty()) {
3116 validate_ir_tree(shader->ir);
3117
3118 /* Do some optimization at compile time to reduce shader IR size
3119 * and reduce later work if the same shader is linked multiple times
3120 */
3121 while (do_common_optimization(shader->ir, false, 32))
3122 ;
3123
3124 validate_ir_tree(shader->ir);
3125 }
3126
3127 shader->symbols = state->symbols;
3128
3129 shader->CompileStatus = !state->error;
3130 shader->InfoLog = state->info_log;
3131 shader->Version = state->language_version;
3132 memcpy(shader->builtins_to_link, state->builtins_to_link,
3133 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
3134 shader->num_builtins_to_link = state->num_builtins_to_link;
3135
3136 if (ctx->Shader.Flags & GLSL_LOG) {
3137 _mesa_write_shader_to_file(shader);
3138 }
3139
3140 if (ctx->Shader.Flags & GLSL_DUMP) {
3141 if (shader->CompileStatus) {
3142 printf("GLSL IR for shader %d:\n", shader->Name);
3143 _mesa_print_ir(shader->ir, NULL);
3144 printf("\n\n");
3145 } else {
3146 printf("GLSL shader %d failed to compile.\n", shader->Name);
3147 }
3148 if (shader->InfoLog && shader->InfoLog[0] != 0) {
3149 printf("GLSL shader %d info log:\n", shader->Name);
3150 printf("%s\n", shader->InfoLog);
3151 }
3152 }
3153
3154 /* Retain any live IR, but trash the rest. */
3155 reparent_ir(shader->ir, shader->ir);
3156
3157 talloc_free(state);
3158
3159 if (shader->CompileStatus) {
3160 if (!ctx->Driver.CompileShader(ctx, shader))
3161 shader->CompileStatus = GL_FALSE;
3162 }
3163 }
3164
3165
3166 /**
3167 * Link a GLSL shader program. Called via glLinkProgram().
3168 */
3169 void
3170 _mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
3171 {
3172 unsigned int i;
3173
3174 _mesa_clear_shader_program_data(ctx, prog);
3175
3176 prog->LinkStatus = GL_TRUE;
3177
3178 for (i = 0; i < prog->NumShaders; i++) {
3179 if (!prog->Shaders[i]->CompileStatus) {
3180 fail_link(prog, "linking with uncompiled shader");
3181 prog->LinkStatus = GL_FALSE;
3182 }
3183 }
3184
3185 prog->Varying = _mesa_new_parameter_list();
3186 _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
3187 _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
3188 _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
3189
3190 if (prog->LinkStatus) {
3191 link_shaders(ctx, prog);
3192 }
3193
3194 if (prog->LinkStatus) {
3195 if (!ctx->Driver.LinkShader(ctx, prog)) {
3196 prog->LinkStatus = GL_FALSE;
3197 }
3198 }
3199
3200 set_uniform_initializers(ctx, prog);
3201
3202 if (ctx->Shader.Flags & GLSL_DUMP) {
3203 if (!prog->LinkStatus) {
3204 printf("GLSL shader program %d failed to link\n", prog->Name);
3205 }
3206
3207 if (prog->InfoLog && prog->InfoLog[0] != 0) {
3208 printf("GLSL shader program %d info log:\n", prog->Name);
3209 printf("%s\n", prog->InfoLog);
3210 }
3211 }
3212 }
3213
3214 } /* extern "C" */