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