2 * Mesa 3-D graphics library
4 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
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:
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
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.
26 #include "main/glheader.h"
27 #include "main/context.h"
28 #include "main/macros.h"
30 #include "prog_instruction.h"
31 #include "prog_optimize.h"
32 #include "prog_print.h"
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
41 #define REG_ALLOCATE_MAX_PROGRAM_TEMPS ((1 << INST_INDEX_BITS) - 1)
43 static GLboolean dbg
= GL_FALSE
;
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
54 get_src_arg_mask(const struct prog_instruction
*inst
,
55 GLuint arg
, GLuint dst_mask
)
57 GLuint read_mask
, channel_mask
;
60 ASSERT(arg
< _mesa_num_inst_src_regs(inst
->Opcode
));
62 /* Form the dst register, find the written channels */
63 if (inst
->CondUpdate
) {
64 channel_mask
= WRITEMASK_XYZW
;
67 switch (inst
->Opcode
) {
87 channel_mask
= inst
->DstReg
.WriteMask
& dst_mask
;
96 channel_mask
= WRITEMASK_X
;
99 channel_mask
= WRITEMASK_XY
;
103 channel_mask
= WRITEMASK_XYZ
;
106 channel_mask
= WRITEMASK_XYZW
;
111 /* Now, given the src swizzle and the written channels, find which
112 * components are actually read
115 for (comp
= 0; comp
< 4; ++comp
) {
116 const GLuint coord
= GET_SWZ(inst
->SrcReg
[arg
].Swizzle
, comp
);
118 if (channel_mask
& (1 << comp
) && coord
<= SWIZZLE_W
)
119 read_mask
|= 1 << coord
;
127 * For a MOV instruction, compute a write mask when src register also has
131 get_dst_mask_for_mov(const struct prog_instruction
*mov
, GLuint src_mask
)
133 const GLuint mask
= mov
->DstReg
.WriteMask
;
135 GLuint updated_mask
= 0x0;
137 ASSERT(mov
->Opcode
== OPCODE_MOV
);
139 for (comp
= 0; comp
< 4; ++comp
) {
141 if ((mask
& (1 << comp
)) == 0)
143 src_comp
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, comp
);
144 if ((src_mask
& (1 << src_comp
)) == 0)
146 updated_mask
|= 1 << comp
;
154 * Ensure that the swizzle is regular. That is, all of the swizzle
155 * terms are SWIZZLE_X,Y,Z,W and not SWIZZLE_ZERO or SWIZZLE_ONE.
158 is_swizzle_regular(GLuint swz
)
160 return GET_SWZ(swz
,0) <= SWIZZLE_W
&&
161 GET_SWZ(swz
,1) <= SWIZZLE_W
&&
162 GET_SWZ(swz
,2) <= SWIZZLE_W
&&
163 GET_SWZ(swz
,3) <= SWIZZLE_W
;
168 * In 'prog' remove instruction[i] if removeFlags[i] == TRUE.
169 * \return number of instructions removed
172 remove_instructions(struct gl_program
*prog
, const GLboolean
*removeFlags
)
174 GLint i
, removeEnd
= 0, removeCount
= 0;
175 GLuint totalRemoved
= 0;
178 for (i
= prog
->NumInstructions
- 1; i
>= 0; i
--) {
179 if (removeFlags
[i
]) {
181 if (removeCount
== 0) {
182 /* begin a run of instructions to remove */
187 /* extend the run of instructions to remove */
192 /* don't remove this instruction, but check if the preceeding
193 * instructions are to be removed.
195 if (removeCount
> 0) {
196 GLint removeStart
= removeEnd
- removeCount
+ 1;
197 _mesa_delete_instructions(prog
, removeStart
, removeCount
);
198 removeStart
= removeCount
= 0; /* reset removal info */
202 /* Finish removing if the first instruction was to be removed. */
203 if (removeCount
> 0) {
204 GLint removeStart
= removeEnd
- removeCount
+ 1;
205 _mesa_delete_instructions(prog
, removeStart
, removeCount
);
212 * Remap register indexes according to map.
213 * \param prog the program to search/replace
214 * \param file the type of register file to search/replace
215 * \param map maps old register indexes to new indexes
218 replace_regs(struct gl_program
*prog
, gl_register_file file
, const GLint map
[])
222 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
223 struct prog_instruction
*inst
= prog
->Instructions
+ i
;
224 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
226 for (j
= 0; j
< numSrc
; j
++) {
227 if (inst
->SrcReg
[j
].File
== file
) {
228 GLuint index
= inst
->SrcReg
[j
].Index
;
229 ASSERT(map
[index
] >= 0);
230 inst
->SrcReg
[j
].Index
= map
[index
];
233 if (inst
->DstReg
.File
== file
) {
234 const GLuint index
= inst
->DstReg
.Index
;
235 ASSERT(map
[index
] >= 0);
236 inst
->DstReg
.Index
= map
[index
];
243 * Remove dead instructions from the given program.
244 * This is very primitive for now. Basically look for temp registers
245 * that are written to but never read. Remove any instructions that
246 * write to such registers. Be careful with condition code setters.
249 _mesa_remove_dead_code_global(struct gl_program
*prog
)
251 GLboolean tempRead
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
][4];
252 GLboolean
*removeInst
; /* per-instruction removal flag */
253 GLuint i
, rem
= 0, comp
;
255 memset(tempRead
, 0, sizeof(tempRead
));
258 printf("Optimize: Begin dead code removal\n");
259 /*_mesa_print_program(prog);*/
263 calloc(1, prog
->NumInstructions
* sizeof(GLboolean
));
265 /* Determine which temps are read and written */
266 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
267 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
268 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
272 for (j
= 0; j
< numSrc
; j
++) {
273 if (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
) {
274 const GLuint index
= inst
->SrcReg
[j
].Index
;
276 ASSERT(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
277 read_mask
= get_src_arg_mask(inst
, j
, NO_MASK
);
279 if (inst
->SrcReg
[j
].RelAddr
) {
281 printf("abort remove dead code (indirect temp)\n");
285 for (comp
= 0; comp
< 4; comp
++) {
286 const GLuint swz
= GET_SWZ(inst
->SrcReg
[j
].Swizzle
, comp
);
288 if ((read_mask
& (1 << swz
)) == 0)
290 if (swz
<= SWIZZLE_W
)
291 tempRead
[index
][swz
] = GL_TRUE
;
297 if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
298 const GLuint index
= inst
->DstReg
.Index
;
299 ASSERT(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
301 if (inst
->DstReg
.RelAddr
) {
303 printf("abort remove dead code (indirect temp)\n");
307 if (inst
->CondUpdate
) {
308 /* If we're writing to this register and setting condition
309 * codes we cannot remove the instruction. Prevent removal
310 * by setting the 'read' flag.
312 tempRead
[index
][0] = GL_TRUE
;
313 tempRead
[index
][1] = GL_TRUE
;
314 tempRead
[index
][2] = GL_TRUE
;
315 tempRead
[index
][3] = GL_TRUE
;
320 /* find instructions that write to dead registers, flag for removal */
321 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
322 struct prog_instruction
*inst
= prog
->Instructions
+ i
;
323 const GLuint numDst
= _mesa_num_inst_dst_regs(inst
->Opcode
);
325 if (numDst
!= 0 && inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
326 GLint chan
, index
= inst
->DstReg
.Index
;
328 for (chan
= 0; chan
< 4; chan
++) {
329 if (!tempRead
[index
][chan
] &&
330 inst
->DstReg
.WriteMask
& (1 << chan
)) {
332 printf("Remove writemask on %u.%c\n", i
,
333 chan
== 3 ? 'w' : 'x' + chan
);
335 inst
->DstReg
.WriteMask
&= ~(1 << chan
);
340 if (inst
->DstReg
.WriteMask
== 0) {
341 /* If we cleared all writes, the instruction can be removed. */
343 printf("Remove instruction %u: \n", i
);
344 removeInst
[i
] = GL_TRUE
;
349 /* now remove the instructions which aren't needed */
350 rem
= remove_instructions(prog
, removeInst
);
353 printf("Optimize: End dead code removal.\n");
354 printf(" %u channel writes removed\n", rem
);
355 printf(" %u instructions removed\n", rem
);
356 /*_mesa_print_program(prog);*/
375 * Scan forward in program from 'start' for the next occurances of TEMP[index].
376 * We look if an instruction reads the component given by the masks and if they
378 * Return READ, WRITE, FLOW or END to indicate the next usage or an indicator
379 * that we can't look further.
382 find_next_use(const struct gl_program
*prog
,
389 for (i
= start
; i
< prog
->NumInstructions
; i
++) {
390 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
391 switch (inst
->Opcode
) {
407 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
409 for (j
= 0; j
< numSrc
; j
++) {
410 if (inst
->SrcReg
[j
].RelAddr
||
411 (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
&&
412 inst
->SrcReg
[j
].Index
== index
&&
413 (get_src_arg_mask(inst
,j
,NO_MASK
) & mask
)))
416 if (_mesa_num_inst_dst_regs(inst
->Opcode
) == 1 &&
417 inst
->DstReg
.File
== PROGRAM_TEMPORARY
&&
418 inst
->DstReg
.Index
== index
) {
419 mask
&= ~inst
->DstReg
.WriteMask
;
431 * Is the given instruction opcode a flow-control opcode?
432 * XXX maybe move this into prog_instruction.[ch]
435 _mesa_is_flow_control_opcode(enum prog_opcode opcode
)
457 * Test if the given instruction is a simple MOV (no conditional updating,
458 * not relative addressing, no negation/abs, etc).
461 can_downward_mov_be_modifed(const struct prog_instruction
*mov
)
464 mov
->Opcode
== OPCODE_MOV
&&
465 mov
->CondUpdate
== GL_FALSE
&&
466 mov
->SrcReg
[0].RelAddr
== 0 &&
467 mov
->SrcReg
[0].Negate
== 0 &&
468 mov
->SrcReg
[0].Abs
== 0 &&
469 mov
->SrcReg
[0].HasIndex2
== 0 &&
470 mov
->SrcReg
[0].RelAddr2
== 0 &&
471 mov
->DstReg
.RelAddr
== 0 &&
472 mov
->DstReg
.CondMask
== COND_TR
;
477 can_upward_mov_be_modifed(const struct prog_instruction
*mov
)
480 can_downward_mov_be_modifed(mov
) &&
481 mov
->DstReg
.File
== PROGRAM_TEMPORARY
&&
482 mov
->SaturateMode
== SATURATE_OFF
;
487 * Try to remove use of extraneous MOV instructions, to free them up for dead
491 _mesa_remove_extra_move_use(struct gl_program
*prog
)
496 printf("Optimize: Begin remove extra move use\n");
497 _mesa_print_program(prog
);
501 * Look for sequences such as this:
504 * FOO tmpY, tmpX, arg1;
508 * FOO tmpY, arg0, arg1;
511 for (i
= 0; i
+ 1 < prog
->NumInstructions
; i
++) {
512 const struct prog_instruction
*mov
= prog
->Instructions
+ i
;
513 GLuint dst_mask
, src_mask
;
514 if (can_upward_mov_be_modifed(mov
) == GL_FALSE
)
517 /* Scanning the code, we maintain the components which are still active in
520 dst_mask
= mov
->DstReg
.WriteMask
;
521 src_mask
= get_src_arg_mask(mov
, 0, NO_MASK
);
523 /* Walk through remaining instructions until the or src reg gets
524 * rewritten or we get into some flow-control, eliminating the use of
527 for (j
= i
+ 1; j
< prog
->NumInstructions
; j
++) {
528 struct prog_instruction
*inst2
= prog
->Instructions
+ j
;
531 if (_mesa_is_flow_control_opcode(inst2
->Opcode
))
534 /* First rewrite this instruction's args if appropriate. */
535 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst2
->Opcode
); arg
++) {
536 GLuint comp
, read_mask
;
538 if (inst2
->SrcReg
[arg
].File
!= mov
->DstReg
.File
||
539 inst2
->SrcReg
[arg
].Index
!= mov
->DstReg
.Index
||
540 inst2
->SrcReg
[arg
].RelAddr
||
541 inst2
->SrcReg
[arg
].Abs
)
543 read_mask
= get_src_arg_mask(inst2
, arg
, NO_MASK
);
545 /* Adjust the swizzles of inst2 to point at MOV's source if ALL the
546 * components read still come from the mov instructions
548 if (is_swizzle_regular(inst2
->SrcReg
[arg
].Swizzle
) &&
549 (read_mask
& dst_mask
) == read_mask
) {
550 for (comp
= 0; comp
< 4; comp
++) {
551 const GLuint inst2_swz
=
552 GET_SWZ(inst2
->SrcReg
[arg
].Swizzle
, comp
);
553 const GLuint s
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, inst2_swz
);
554 inst2
->SrcReg
[arg
].Swizzle
&= ~(7 << (3 * comp
));
555 inst2
->SrcReg
[arg
].Swizzle
|= s
<< (3 * comp
);
556 inst2
->SrcReg
[arg
].Negate
^= (((mov
->SrcReg
[0].Negate
>>
557 inst2_swz
) & 0x1) << comp
);
559 inst2
->SrcReg
[arg
].File
= mov
->SrcReg
[0].File
;
560 inst2
->SrcReg
[arg
].Index
= mov
->SrcReg
[0].Index
;
564 /* The source of MOV is written. This potentially deactivates some
565 * components from the src and dst of the MOV instruction
567 if (inst2
->DstReg
.File
== mov
->DstReg
.File
&&
568 (inst2
->DstReg
.RelAddr
||
569 inst2
->DstReg
.Index
== mov
->DstReg
.Index
)) {
570 dst_mask
&= ~inst2
->DstReg
.WriteMask
;
571 src_mask
= get_src_arg_mask(mov
, 0, dst_mask
);
574 /* Idem when the destination of mov is written */
575 if (inst2
->DstReg
.File
== mov
->SrcReg
[0].File
&&
576 (inst2
->DstReg
.RelAddr
||
577 inst2
->DstReg
.Index
== mov
->SrcReg
[0].Index
)) {
578 src_mask
&= ~inst2
->DstReg
.WriteMask
;
579 dst_mask
&= get_dst_mask_for_mov(mov
, src_mask
);
587 printf("Optimize: End remove extra move use.\n");
588 /*_mesa_print_program(prog);*/
594 * Complements dead_code_global. Try to remove code in block of code by
595 * carefully monitoring the swizzles. Both functions should be merged into one
596 * with a proper control flow graph
599 _mesa_remove_dead_code_local(struct gl_program
*prog
)
601 GLboolean
*removeInst
;
602 GLuint i
, arg
, rem
= 0;
605 calloc(1, prog
->NumInstructions
* sizeof(GLboolean
));
607 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
608 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
609 const GLuint index
= inst
->DstReg
.Index
;
610 const GLuint mask
= inst
->DstReg
.WriteMask
;
613 /* We must deactivate the pass as soon as some indirection is used */
614 if (inst
->DstReg
.RelAddr
)
616 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst
->Opcode
); arg
++)
617 if (inst
->SrcReg
[arg
].RelAddr
)
620 if (_mesa_is_flow_control_opcode(inst
->Opcode
) ||
621 _mesa_num_inst_dst_regs(inst
->Opcode
) == 0 ||
622 inst
->DstReg
.File
!= PROGRAM_TEMPORARY
||
623 inst
->DstReg
.RelAddr
)
626 use
= find_next_use(prog
, i
+1, index
, mask
);
627 if (use
== WRITE
|| use
== END
)
628 removeInst
[i
] = GL_TRUE
;
631 rem
= remove_instructions(prog
, removeInst
);
640 * Try to inject the destination of mov as the destination of inst and recompute
641 * the swizzles operators for the sources of inst if required. Return GL_TRUE
642 * of the substitution was possible, GL_FALSE otherwise
645 _mesa_merge_mov_into_inst(struct prog_instruction
*inst
,
646 const struct prog_instruction
*mov
)
648 /* Indirection table which associates destination and source components for
649 * the mov instruction
651 const GLuint mask
= get_src_arg_mask(mov
, 0, NO_MASK
);
653 /* Some components are not written by inst. We cannot remove the mov */
654 if (mask
!= (inst
->DstReg
.WriteMask
& mask
))
657 inst
->SaturateMode
|= mov
->SaturateMode
;
659 /* Depending on the instruction, we may need to recompute the swizzles.
660 * Also, some other instructions (like TEX) are not linear. We will only
661 * consider completely active sources and destinations
663 switch (inst
->Opcode
) {
665 /* Carstesian instructions: we compute the swizzle */
675 GLuint dst_to_src_comp
[4] = {0,0,0,0};
676 GLuint dst_comp
, arg
;
677 for (dst_comp
= 0; dst_comp
< 4; ++dst_comp
) {
678 if (mov
->DstReg
.WriteMask
& (1 << dst_comp
)) {
679 const GLuint src_comp
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, dst_comp
);
680 ASSERT(src_comp
< 4);
681 dst_to_src_comp
[dst_comp
] = src_comp
;
685 /* Patch each source of the instruction */
686 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst
->Opcode
); arg
++) {
687 const GLuint arg_swz
= inst
->SrcReg
[arg
].Swizzle
;
688 inst
->SrcReg
[arg
].Swizzle
= 0;
690 /* Reset each active component of the swizzle */
691 for (dst_comp
= 0; dst_comp
< 4; ++dst_comp
) {
692 GLuint src_comp
, arg_comp
;
693 if ((mov
->DstReg
.WriteMask
& (1 << dst_comp
)) == 0)
695 src_comp
= dst_to_src_comp
[dst_comp
];
696 ASSERT(src_comp
< 4);
697 arg_comp
= GET_SWZ(arg_swz
, src_comp
);
698 ASSERT(arg_comp
< 4);
699 inst
->SrcReg
[arg
].Swizzle
|= arg_comp
<< (3*dst_comp
);
702 inst
->DstReg
= mov
->DstReg
;
706 /* Dot products and scalar instructions: we only change the destination */
717 inst
->DstReg
= mov
->DstReg
;
720 /* All other instructions require fully active components with no swizzle */
722 if (mov
->SrcReg
[0].Swizzle
!= SWIZZLE_XYZW
||
723 inst
->DstReg
.WriteMask
!= WRITEMASK_XYZW
)
725 inst
->DstReg
= mov
->DstReg
;
732 * Try to remove extraneous MOV instructions from the given program.
735 _mesa_remove_extra_moves(struct gl_program
*prog
)
737 GLboolean
*removeInst
; /* per-instruction removal flag */
738 GLuint i
, rem
= 0, nesting
= 0;
741 printf("Optimize: Begin remove extra moves\n");
742 _mesa_print_program(prog
);
746 calloc(1, prog
->NumInstructions
* sizeof(GLboolean
));
749 * Look for sequences such as this:
750 * FOO tmpX, arg0, arg1;
753 * FOO tmpY, arg0, arg1;
756 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
757 const struct prog_instruction
*mov
= prog
->Instructions
+ i
;
759 switch (mov
->Opcode
) {
772 can_downward_mov_be_modifed(mov
) &&
773 mov
->SrcReg
[0].File
== PROGRAM_TEMPORARY
&&
777 /* see if this MOV can be removed */
778 const GLuint id
= mov
->SrcReg
[0].Index
;
779 struct prog_instruction
*prevInst
;
782 /* get pointer to previous instruction */
784 while (prevI
> 0 && removeInst
[prevI
])
786 prevInst
= prog
->Instructions
+ prevI
;
788 if (prevInst
->DstReg
.File
== PROGRAM_TEMPORARY
&&
789 prevInst
->DstReg
.Index
== id
&&
790 prevInst
->DstReg
.RelAddr
== 0 &&
791 prevInst
->DstReg
.CondMask
== COND_TR
) {
793 const GLuint dst_mask
= prevInst
->DstReg
.WriteMask
;
794 enum inst_use next_use
= find_next_use(prog
, i
+1, id
, dst_mask
);
796 if (next_use
== WRITE
|| next_use
== END
) {
797 /* OK, we can safely remove this MOV instruction.
799 * prevI: FOO tempIndex, x, y;
800 * i: MOV z, tempIndex;
802 * prevI: FOO z, x, y;
804 if (_mesa_merge_mov_into_inst(prevInst
, mov
)) {
805 removeInst
[i
] = GL_TRUE
;
807 printf("Remove MOV at %u\n", i
);
808 printf("new prev inst %u: ", prevI
);
809 _mesa_print_instruction(prevInst
);
821 /* now remove the instructions which aren't needed */
822 rem
= remove_instructions(prog
, removeInst
);
827 printf("Optimize: End remove extra moves. %u instructions removed\n", rem
);
828 /*_mesa_print_program(prog);*/
835 /** A live register interval */
838 GLuint Reg
; /** The temporary register index */
839 GLuint Start
, End
; /** Start/end instruction numbers */
843 /** A list of register intervals */
847 struct interval Intervals
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
852 append_interval(struct interval_list
*list
, const struct interval
*inv
)
854 list
->Intervals
[list
->Num
++] = *inv
;
858 /** Insert interval inv into list, sorted by interval end */
860 insert_interval_by_end(struct interval_list
*list
, const struct interval
*inv
)
862 /* XXX we could do a binary search insertion here since list is sorted */
863 GLint i
= list
->Num
- 1;
864 while (i
>= 0 && list
->Intervals
[i
].End
> inv
->End
) {
865 list
->Intervals
[i
+ 1] = list
->Intervals
[i
];
868 list
->Intervals
[i
+ 1] = *inv
;
874 for (i
= 0; i
+ 1 < list
->Num
; i
++) {
875 ASSERT(list
->Intervals
[i
].End
<= list
->Intervals
[i
+ 1].End
);
882 /** Remove the given interval from the interval list */
884 remove_interval(struct interval_list
*list
, const struct interval
*inv
)
886 /* XXX we could binary search since list is sorted */
888 for (k
= 0; k
< list
->Num
; k
++) {
889 if (list
->Intervals
[k
].Reg
== inv
->Reg
) {
890 /* found, remove it */
891 ASSERT(list
->Intervals
[k
].Start
== inv
->Start
);
892 ASSERT(list
->Intervals
[k
].End
== inv
->End
);
893 while (k
< list
->Num
- 1) {
894 list
->Intervals
[k
] = list
->Intervals
[k
+ 1];
904 /** called by qsort() */
906 compare_start(const void *a
, const void *b
)
908 const struct interval
*ia
= (const struct interval
*) a
;
909 const struct interval
*ib
= (const struct interval
*) b
;
910 if (ia
->Start
< ib
->Start
)
912 else if (ia
->Start
> ib
->Start
)
919 /** sort the interval list according to interval starts */
921 sort_interval_list_by_start(struct interval_list
*list
)
923 qsort(list
->Intervals
, list
->Num
, sizeof(struct interval
), compare_start
);
927 for (i
= 0; i
+ 1 < list
->Num
; i
++) {
928 ASSERT(list
->Intervals
[i
].Start
<= list
->Intervals
[i
+ 1].Start
);
936 GLuint Start
, End
; /**< Start, end instructions of loop */
940 * Update the intermediate interval info for register 'index' and
944 update_interval(GLint intBegin
[], GLint intEnd
[],
945 struct loop_info
*loopStack
, GLuint loopStackDepth
,
946 GLuint index
, GLuint ic
)
952 /* If the register is used in a loop, extend its lifetime through the end
953 * of the outermost loop that doesn't contain its definition.
955 for (i
= 0; i
< loopStackDepth
; i
++) {
956 if (intBegin
[index
] < loopStack
[i
].Start
) {
957 end
= loopStack
[i
].End
;
962 /* Variables that are live at the end of a loop will also be live at the
963 * beginning, so an instruction inside of a loop should have its live
964 * interval begin at the start of the outermost loop.
966 if (loopStackDepth
> 0 && ic
> loopStack
[0].Start
&& ic
< loopStack
[0].End
) {
967 begin
= loopStack
[0].Start
;
970 ASSERT(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
971 if (intBegin
[index
] == -1) {
972 ASSERT(intEnd
[index
] == -1);
973 intBegin
[index
] = begin
;
983 * Find first/last instruction that references each temporary register.
986 _mesa_find_temp_intervals(const struct prog_instruction
*instructions
,
987 GLuint numInstructions
,
988 GLint intBegin
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
],
989 GLint intEnd
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
])
991 struct loop_info loopStack
[MAX_LOOP_NESTING
];
992 GLuint loopStackDepth
= 0;
995 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++){
996 intBegin
[i
] = intEnd
[i
] = -1;
999 /* Scan instructions looking for temporary registers */
1000 for (i
= 0; i
< numInstructions
; i
++) {
1001 const struct prog_instruction
*inst
= instructions
+ i
;
1002 if (inst
->Opcode
== OPCODE_BGNLOOP
) {
1003 loopStack
[loopStackDepth
].Start
= i
;
1004 loopStack
[loopStackDepth
].End
= inst
->BranchTarget
;
1007 else if (inst
->Opcode
== OPCODE_ENDLOOP
) {
1010 else if (inst
->Opcode
== OPCODE_CAL
) {
1014 const GLuint numSrc
= 3;/*_mesa_num_inst_src_regs(inst->Opcode);*/
1016 for (j
= 0; j
< numSrc
; j
++) {
1017 if (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
) {
1018 const GLuint index
= inst
->SrcReg
[j
].Index
;
1019 if (inst
->SrcReg
[j
].RelAddr
)
1021 update_interval(intBegin
, intEnd
, loopStack
, loopStackDepth
,
1025 if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
1026 const GLuint index
= inst
->DstReg
.Index
;
1027 if (inst
->DstReg
.RelAddr
)
1029 update_interval(intBegin
, intEnd
, loopStack
, loopStackDepth
,
1040 * Find the live intervals for each temporary register in the program.
1041 * For register R, the interval [A,B] indicates that R is referenced
1042 * from instruction A through instruction B.
1043 * Special consideration is needed for loops and subroutines.
1044 * \return GL_TRUE if success, GL_FALSE if we cannot proceed for some reason
1047 find_live_intervals(struct gl_program
*prog
,
1048 struct interval_list
*liveIntervals
)
1050 GLint intBegin
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1051 GLint intEnd
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1055 * Note: we'll return GL_FALSE below if we find relative indexing
1056 * into the TEMP register file. We can't handle that yet.
1057 * We also give up on subroutines for now.
1061 printf("Optimize: Begin find intervals\n");
1064 /* build intermediate arrays */
1065 if (!_mesa_find_temp_intervals(prog
->Instructions
, prog
->NumInstructions
,
1069 /* Build live intervals list from intermediate arrays */
1070 liveIntervals
->Num
= 0;
1071 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++) {
1072 if (intBegin
[i
] >= 0) {
1073 struct interval inv
;
1075 inv
.Start
= intBegin
[i
];
1076 inv
.End
= intEnd
[i
];
1077 append_interval(liveIntervals
, &inv
);
1081 /* Sort the list according to interval starts */
1082 sort_interval_list_by_start(liveIntervals
);
1085 /* print interval info */
1086 for (i
= 0; i
< liveIntervals
->Num
; i
++) {
1087 const struct interval
*inv
= liveIntervals
->Intervals
+ i
;
1088 printf("Reg[%d] live [%d, %d]:",
1089 inv
->Reg
, inv
->Start
, inv
->End
);
1092 for (j
= 0; j
< inv
->Start
; j
++)
1094 for (j
= inv
->Start
; j
<= inv
->End
; j
++)
1105 /** Scan the array of used register flags to find free entry */
1107 alloc_register(GLboolean usedRegs
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
])
1110 for (k
= 0; k
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; k
++) {
1112 usedRegs
[k
] = GL_TRUE
;
1121 * This function implements "Linear Scan Register Allocation" to reduce
1122 * the number of temporary registers used by the program.
1124 * We compute the "live interval" for all temporary registers then
1125 * examine the overlap of the intervals to allocate new registers.
1126 * Basically, if two intervals do not overlap, they can use the same register.
1129 _mesa_reallocate_registers(struct gl_program
*prog
)
1131 struct interval_list liveIntervals
;
1132 GLint registerMap
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1133 GLboolean usedRegs
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1138 printf("Optimize: Begin live-interval register reallocation\n");
1139 _mesa_print_program(prog
);
1142 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++){
1143 registerMap
[i
] = -1;
1144 usedRegs
[i
] = GL_FALSE
;
1147 if (!find_live_intervals(prog
, &liveIntervals
)) {
1149 printf("Aborting register reallocation\n");
1154 struct interval_list activeIntervals
;
1155 activeIntervals
.Num
= 0;
1157 /* loop over live intervals, allocating a new register for each */
1158 for (i
= 0; i
< liveIntervals
.Num
; i
++) {
1159 const struct interval
*live
= liveIntervals
.Intervals
+ i
;
1162 printf("Consider register %u\n", live
->Reg
);
1164 /* Expire old intervals. Intervals which have ended with respect
1165 * to the live interval can have their remapped registers freed.
1169 for (j
= 0; j
< (GLint
) activeIntervals
.Num
; j
++) {
1170 const struct interval
*inv
= activeIntervals
.Intervals
+ j
;
1171 if (inv
->End
>= live
->Start
) {
1172 /* Stop now. Since the activeInterval list is sorted
1173 * we know we don't have to go further.
1178 /* Interval 'inv' has expired */
1179 const GLint regNew
= registerMap
[inv
->Reg
];
1180 ASSERT(regNew
>= 0);
1183 printf(" expire interval for reg %u\n", inv
->Reg
);
1185 /* remove interval j from active list */
1186 remove_interval(&activeIntervals
, inv
);
1187 j
--; /* counter-act j++ in for-loop above */
1189 /* return register regNew to the free pool */
1191 printf(" free reg %d\n", regNew
);
1192 ASSERT(usedRegs
[regNew
] == GL_TRUE
);
1193 usedRegs
[regNew
] = GL_FALSE
;
1198 /* find a free register for this live interval */
1200 const GLint k
= alloc_register(usedRegs
);
1202 /* out of registers, give up */
1205 registerMap
[live
->Reg
] = k
;
1206 maxTemp
= MAX2(maxTemp
, k
);
1208 printf(" remap register %u -> %d\n", live
->Reg
, k
);
1211 /* Insert this live interval into the active list which is sorted
1212 * by increasing end points.
1214 insert_interval_by_end(&activeIntervals
, live
);
1218 if (maxTemp
+ 1 < (GLint
) liveIntervals
.Num
) {
1219 /* OK, we've reduced the number of registers needed.
1220 * Scan the program and replace all the old temporary register
1221 * indexes with the new indexes.
1223 replace_regs(prog
, PROGRAM_TEMPORARY
, registerMap
);
1225 prog
->NumTemporaries
= maxTemp
+ 1;
1229 printf("Optimize: End live-interval register reallocation\n");
1230 printf("Num temp regs before: %u after: %u\n",
1231 liveIntervals
.Num
, maxTemp
+ 1);
1232 _mesa_print_program(prog
);
1239 print_it(struct gl_context
*ctx
, struct gl_program
*program
, const char *txt
) {
1240 fprintf(stderr
, "%s (%u inst):\n", txt
, program
->NumInstructions
);
1241 _mesa_print_program(program
);
1242 _mesa_print_program_parameters(ctx
, program
);
1243 fprintf(stderr
, "\n\n");
1248 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
1249 * instruction is the first instruction to write to register T0. The are
1250 * several lowering passes done in GLSL IR (e.g. branches and
1251 * relative addressing) that create a large number of conditional assignments
1252 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
1254 * Here is why this conversion is safe:
1255 * CMP T0, T1 T2 T0 can be expanded to:
1261 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
1262 * as the original program. If (T1 < 0.0) evaluates to false, executing
1263 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
1264 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
1265 * because any instruction that was going to read from T0 after this was going
1266 * to read a garbage value anyway.
1269 _mesa_simplify_cmp(struct gl_program
* program
)
1271 GLuint tempWrites
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1272 GLuint outputWrites
[MAX_PROGRAM_OUTPUTS
];
1276 printf("Optimize: Begin reads without writes\n");
1277 _mesa_print_program(program
);
1280 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++) {
1284 for (i
= 0; i
< MAX_PROGRAM_OUTPUTS
; i
++) {
1285 outputWrites
[i
] = 0;
1288 for (i
= 0; i
< program
->NumInstructions
; i
++) {
1289 struct prog_instruction
*inst
= program
->Instructions
+ i
;
1290 GLuint prevWriteMask
;
1292 /* Give up if we encounter relative addressing or flow control. */
1293 if (_mesa_is_flow_control_opcode(inst
->Opcode
) || inst
->DstReg
.RelAddr
) {
1297 if (inst
->DstReg
.File
== PROGRAM_OUTPUT
) {
1298 assert(inst
->DstReg
.Index
< MAX_PROGRAM_OUTPUTS
);
1299 prevWriteMask
= outputWrites
[inst
->DstReg
.Index
];
1300 outputWrites
[inst
->DstReg
.Index
] |= inst
->DstReg
.WriteMask
;
1301 } else if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
1302 assert(inst
->DstReg
.Index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
1303 prevWriteMask
= tempWrites
[inst
->DstReg
.Index
];
1304 tempWrites
[inst
->DstReg
.Index
] |= inst
->DstReg
.WriteMask
;
1306 /* No other register type can be a destination register. */
1310 /* For a CMP to be considered a conditional write, the destination
1311 * register and source register two must be the same. */
1312 if (inst
->Opcode
== OPCODE_CMP
1313 && !(inst
->DstReg
.WriteMask
& prevWriteMask
)
1314 && inst
->SrcReg
[2].File
== inst
->DstReg
.File
1315 && inst
->SrcReg
[2].Index
== inst
->DstReg
.Index
1316 && inst
->DstReg
.WriteMask
== get_src_arg_mask(inst
, 2, NO_MASK
)) {
1318 inst
->Opcode
= OPCODE_MOV
;
1319 inst
->SrcReg
[0] = inst
->SrcReg
[1];
1321 /* Unused operands are expected to have the file set to
1322 * PROGRAM_UNDEFINED. This is how _mesa_init_instructions initializes
1323 * all of the sources.
1325 inst
->SrcReg
[1].File
= PROGRAM_UNDEFINED
;
1326 inst
->SrcReg
[1].Swizzle
= SWIZZLE_NOOP
;
1327 inst
->SrcReg
[2].File
= PROGRAM_UNDEFINED
;
1328 inst
->SrcReg
[2].Swizzle
= SWIZZLE_NOOP
;
1332 printf("Optimize: End reads without writes\n");
1333 _mesa_print_program(program
);
1338 * Apply optimizations to the given program to eliminate unnecessary
1339 * instructions, temp regs, etc.
1342 _mesa_optimize_program(struct gl_context
*ctx
, struct gl_program
*program
)
1344 GLboolean any_change
;
1346 _mesa_simplify_cmp(program
);
1347 /* Stop when no modifications were output */
1349 any_change
= GL_FALSE
;
1350 _mesa_remove_extra_move_use(program
);
1351 if (_mesa_remove_dead_code_global(program
))
1352 any_change
= GL_TRUE
;
1353 if (_mesa_remove_extra_moves(program
))
1354 any_change
= GL_TRUE
;
1355 if (_mesa_remove_dead_code_local(program
))
1356 any_change
= GL_TRUE
;
1358 any_change
= _mesa_constant_fold(program
) || any_change
;
1359 _mesa_reallocate_registers(program
);
1360 } while (any_change
);