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