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