Path: blob/main/cranelift/fuzzgen/src/passes/int_divz.rs
1692 views
use crate::FuzzGen;1use anyhow::Result;2use cranelift::codegen::cursor::{Cursor, FuncCursor};3use cranelift::codegen::ir::{Function, Inst, Opcode};4use cranelift::prelude::{InstBuilder, IntCC};56pub fn do_int_divz_pass(fuzz: &mut FuzzGen, func: &mut Function) -> Result<()> {7// Insert this per function, otherwise the actual rate of int_divz doesn't go down that much8// Experimentally if we decide this per instruction with a 0.1% allow rate, we get 4.4% of runs9// trapping. Doing this per function decreases the number of runs that trap. It also consumes10// fewer fuzzer input bytes which is nice.11let ratio = fuzz.config.allowed_int_divz_ratio;12let insert_seq = !fuzz.u.ratio(ratio.0, ratio.1)?;13if !insert_seq {14return Ok(());15}1617let mut pos = FuncCursor::new(func);18while let Some(_block) = pos.next_block() {19while let Some(inst) = pos.next_inst() {20if can_int_divz(&pos, inst) {21insert_int_divz_sequence(&mut pos, inst);22}23}24}25Ok(())26}2728/// Returns true/false if this instruction can cause a `int_divz` trap29fn can_int_divz(pos: &FuncCursor, inst: Inst) -> bool {30let opcode = pos.func.dfg.insts[inst].opcode();3132matches!(33opcode,34Opcode::Sdiv | Opcode::Udiv | Opcode::Srem | Opcode::Urem35)36}3738/// Prepend instructions to inst to avoid `int_divz` traps39fn insert_int_divz_sequence(pos: &mut FuncCursor, inst: Inst) {40let opcode = pos.func.dfg.insts[inst].opcode();41let inst_args = pos.func.dfg.inst_args(inst);42let (lhs, rhs) = (inst_args[0], inst_args[1]);43assert_eq!(pos.func.dfg.value_type(lhs), pos.func.dfg.value_type(rhs));44let ty = pos.func.dfg.value_type(lhs);4546// All of these instructions can trap if the denominator is zero47let zero = pos.ins().iconst(ty, 0);48let one = pos.ins().iconst(ty, 1);49let denominator_is_zero = pos.ins().icmp(IntCC::Equal, rhs, zero);5051let replace_denominator = if matches!(opcode, Opcode::Srem | Opcode::Sdiv) {52// Srem and Sdiv can also trap on INT_MIN / -1. So we need to check for the second one5354// 1 << (ty bits - 1) to get INT_MIN55let int_min = pos.ins().ishl_imm(one, ty.lane_bits() as i64 - 1);5657// Get a -1 const58// TODO: A iconst -1 would be clearer, but #2906 makes this impossible for i12859let neg_one = pos.ins().isub(zero, one);6061let lhs_check = pos.ins().icmp(IntCC::Equal, lhs, int_min);62let rhs_check = pos.ins().icmp(IntCC::Equal, rhs, neg_one);63let is_invalid = pos.ins().band(lhs_check, rhs_check);6465// These also crash if the denominator is zero, so we still need to check for that.66pos.ins().bor(denominator_is_zero, is_invalid)67} else {68denominator_is_zero69};7071// If we have a trap we replace the denominator with a 172let new_rhs = pos.ins().select(replace_denominator, one, rhs);7374// Replace the previous rhs with the new one75let args = pos.func.dfg.inst_args_mut(inst);76args[1] = new_rhs;77}787980