program: Remove RelAddr2 support.
[mesa.git] / src / mesa / program / prog_optimize.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
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 shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * VMWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
20 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24
25
26 #include "main/glheader.h"
27 #include "main/context.h"
28 #include "main/macros.h"
29 #include "program.h"
30 #include "prog_instruction.h"
31 #include "prog_optimize.h"
32 #include "prog_print.h"
33
34
35 #define MAX_LOOP_NESTING 50
36 /* MAX_PROGRAM_TEMPS is a low number (256), and we want to be able to
37 * register allocate many temporary values into that small number of
38 * temps. So allow large temporary indices coming into the register
39 * allocator.
40 */
41 #define REG_ALLOCATE_MAX_PROGRAM_TEMPS ((1 << INST_INDEX_BITS) - 1)
42
43 static GLboolean dbg = GL_FALSE;
44
45 #define NO_MASK 0xf
46
47 /**
48 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
49 * are read from the given src in this instruction, We also provide
50 * one optional masks which may mask other components in the dst
51 * register
52 */
53 static GLuint
54 get_src_arg_mask(const struct prog_instruction *inst,
55 GLuint arg, GLuint dst_mask)
56 {
57 GLuint read_mask, channel_mask;
58 GLuint comp;
59
60 assert(arg < _mesa_num_inst_src_regs(inst->Opcode));
61
62 /* Form the dst register, find the written channels */
63 if (inst->CondUpdate) {
64 channel_mask = WRITEMASK_XYZW;
65 }
66 else {
67 switch (inst->Opcode) {
68 case OPCODE_MOV:
69 case OPCODE_MIN:
70 case OPCODE_MAX:
71 case OPCODE_ABS:
72 case OPCODE_ADD:
73 case OPCODE_MAD:
74 case OPCODE_MUL:
75 case OPCODE_SUB:
76 case OPCODE_CMP:
77 case OPCODE_FLR:
78 case OPCODE_FRC:
79 case OPCODE_LRP:
80 case OPCODE_SEQ:
81 case OPCODE_SGE:
82 case OPCODE_SGT:
83 case OPCODE_SLE:
84 case OPCODE_SLT:
85 case OPCODE_SNE:
86 case OPCODE_SSG:
87 channel_mask = inst->DstReg.WriteMask & dst_mask;
88 break;
89 case OPCODE_RCP:
90 case OPCODE_SIN:
91 case OPCODE_COS:
92 case OPCODE_RSQ:
93 case OPCODE_POW:
94 case OPCODE_EX2:
95 case OPCODE_LOG:
96 channel_mask = WRITEMASK_X;
97 break;
98 case OPCODE_DP2:
99 channel_mask = WRITEMASK_XY;
100 break;
101 case OPCODE_DP3:
102 case OPCODE_XPD:
103 channel_mask = WRITEMASK_XYZ;
104 break;
105 default:
106 channel_mask = WRITEMASK_XYZW;
107 break;
108 }
109 }
110
111 /* Now, given the src swizzle and the written channels, find which
112 * components are actually read
113 */
114 read_mask = 0x0;
115 for (comp = 0; comp < 4; ++comp) {
116 const GLuint coord = GET_SWZ(inst->SrcReg[arg].Swizzle, comp);
117 if (channel_mask & (1 << comp) && coord <= SWIZZLE_W)
118 read_mask |= 1 << coord;
119 }
120
121 return read_mask;
122 }
123
124
125 /**
126 * For a MOV instruction, compute a write mask when src register also has
127 * a mask
128 */
129 static GLuint
130 get_dst_mask_for_mov(const struct prog_instruction *mov, GLuint src_mask)
131 {
132 const GLuint mask = mov->DstReg.WriteMask;
133 GLuint comp;
134 GLuint updated_mask = 0x0;
135
136 assert(mov->Opcode == OPCODE_MOV);
137
138 for (comp = 0; comp < 4; ++comp) {
139 GLuint src_comp;
140 if ((mask & (1 << comp)) == 0)
141 continue;
142 src_comp = GET_SWZ(mov->SrcReg[0].Swizzle, comp);
143 if ((src_mask & (1 << src_comp)) == 0)
144 continue;
145 updated_mask |= 1 << comp;
146 }
147
148 return updated_mask;
149 }
150
151
152 /**
153 * Ensure that the swizzle is regular. That is, all of the swizzle
154 * terms are SWIZZLE_X,Y,Z,W and not SWIZZLE_ZERO or SWIZZLE_ONE.
155 */
156 static GLboolean
157 is_swizzle_regular(GLuint swz)
158 {
159 return GET_SWZ(swz,0) <= SWIZZLE_W &&
160 GET_SWZ(swz,1) <= SWIZZLE_W &&
161 GET_SWZ(swz,2) <= SWIZZLE_W &&
162 GET_SWZ(swz,3) <= SWIZZLE_W;
163 }
164
165
166 /**
167 * In 'prog' remove instruction[i] if removeFlags[i] == TRUE.
168 * \return number of instructions removed
169 */
170 static GLuint
171 remove_instructions(struct gl_program *prog, const GLboolean *removeFlags)
172 {
173 GLint i, removeEnd = 0, removeCount = 0;
174 GLuint totalRemoved = 0;
175
176 /* go backward */
177 for (i = prog->NumInstructions - 1; i >= 0; i--) {
178 if (removeFlags[i]) {
179 totalRemoved++;
180 if (removeCount == 0) {
181 /* begin a run of instructions to remove */
182 removeEnd = i;
183 removeCount = 1;
184 }
185 else {
186 /* extend the run of instructions to remove */
187 removeCount++;
188 }
189 }
190 else {
191 /* don't remove this instruction, but check if the preceeding
192 * instructions are to be removed.
193 */
194 if (removeCount > 0) {
195 GLint removeStart = removeEnd - removeCount + 1;
196 _mesa_delete_instructions(prog, removeStart, removeCount);
197 removeStart = removeCount = 0; /* reset removal info */
198 }
199 }
200 }
201 /* Finish removing if the first instruction was to be removed. */
202 if (removeCount > 0) {
203 GLint removeStart = removeEnd - removeCount + 1;
204 _mesa_delete_instructions(prog, removeStart, removeCount);
205 }
206 return totalRemoved;
207 }
208
209
210 /**
211 * Remap register indexes according to map.
212 * \param prog the program to search/replace
213 * \param file the type of register file to search/replace
214 * \param map maps old register indexes to new indexes
215 */
216 static void
217 replace_regs(struct gl_program *prog, gl_register_file file, const GLint map[])
218 {
219 GLuint i;
220
221 for (i = 0; i < prog->NumInstructions; i++) {
222 struct prog_instruction *inst = prog->Instructions + i;
223 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
224 GLuint j;
225 for (j = 0; j < numSrc; j++) {
226 if (inst->SrcReg[j].File == file) {
227 GLuint index = inst->SrcReg[j].Index;
228 assert(map[index] >= 0);
229 inst->SrcReg[j].Index = map[index];
230 }
231 }
232 if (inst->DstReg.File == file) {
233 const GLuint index = inst->DstReg.Index;
234 assert(map[index] >= 0);
235 inst->DstReg.Index = map[index];
236 }
237 }
238 }
239
240
241 /**
242 * Remove dead instructions from the given program.
243 * This is very primitive for now. Basically look for temp registers
244 * that are written to but never read. Remove any instructions that
245 * write to such registers. Be careful with condition code setters.
246 */
247 static GLboolean
248 _mesa_remove_dead_code_global(struct gl_program *prog)
249 {
250 GLboolean tempRead[REG_ALLOCATE_MAX_PROGRAM_TEMPS][4];
251 GLboolean *removeInst; /* per-instruction removal flag */
252 GLuint i, rem = 0, comp;
253
254 memset(tempRead, 0, sizeof(tempRead));
255
256 if (dbg) {
257 printf("Optimize: Begin dead code removal\n");
258 /*_mesa_print_program(prog);*/
259 }
260
261 removeInst =
262 calloc(prog->NumInstructions, sizeof(GLboolean));
263
264 /* Determine which temps are read and written */
265 for (i = 0; i < prog->NumInstructions; i++) {
266 const struct prog_instruction *inst = prog->Instructions + i;
267 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
268 GLuint j;
269
270 /* check src regs */
271 for (j = 0; j < numSrc; j++) {
272 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
273 const GLuint index = inst->SrcReg[j].Index;
274 GLuint read_mask;
275 assert(index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
276 read_mask = get_src_arg_mask(inst, j, NO_MASK);
277
278 if (inst->SrcReg[j].RelAddr) {
279 if (dbg)
280 printf("abort remove dead code (indirect temp)\n");
281 goto done;
282 }
283
284 for (comp = 0; comp < 4; comp++) {
285 const GLuint swz = GET_SWZ(inst->SrcReg[j].Swizzle, comp);
286 if (swz <= SWIZZLE_W) {
287 if ((read_mask & (1 << swz)) == 0)
288 continue;
289 tempRead[index][swz] = GL_TRUE;
290 }
291 }
292 }
293 }
294
295 /* check dst reg */
296 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
297 const GLuint index = inst->DstReg.Index;
298 assert(index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
299
300 if (inst->DstReg.RelAddr) {
301 if (dbg)
302 printf("abort remove dead code (indirect temp)\n");
303 goto done;
304 }
305
306 if (inst->CondUpdate) {
307 /* If we're writing to this register and setting condition
308 * codes we cannot remove the instruction. Prevent removal
309 * by setting the 'read' flag.
310 */
311 tempRead[index][0] = GL_TRUE;
312 tempRead[index][1] = GL_TRUE;
313 tempRead[index][2] = GL_TRUE;
314 tempRead[index][3] = GL_TRUE;
315 }
316 }
317 }
318
319 /* find instructions that write to dead registers, flag for removal */
320 for (i = 0; i < prog->NumInstructions; i++) {
321 struct prog_instruction *inst = prog->Instructions + i;
322 const GLuint numDst = _mesa_num_inst_dst_regs(inst->Opcode);
323
324 if (numDst != 0 && inst->DstReg.File == PROGRAM_TEMPORARY) {
325 GLint chan, index = inst->DstReg.Index;
326
327 for (chan = 0; chan < 4; chan++) {
328 if (!tempRead[index][chan] &&
329 inst->DstReg.WriteMask & (1 << chan)) {
330 if (dbg) {
331 printf("Remove writemask on %u.%c\n", i,
332 chan == 3 ? 'w' : 'x' + chan);
333 }
334 inst->DstReg.WriteMask &= ~(1 << chan);
335 rem++;
336 }
337 }
338
339 if (inst->DstReg.WriteMask == 0) {
340 /* If we cleared all writes, the instruction can be removed. */
341 if (dbg)
342 printf("Remove instruction %u: \n", i);
343 removeInst[i] = GL_TRUE;
344 }
345 }
346 }
347
348 /* now remove the instructions which aren't needed */
349 rem = remove_instructions(prog, removeInst);
350
351 if (dbg) {
352 printf("Optimize: End dead code removal.\n");
353 printf(" %u channel writes removed\n", rem);
354 printf(" %u instructions removed\n", rem);
355 /*_mesa_print_program(prog);*/
356 }
357
358 done:
359 free(removeInst);
360 return rem != 0;
361 }
362
363
364 enum inst_use
365 {
366 READ,
367 WRITE,
368 FLOW,
369 END
370 };
371
372
373 /**
374 * Scan forward in program from 'start' for the next occurances of TEMP[index].
375 * We look if an instruction reads the component given by the masks and if they
376 * are overwritten.
377 * Return READ, WRITE, FLOW or END to indicate the next usage or an indicator
378 * that we can't look further.
379 */
380 static enum inst_use
381 find_next_use(const struct gl_program *prog,
382 GLuint start,
383 GLuint index,
384 GLuint mask)
385 {
386 GLuint i;
387
388 for (i = start; i < prog->NumInstructions; i++) {
389 const struct prog_instruction *inst = prog->Instructions + i;
390 switch (inst->Opcode) {
391 case OPCODE_BGNLOOP:
392 case OPCODE_BGNSUB:
393 case OPCODE_CAL:
394 case OPCODE_CONT:
395 case OPCODE_IF:
396 case OPCODE_ELSE:
397 case OPCODE_ENDIF:
398 case OPCODE_ENDLOOP:
399 case OPCODE_ENDSUB:
400 case OPCODE_RET:
401 return FLOW;
402 case OPCODE_END:
403 return END;
404 default:
405 {
406 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
407 GLuint j;
408 for (j = 0; j < numSrc; j++) {
409 if (inst->SrcReg[j].RelAddr ||
410 (inst->SrcReg[j].File == PROGRAM_TEMPORARY &&
411 inst->SrcReg[j].Index == (GLint)index &&
412 (get_src_arg_mask(inst,j,NO_MASK) & mask)))
413 return READ;
414 }
415 if (_mesa_num_inst_dst_regs(inst->Opcode) == 1 &&
416 inst->DstReg.File == PROGRAM_TEMPORARY &&
417 inst->DstReg.Index == index) {
418 mask &= ~inst->DstReg.WriteMask;
419 if (mask == 0)
420 return WRITE;
421 }
422 }
423 }
424 }
425 return END;
426 }
427
428
429 /**
430 * Is the given instruction opcode a flow-control opcode?
431 * XXX maybe move this into prog_instruction.[ch]
432 */
433 static GLboolean
434 _mesa_is_flow_control_opcode(enum prog_opcode opcode)
435 {
436 switch (opcode) {
437 case OPCODE_BGNLOOP:
438 case OPCODE_BGNSUB:
439 case OPCODE_CAL:
440 case OPCODE_CONT:
441 case OPCODE_IF:
442 case OPCODE_ELSE:
443 case OPCODE_END:
444 case OPCODE_ENDIF:
445 case OPCODE_ENDLOOP:
446 case OPCODE_ENDSUB:
447 case OPCODE_RET:
448 return GL_TRUE;
449 default:
450 return GL_FALSE;
451 }
452 }
453
454
455 /**
456 * Test if the given instruction is a simple MOV (no conditional updating,
457 * not relative addressing, no negation/abs, etc).
458 */
459 static GLboolean
460 can_downward_mov_be_modifed(const struct prog_instruction *mov)
461 {
462 return
463 mov->Opcode == OPCODE_MOV &&
464 mov->CondUpdate == GL_FALSE &&
465 mov->SrcReg[0].RelAddr == 0 &&
466 mov->SrcReg[0].Negate == 0 &&
467 mov->SrcReg[0].Abs == 0 &&
468 mov->DstReg.RelAddr == 0 &&
469 mov->DstReg.CondMask == COND_TR;
470 }
471
472
473 static GLboolean
474 can_upward_mov_be_modifed(const struct prog_instruction *mov)
475 {
476 return
477 can_downward_mov_be_modifed(mov) &&
478 mov->DstReg.File == PROGRAM_TEMPORARY &&
479 !mov->Saturate;
480 }
481
482
483 /**
484 * Try to remove use of extraneous MOV instructions, to free them up for dead
485 * code removal.
486 */
487 static void
488 _mesa_remove_extra_move_use(struct gl_program *prog)
489 {
490 GLuint i, j;
491
492 if (dbg) {
493 printf("Optimize: Begin remove extra move use\n");
494 _mesa_print_program(prog);
495 }
496
497 /*
498 * Look for sequences such as this:
499 * MOV tmpX, arg0;
500 * ...
501 * FOO tmpY, tmpX, arg1;
502 * and convert into:
503 * MOV tmpX, arg0;
504 * ...
505 * FOO tmpY, arg0, arg1;
506 */
507
508 for (i = 0; i + 1 < prog->NumInstructions; i++) {
509 const struct prog_instruction *mov = prog->Instructions + i;
510 GLuint dst_mask, src_mask;
511 if (can_upward_mov_be_modifed(mov) == GL_FALSE)
512 continue;
513
514 /* Scanning the code, we maintain the components which are still active in
515 * these two masks
516 */
517 dst_mask = mov->DstReg.WriteMask;
518 src_mask = get_src_arg_mask(mov, 0, NO_MASK);
519
520 /* Walk through remaining instructions until the or src reg gets
521 * rewritten or we get into some flow-control, eliminating the use of
522 * this MOV.
523 */
524 for (j = i + 1; j < prog->NumInstructions; j++) {
525 struct prog_instruction *inst2 = prog->Instructions + j;
526 GLuint arg;
527
528 if (_mesa_is_flow_control_opcode(inst2->Opcode))
529 break;
530
531 /* First rewrite this instruction's args if appropriate. */
532 for (arg = 0; arg < _mesa_num_inst_src_regs(inst2->Opcode); arg++) {
533 GLuint comp, read_mask;
534
535 if (inst2->SrcReg[arg].File != mov->DstReg.File ||
536 inst2->SrcReg[arg].Index != mov->DstReg.Index ||
537 inst2->SrcReg[arg].RelAddr ||
538 inst2->SrcReg[arg].Abs)
539 continue;
540 read_mask = get_src_arg_mask(inst2, arg, NO_MASK);
541
542 /* Adjust the swizzles of inst2 to point at MOV's source if ALL the
543 * components read still come from the mov instructions
544 */
545 if (is_swizzle_regular(inst2->SrcReg[arg].Swizzle) &&
546 (read_mask & dst_mask) == read_mask) {
547 for (comp = 0; comp < 4; comp++) {
548 const GLuint inst2_swz =
549 GET_SWZ(inst2->SrcReg[arg].Swizzle, comp);
550 const GLuint s = GET_SWZ(mov->SrcReg[0].Swizzle, inst2_swz);
551 inst2->SrcReg[arg].Swizzle &= ~(7 << (3 * comp));
552 inst2->SrcReg[arg].Swizzle |= s << (3 * comp);
553 inst2->SrcReg[arg].Negate ^= (((mov->SrcReg[0].Negate >>
554 inst2_swz) & 0x1) << comp);
555 }
556 inst2->SrcReg[arg].File = mov->SrcReg[0].File;
557 inst2->SrcReg[arg].Index = mov->SrcReg[0].Index;
558 }
559 }
560
561 /* The source of MOV is written. This potentially deactivates some
562 * components from the src and dst of the MOV instruction
563 */
564 if (inst2->DstReg.File == mov->DstReg.File &&
565 (inst2->DstReg.RelAddr ||
566 inst2->DstReg.Index == mov->DstReg.Index)) {
567 dst_mask &= ~inst2->DstReg.WriteMask;
568 src_mask = get_src_arg_mask(mov, 0, dst_mask);
569 }
570
571 /* Idem when the destination of mov is written */
572 if (inst2->DstReg.File == mov->SrcReg[0].File &&
573 (inst2->DstReg.RelAddr ||
574 inst2->DstReg.Index == mov->SrcReg[0].Index)) {
575 src_mask &= ~inst2->DstReg.WriteMask;
576 dst_mask &= get_dst_mask_for_mov(mov, src_mask);
577 }
578 if (dst_mask == 0)
579 break;
580 }
581 }
582
583 if (dbg) {
584 printf("Optimize: End remove extra move use.\n");
585 /*_mesa_print_program(prog);*/
586 }
587 }
588
589
590 /**
591 * Complements dead_code_global. Try to remove code in block of code by
592 * carefully monitoring the swizzles. Both functions should be merged into one
593 * with a proper control flow graph
594 */
595 static GLboolean
596 _mesa_remove_dead_code_local(struct gl_program *prog)
597 {
598 GLboolean *removeInst;
599 GLuint i, arg, rem = 0;
600
601 removeInst =
602 calloc(prog->NumInstructions, sizeof(GLboolean));
603
604 for (i = 0; i < prog->NumInstructions; i++) {
605 const struct prog_instruction *inst = prog->Instructions + i;
606 const GLuint index = inst->DstReg.Index;
607 const GLuint mask = inst->DstReg.WriteMask;
608 enum inst_use use;
609
610 /* We must deactivate the pass as soon as some indirection is used */
611 if (inst->DstReg.RelAddr)
612 goto done;
613 for (arg = 0; arg < _mesa_num_inst_src_regs(inst->Opcode); arg++)
614 if (inst->SrcReg[arg].RelAddr)
615 goto done;
616
617 if (_mesa_is_flow_control_opcode(inst->Opcode) ||
618 _mesa_num_inst_dst_regs(inst->Opcode) == 0 ||
619 inst->DstReg.File != PROGRAM_TEMPORARY ||
620 inst->DstReg.RelAddr)
621 continue;
622
623 use = find_next_use(prog, i+1, index, mask);
624 if (use == WRITE || use == END)
625 removeInst[i] = GL_TRUE;
626 }
627
628 rem = remove_instructions(prog, removeInst);
629
630 done:
631 free(removeInst);
632 return rem != 0;
633 }
634
635
636 /**
637 * Try to inject the destination of mov as the destination of inst and recompute
638 * the swizzles operators for the sources of inst if required. Return GL_TRUE
639 * of the substitution was possible, GL_FALSE otherwise
640 */
641 static GLboolean
642 _mesa_merge_mov_into_inst(struct prog_instruction *inst,
643 const struct prog_instruction *mov)
644 {
645 /* Indirection table which associates destination and source components for
646 * the mov instruction
647 */
648 const GLuint mask = get_src_arg_mask(mov, 0, NO_MASK);
649
650 /* Some components are not written by inst. We cannot remove the mov */
651 if (mask != (inst->DstReg.WriteMask & mask))
652 return GL_FALSE;
653
654 inst->Saturate |= mov->Saturate;
655
656 /* Depending on the instruction, we may need to recompute the swizzles.
657 * Also, some other instructions (like TEX) are not linear. We will only
658 * consider completely active sources and destinations
659 */
660 switch (inst->Opcode) {
661
662 /* Carstesian instructions: we compute the swizzle */
663 case OPCODE_MOV:
664 case OPCODE_MIN:
665 case OPCODE_MAX:
666 case OPCODE_ABS:
667 case OPCODE_ADD:
668 case OPCODE_MAD:
669 case OPCODE_MUL:
670 case OPCODE_SUB:
671 {
672 GLuint dst_to_src_comp[4] = {0,0,0,0};
673 GLuint dst_comp, arg;
674 for (dst_comp = 0; dst_comp < 4; ++dst_comp) {
675 if (mov->DstReg.WriteMask & (1 << dst_comp)) {
676 const GLuint src_comp = GET_SWZ(mov->SrcReg[0].Swizzle, dst_comp);
677 assert(src_comp < 4);
678 dst_to_src_comp[dst_comp] = src_comp;
679 }
680 }
681
682 /* Patch each source of the instruction */
683 for (arg = 0; arg < _mesa_num_inst_src_regs(inst->Opcode); arg++) {
684 const GLuint arg_swz = inst->SrcReg[arg].Swizzle;
685 inst->SrcReg[arg].Swizzle = 0;
686
687 /* Reset each active component of the swizzle */
688 for (dst_comp = 0; dst_comp < 4; ++dst_comp) {
689 GLuint src_comp, arg_comp;
690 if ((mov->DstReg.WriteMask & (1 << dst_comp)) == 0)
691 continue;
692 src_comp = dst_to_src_comp[dst_comp];
693 assert(src_comp < 4);
694 arg_comp = GET_SWZ(arg_swz, src_comp);
695 assert(arg_comp < 4);
696 inst->SrcReg[arg].Swizzle |= arg_comp << (3*dst_comp);
697 }
698 }
699 inst->DstReg = mov->DstReg;
700 return GL_TRUE;
701 }
702
703 /* Dot products and scalar instructions: we only change the destination */
704 case OPCODE_RCP:
705 case OPCODE_SIN:
706 case OPCODE_COS:
707 case OPCODE_RSQ:
708 case OPCODE_POW:
709 case OPCODE_EX2:
710 case OPCODE_LOG:
711 case OPCODE_DP2:
712 case OPCODE_DP3:
713 case OPCODE_DP4:
714 inst->DstReg = mov->DstReg;
715 return GL_TRUE;
716
717 /* All other instructions require fully active components with no swizzle */
718 default:
719 if (mov->SrcReg[0].Swizzle != SWIZZLE_XYZW ||
720 inst->DstReg.WriteMask != WRITEMASK_XYZW)
721 return GL_FALSE;
722 inst->DstReg = mov->DstReg;
723 return GL_TRUE;
724 }
725 }
726
727
728 /**
729 * Try to remove extraneous MOV instructions from the given program.
730 */
731 static GLboolean
732 _mesa_remove_extra_moves(struct gl_program *prog)
733 {
734 GLboolean *removeInst; /* per-instruction removal flag */
735 GLuint i, rem = 0, nesting = 0;
736
737 if (dbg) {
738 printf("Optimize: Begin remove extra moves\n");
739 _mesa_print_program(prog);
740 }
741
742 removeInst =
743 calloc(prog->NumInstructions, sizeof(GLboolean));
744
745 /*
746 * Look for sequences such as this:
747 * FOO tmpX, arg0, arg1;
748 * MOV tmpY, tmpX;
749 * and convert into:
750 * FOO tmpY, arg0, arg1;
751 */
752
753 for (i = 0; i < prog->NumInstructions; i++) {
754 const struct prog_instruction *mov = prog->Instructions + i;
755
756 switch (mov->Opcode) {
757 case OPCODE_BGNLOOP:
758 case OPCODE_BGNSUB:
759 case OPCODE_IF:
760 nesting++;
761 break;
762 case OPCODE_ENDLOOP:
763 case OPCODE_ENDSUB:
764 case OPCODE_ENDIF:
765 nesting--;
766 break;
767 case OPCODE_MOV:
768 if (i > 0 &&
769 can_downward_mov_be_modifed(mov) &&
770 mov->SrcReg[0].File == PROGRAM_TEMPORARY &&
771 nesting == 0)
772 {
773
774 /* see if this MOV can be removed */
775 const GLuint id = mov->SrcReg[0].Index;
776 struct prog_instruction *prevInst;
777 GLuint prevI;
778
779 /* get pointer to previous instruction */
780 prevI = i - 1;
781 while (prevI > 0 && removeInst[prevI])
782 prevI--;
783 prevInst = prog->Instructions + prevI;
784
785 if (prevInst->DstReg.File == PROGRAM_TEMPORARY &&
786 prevInst->DstReg.Index == id &&
787 prevInst->DstReg.RelAddr == 0 &&
788 prevInst->DstReg.CondMask == COND_TR) {
789
790 const GLuint dst_mask = prevInst->DstReg.WriteMask;
791 enum inst_use next_use = find_next_use(prog, i+1, id, dst_mask);
792
793 if (next_use == WRITE || next_use == END) {
794 /* OK, we can safely remove this MOV instruction.
795 * Transform:
796 * prevI: FOO tempIndex, x, y;
797 * i: MOV z, tempIndex;
798 * Into:
799 * prevI: FOO z, x, y;
800 */
801 if (_mesa_merge_mov_into_inst(prevInst, mov)) {
802 removeInst[i] = GL_TRUE;
803 if (dbg) {
804 printf("Remove MOV at %u\n", i);
805 printf("new prev inst %u: ", prevI);
806 _mesa_print_instruction(prevInst);
807 }
808 }
809 }
810 }
811 }
812 break;
813 default:
814 ; /* nothing */
815 }
816 }
817
818 /* now remove the instructions which aren't needed */
819 rem = remove_instructions(prog, removeInst);
820
821 free(removeInst);
822
823 if (dbg) {
824 printf("Optimize: End remove extra moves. %u instructions removed\n", rem);
825 /*_mesa_print_program(prog);*/
826 }
827
828 return rem != 0;
829 }
830
831
832 /** A live register interval */
833 struct interval
834 {
835 GLuint Reg; /** The temporary register index */
836 GLuint Start, End; /** Start/end instruction numbers */
837 };
838
839
840 /** A list of register intervals */
841 struct interval_list
842 {
843 GLuint Num;
844 struct interval Intervals[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
845 };
846
847
848 static void
849 append_interval(struct interval_list *list, const struct interval *inv)
850 {
851 list->Intervals[list->Num++] = *inv;
852 }
853
854
855 /** Insert interval inv into list, sorted by interval end */
856 static void
857 insert_interval_by_end(struct interval_list *list, const struct interval *inv)
858 {
859 /* XXX we could do a binary search insertion here since list is sorted */
860 GLint i = list->Num - 1;
861 while (i >= 0 && list->Intervals[i].End > inv->End) {
862 list->Intervals[i + 1] = list->Intervals[i];
863 i--;
864 }
865 list->Intervals[i + 1] = *inv;
866 list->Num++;
867
868 #ifdef DEBUG
869 {
870 GLuint i;
871 for (i = 0; i + 1 < list->Num; i++) {
872 assert(list->Intervals[i].End <= list->Intervals[i + 1].End);
873 }
874 }
875 #endif
876 }
877
878
879 /** Remove the given interval from the interval list */
880 static void
881 remove_interval(struct interval_list *list, const struct interval *inv)
882 {
883 /* XXX we could binary search since list is sorted */
884 GLuint k;
885 for (k = 0; k < list->Num; k++) {
886 if (list->Intervals[k].Reg == inv->Reg) {
887 /* found, remove it */
888 assert(list->Intervals[k].Start == inv->Start);
889 assert(list->Intervals[k].End == inv->End);
890 while (k < list->Num - 1) {
891 list->Intervals[k] = list->Intervals[k + 1];
892 k++;
893 }
894 list->Num--;
895 return;
896 }
897 }
898 }
899
900
901 /** called by qsort() */
902 static int
903 compare_start(const void *a, const void *b)
904 {
905 const struct interval *ia = (const struct interval *) a;
906 const struct interval *ib = (const struct interval *) b;
907 if (ia->Start < ib->Start)
908 return -1;
909 else if (ia->Start > ib->Start)
910 return +1;
911 else
912 return 0;
913 }
914
915
916 /** sort the interval list according to interval starts */
917 static void
918 sort_interval_list_by_start(struct interval_list *list)
919 {
920 qsort(list->Intervals, list->Num, sizeof(struct interval), compare_start);
921 #ifdef DEBUG
922 {
923 GLuint i;
924 for (i = 0; i + 1 < list->Num; i++) {
925 assert(list->Intervals[i].Start <= list->Intervals[i + 1].Start);
926 }
927 }
928 #endif
929 }
930
931 struct loop_info
932 {
933 GLuint Start, End; /**< Start, end instructions of loop */
934 };
935
936 /**
937 * Update the intermediate interval info for register 'index' and
938 * instruction 'ic'.
939 */
940 static void
941 update_interval(GLint intBegin[], GLint intEnd[],
942 struct loop_info *loopStack, GLuint loopStackDepth,
943 GLuint index, GLuint ic)
944 {
945 unsigned i;
946 GLuint begin = ic;
947 GLuint end = ic;
948
949 /* If the register is used in a loop, extend its lifetime through the end
950 * of the outermost loop that doesn't contain its definition.
951 */
952 for (i = 0; i < loopStackDepth; i++) {
953 if (intBegin[index] < loopStack[i].Start) {
954 end = loopStack[i].End;
955 break;
956 }
957 }
958
959 /* Variables that are live at the end of a loop will also be live at the
960 * beginning, so an instruction inside of a loop should have its live
961 * interval begin at the start of the outermost loop.
962 */
963 if (loopStackDepth > 0 && ic > loopStack[0].Start && ic < loopStack[0].End) {
964 begin = loopStack[0].Start;
965 }
966
967 assert(index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
968 if (intBegin[index] == -1) {
969 assert(intEnd[index] == -1);
970 intBegin[index] = begin;
971 intEnd[index] = end;
972 }
973 else {
974 intEnd[index] = end;
975 }
976 }
977
978
979 /**
980 * Find first/last instruction that references each temporary register.
981 */
982 GLboolean
983 _mesa_find_temp_intervals(const struct prog_instruction *instructions,
984 GLuint numInstructions,
985 GLint intBegin[REG_ALLOCATE_MAX_PROGRAM_TEMPS],
986 GLint intEnd[REG_ALLOCATE_MAX_PROGRAM_TEMPS])
987 {
988 struct loop_info loopStack[MAX_LOOP_NESTING];
989 GLuint loopStackDepth = 0;
990 GLuint i;
991
992 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++){
993 intBegin[i] = intEnd[i] = -1;
994 }
995
996 /* Scan instructions looking for temporary registers */
997 for (i = 0; i < numInstructions; i++) {
998 const struct prog_instruction *inst = instructions + i;
999 if (inst->Opcode == OPCODE_BGNLOOP) {
1000 loopStack[loopStackDepth].Start = i;
1001 loopStack[loopStackDepth].End = inst->BranchTarget;
1002 loopStackDepth++;
1003 }
1004 else if (inst->Opcode == OPCODE_ENDLOOP) {
1005 loopStackDepth--;
1006 }
1007 else if (inst->Opcode == OPCODE_CAL) {
1008 return GL_FALSE;
1009 }
1010 else {
1011 const GLuint numSrc = 3;/*_mesa_num_inst_src_regs(inst->Opcode);*/
1012 GLuint j;
1013 for (j = 0; j < numSrc; j++) {
1014 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
1015 const GLuint index = inst->SrcReg[j].Index;
1016 if (inst->SrcReg[j].RelAddr)
1017 return GL_FALSE;
1018 update_interval(intBegin, intEnd, loopStack, loopStackDepth,
1019 index, i);
1020 }
1021 }
1022 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
1023 const GLuint index = inst->DstReg.Index;
1024 if (inst->DstReg.RelAddr)
1025 return GL_FALSE;
1026 update_interval(intBegin, intEnd, loopStack, loopStackDepth,
1027 index, i);
1028 }
1029 }
1030 }
1031
1032 return GL_TRUE;
1033 }
1034
1035
1036 /**
1037 * Find the live intervals for each temporary register in the program.
1038 * For register R, the interval [A,B] indicates that R is referenced
1039 * from instruction A through instruction B.
1040 * Special consideration is needed for loops and subroutines.
1041 * \return GL_TRUE if success, GL_FALSE if we cannot proceed for some reason
1042 */
1043 static GLboolean
1044 find_live_intervals(struct gl_program *prog,
1045 struct interval_list *liveIntervals)
1046 {
1047 GLint intBegin[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1048 GLint intEnd[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1049 GLuint i;
1050
1051 /*
1052 * Note: we'll return GL_FALSE below if we find relative indexing
1053 * into the TEMP register file. We can't handle that yet.
1054 * We also give up on subroutines for now.
1055 */
1056
1057 if (dbg) {
1058 printf("Optimize: Begin find intervals\n");
1059 }
1060
1061 /* build intermediate arrays */
1062 if (!_mesa_find_temp_intervals(prog->Instructions, prog->NumInstructions,
1063 intBegin, intEnd))
1064 return GL_FALSE;
1065
1066 /* Build live intervals list from intermediate arrays */
1067 liveIntervals->Num = 0;
1068 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++) {
1069 if (intBegin[i] >= 0) {
1070 struct interval inv;
1071 inv.Reg = i;
1072 inv.Start = intBegin[i];
1073 inv.End = intEnd[i];
1074 append_interval(liveIntervals, &inv);
1075 }
1076 }
1077
1078 /* Sort the list according to interval starts */
1079 sort_interval_list_by_start(liveIntervals);
1080
1081 if (dbg) {
1082 /* print interval info */
1083 for (i = 0; i < liveIntervals->Num; i++) {
1084 const struct interval *inv = liveIntervals->Intervals + i;
1085 printf("Reg[%d] live [%d, %d]:",
1086 inv->Reg, inv->Start, inv->End);
1087 if (1) {
1088 GLuint j;
1089 for (j = 0; j < inv->Start; j++)
1090 printf(" ");
1091 for (j = inv->Start; j <= inv->End; j++)
1092 printf("x");
1093 }
1094 printf("\n");
1095 }
1096 }
1097
1098 return GL_TRUE;
1099 }
1100
1101
1102 /** Scan the array of used register flags to find free entry */
1103 static GLint
1104 alloc_register(GLboolean usedRegs[REG_ALLOCATE_MAX_PROGRAM_TEMPS])
1105 {
1106 GLuint k;
1107 for (k = 0; k < REG_ALLOCATE_MAX_PROGRAM_TEMPS; k++) {
1108 if (!usedRegs[k]) {
1109 usedRegs[k] = GL_TRUE;
1110 return k;
1111 }
1112 }
1113 return -1;
1114 }
1115
1116
1117 /**
1118 * This function implements "Linear Scan Register Allocation" to reduce
1119 * the number of temporary registers used by the program.
1120 *
1121 * We compute the "live interval" for all temporary registers then
1122 * examine the overlap of the intervals to allocate new registers.
1123 * Basically, if two intervals do not overlap, they can use the same register.
1124 */
1125 static void
1126 _mesa_reallocate_registers(struct gl_program *prog)
1127 {
1128 struct interval_list liveIntervals;
1129 GLint registerMap[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1130 GLboolean usedRegs[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1131 GLuint i;
1132 GLint maxTemp = -1;
1133
1134 if (dbg) {
1135 printf("Optimize: Begin live-interval register reallocation\n");
1136 _mesa_print_program(prog);
1137 }
1138
1139 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++){
1140 registerMap[i] = -1;
1141 usedRegs[i] = GL_FALSE;
1142 }
1143
1144 if (!find_live_intervals(prog, &liveIntervals)) {
1145 if (dbg)
1146 printf("Aborting register reallocation\n");
1147 return;
1148 }
1149
1150 {
1151 struct interval_list activeIntervals;
1152 activeIntervals.Num = 0;
1153
1154 /* loop over live intervals, allocating a new register for each */
1155 for (i = 0; i < liveIntervals.Num; i++) {
1156 const struct interval *live = liveIntervals.Intervals + i;
1157
1158 if (dbg)
1159 printf("Consider register %u\n", live->Reg);
1160
1161 /* Expire old intervals. Intervals which have ended with respect
1162 * to the live interval can have their remapped registers freed.
1163 */
1164 {
1165 GLint j;
1166 for (j = 0; j < (GLint) activeIntervals.Num; j++) {
1167 const struct interval *inv = activeIntervals.Intervals + j;
1168 if (inv->End >= live->Start) {
1169 /* Stop now. Since the activeInterval list is sorted
1170 * we know we don't have to go further.
1171 */
1172 break;
1173 }
1174 else {
1175 /* Interval 'inv' has expired */
1176 const GLint regNew = registerMap[inv->Reg];
1177 assert(regNew >= 0);
1178
1179 if (dbg)
1180 printf(" expire interval for reg %u\n", inv->Reg);
1181
1182 /* remove interval j from active list */
1183 remove_interval(&activeIntervals, inv);
1184 j--; /* counter-act j++ in for-loop above */
1185
1186 /* return register regNew to the free pool */
1187 if (dbg)
1188 printf(" free reg %d\n", regNew);
1189 assert(usedRegs[regNew] == GL_TRUE);
1190 usedRegs[regNew] = GL_FALSE;
1191 }
1192 }
1193 }
1194
1195 /* find a free register for this live interval */
1196 {
1197 const GLint k = alloc_register(usedRegs);
1198 if (k < 0) {
1199 /* out of registers, give up */
1200 return;
1201 }
1202 registerMap[live->Reg] = k;
1203 maxTemp = MAX2(maxTemp, k);
1204 if (dbg)
1205 printf(" remap register %u -> %d\n", live->Reg, k);
1206 }
1207
1208 /* Insert this live interval into the active list which is sorted
1209 * by increasing end points.
1210 */
1211 insert_interval_by_end(&activeIntervals, live);
1212 }
1213 }
1214
1215 if (maxTemp + 1 < (GLint) liveIntervals.Num) {
1216 /* OK, we've reduced the number of registers needed.
1217 * Scan the program and replace all the old temporary register
1218 * indexes with the new indexes.
1219 */
1220 replace_regs(prog, PROGRAM_TEMPORARY, registerMap);
1221
1222 prog->NumTemporaries = maxTemp + 1;
1223 }
1224
1225 if (dbg) {
1226 printf("Optimize: End live-interval register reallocation\n");
1227 printf("Num temp regs before: %u after: %u\n",
1228 liveIntervals.Num, maxTemp + 1);
1229 _mesa_print_program(prog);
1230 }
1231 }
1232
1233
1234 #if 0
1235 static void
1236 print_it(struct gl_context *ctx, struct gl_program *program, const char *txt) {
1237 fprintf(stderr, "%s (%u inst):\n", txt, program->NumInstructions);
1238 _mesa_print_program(program);
1239 _mesa_print_program_parameters(ctx, program);
1240 fprintf(stderr, "\n\n");
1241 }
1242 #endif
1243
1244 /**
1245 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
1246 * instruction is the first instruction to write to register T0. The are
1247 * several lowering passes done in GLSL IR (e.g. branches and
1248 * relative addressing) that create a large number of conditional assignments
1249 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
1250 *
1251 * Here is why this conversion is safe:
1252 * CMP T0, T1 T2 T0 can be expanded to:
1253 * if (T1 < 0.0)
1254 * MOV T0, T2;
1255 * else
1256 * MOV T0, T0;
1257 *
1258 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
1259 * as the original program. If (T1 < 0.0) evaluates to false, executing
1260 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
1261 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
1262 * because any instruction that was going to read from T0 after this was going
1263 * to read a garbage value anyway.
1264 */
1265 static void
1266 _mesa_simplify_cmp(struct gl_program * program)
1267 {
1268 GLuint tempWrites[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1269 GLuint outputWrites[MAX_PROGRAM_OUTPUTS];
1270 GLuint i;
1271
1272 if (dbg) {
1273 printf("Optimize: Begin reads without writes\n");
1274 _mesa_print_program(program);
1275 }
1276
1277 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++) {
1278 tempWrites[i] = 0;
1279 }
1280
1281 for (i = 0; i < MAX_PROGRAM_OUTPUTS; i++) {
1282 outputWrites[i] = 0;
1283 }
1284
1285 for (i = 0; i < program->NumInstructions; i++) {
1286 struct prog_instruction *inst = program->Instructions + i;
1287 GLuint prevWriteMask;
1288
1289 /* Give up if we encounter relative addressing or flow control. */
1290 if (_mesa_is_flow_control_opcode(inst->Opcode) || inst->DstReg.RelAddr) {
1291 return;
1292 }
1293
1294 if (inst->DstReg.File == PROGRAM_OUTPUT) {
1295 assert(inst->DstReg.Index < MAX_PROGRAM_OUTPUTS);
1296 prevWriteMask = outputWrites[inst->DstReg.Index];
1297 outputWrites[inst->DstReg.Index] |= inst->DstReg.WriteMask;
1298 } else if (inst->DstReg.File == PROGRAM_TEMPORARY) {
1299 assert(inst->DstReg.Index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
1300 prevWriteMask = tempWrites[inst->DstReg.Index];
1301 tempWrites[inst->DstReg.Index] |= inst->DstReg.WriteMask;
1302 } else {
1303 /* No other register type can be a destination register. */
1304 continue;
1305 }
1306
1307 /* For a CMP to be considered a conditional write, the destination
1308 * register and source register two must be the same. */
1309 if (inst->Opcode == OPCODE_CMP
1310 && !(inst->DstReg.WriteMask & prevWriteMask)
1311 && inst->SrcReg[2].File == inst->DstReg.File
1312 && inst->SrcReg[2].Index == inst->DstReg.Index
1313 && inst->DstReg.WriteMask == get_src_arg_mask(inst, 2, NO_MASK)) {
1314
1315 inst->Opcode = OPCODE_MOV;
1316 inst->SrcReg[0] = inst->SrcReg[1];
1317
1318 /* Unused operands are expected to have the file set to
1319 * PROGRAM_UNDEFINED. This is how _mesa_init_instructions initializes
1320 * all of the sources.
1321 */
1322 inst->SrcReg[1].File = PROGRAM_UNDEFINED;
1323 inst->SrcReg[1].Swizzle = SWIZZLE_NOOP;
1324 inst->SrcReg[2].File = PROGRAM_UNDEFINED;
1325 inst->SrcReg[2].Swizzle = SWIZZLE_NOOP;
1326 }
1327 }
1328 if (dbg) {
1329 printf("Optimize: End reads without writes\n");
1330 _mesa_print_program(program);
1331 }
1332 }
1333
1334 /**
1335 * Apply optimizations to the given program to eliminate unnecessary
1336 * instructions, temp regs, etc.
1337 */
1338 void
1339 _mesa_optimize_program(struct gl_context *ctx, struct gl_program *program)
1340 {
1341 GLboolean any_change;
1342
1343 _mesa_simplify_cmp(program);
1344 /* Stop when no modifications were output */
1345 do {
1346 any_change = GL_FALSE;
1347 _mesa_remove_extra_move_use(program);
1348 if (_mesa_remove_dead_code_global(program))
1349 any_change = GL_TRUE;
1350 if (_mesa_remove_extra_moves(program))
1351 any_change = GL_TRUE;
1352 if (_mesa_remove_dead_code_local(program))
1353 any_change = GL_TRUE;
1354
1355 any_change = _mesa_constant_fold(program) || any_change;
1356 _mesa_reallocate_registers(program);
1357 } while (any_change);
1358 }
1359