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