summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_codegen_cranelift/src/optimize/peephole.rs
blob: 7f45bbd8f28136a43b8271ba5f3e2755d19d522d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! Peephole optimizations that can be performed while creating clif ir.

use cranelift_codegen::ir::{condcodes::IntCC, InstructionData, Opcode, Value, ValueDef};
use cranelift_frontend::FunctionBuilder;

/// If the given value was produced by the lowering of `Rvalue::Not` return the input and true,
/// otherwise return the given value and false.
pub(crate) fn maybe_unwrap_bool_not(bcx: &mut FunctionBuilder<'_>, arg: Value) -> (Value, bool) {
    if let ValueDef::Result(arg_inst, 0) = bcx.func.dfg.value_def(arg) {
        match bcx.func.dfg[arg_inst] {
            // This is the lowering of `Rvalue::Not`
            InstructionData::IntCompareImm {
                opcode: Opcode::IcmpImm,
                cond: IntCC::Equal,
                arg,
                imm,
            } if imm.bits() == 0 => (arg, true),
            _ => (arg, false),
        }
    } else {
        (arg, false)
    }
}

/// Returns whether the branch is statically known to be taken or `None` if it isn't statically known.
pub(crate) fn maybe_known_branch_taken(
    bcx: &FunctionBuilder<'_>,
    arg: Value,
    test_zero: bool,
) -> Option<bool> {
    let arg_inst = if let ValueDef::Result(arg_inst, 0) = bcx.func.dfg.value_def(arg) {
        arg_inst
    } else {
        return None;
    };

    match bcx.func.dfg[arg_inst] {
        InstructionData::UnaryImm { opcode: Opcode::Iconst, imm } => {
            if test_zero {
                Some(imm.bits() == 0)
            } else {
                Some(imm.bits() != 0)
            }
        }
        _ => None,
    }
}