2 * Copyright (C) 2019 Ryan Houdek <Sonicadvance1@gmail.com>
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 #include "bifrost_opts.h"
25 #include "compiler_defines.h"
28 bifrost_opt_branch_fusion(compiler_context
*ctx
, bifrost_block
*block
)
30 bool progress
= false;
31 mir_foreach_instr_in_block_safe(block
, instr
) {
32 if (instr
->op
!= op_branch
) continue;
33 if (instr
->literal_args
[0] != BR_COND_EQ
) continue;
35 unsigned src1
= instr
->ssa_args
.src0
;
37 // Only work on SSA values
38 if (src1
>= SSA_FIXED_MINIMUM
) continue;
40 // Find the source for this conditional branch instruction
41 // It'll be a CSEL instruction
42 // If it's comparision is one of the ops that our conditional branch supports
43 // then we can merge the two
44 mir_foreach_instr_in_block_from_rev(block
, next_instr
, instr
) {
45 if (next_instr
->op
!= op_csel_i32
) continue;
47 if (next_instr
->ssa_args
.dest
== src1
) {
48 // We found the CSEL instruction that is the source here
49 // Check its condition to make sure it matches what we can fuse
50 unsigned cond
= next_instr
->literal_args
[0];
51 if (cond
== CSEL_IEQ
) {
52 // This CSEL is doing an IEQ for our conditional branch doing EQ
53 // We can just emit a conditional branch that does the comparison
54 struct bifrost_instruction new_instr
= {
58 .dest
= SSA_INVALID_VALUE
,
59 .src0
= next_instr
->ssa_args
.src0
,
60 .src1
= next_instr
->ssa_args
.src1
,
61 .src2
= SSA_INVALID_VALUE
,
62 .src3
= SSA_INVALID_VALUE
,
64 .literal_args
[0] = BR_COND_EQ
,
65 .literal_args
[1] = instr
->literal_args
[1],
67 mir_insert_instr_before(instr
, new_instr
);
68 mir_remove_instr(instr
);