1 //! CLI tool to reduce Cranelift IR files crashing during compilation. 2 3 use crate::utils::read_to_string; 4 use anyhow::{Context as _, Result}; 5 use clap::Parser; 6 use cranelift::prelude::Value; 7 use cranelift_codegen::cursor::{Cursor, FuncCursor}; 8 use cranelift_codegen::flowgraph::ControlFlowGraph; 9 use cranelift_codegen::ir::types::{F32, F64, I128, I64}; 10 use cranelift_codegen::ir::{ 11 self, Block, FuncRef, Function, GlobalValueData, Inst, InstBuilder, InstructionData, 12 StackSlots, TrapCode, 13 }; 14 use cranelift_codegen::isa::TargetIsa; 15 use cranelift_codegen::Context; 16 use cranelift_entity::PrimaryMap; 17 use cranelift_reader::{parse_sets_and_triple, parse_test, ParseOptions}; 18 use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}; 19 use std::collections::HashMap; 20 use std::path::PathBuf; 21 22 /// Reduce size of clif file causing panic during compilation. 23 #[derive(Parser)] 24 pub struct Options { 25 /// Specify an input file to be used. Use '-' for stdin. 26 file: PathBuf, 27 28 /// Configure Cranelift settings 29 #[arg(long = "set")] 30 settings: Vec<String>, 31 32 /// Specify the target architecture. 33 target: String, 34 35 /// Be more verbose 36 #[arg(short, long)] 37 verbose: bool, 38 } 39 40 pub fn run(options: &Options) -> Result<()> { 41 let parsed = parse_sets_and_triple(&options.settings, &options.target)?; 42 let fisa = parsed.as_fisa(); 43 44 let buffer = read_to_string(&options.file)?; 45 let test_file = parse_test(&buffer, ParseOptions::default()) 46 .with_context(|| format!("failed to parse {}", options.file.display()))?; 47 48 // If we have an isa from the command-line, use that. Otherwise if the 49 // file contains a unique isa, use that. 50 let isa = if let Some(isa) = fisa.isa { 51 isa 52 } else if let Some(isa) = test_file.isa_spec.unique_isa() { 53 isa 54 } else { 55 anyhow::bail!("compilation requires a target isa"); 56 }; 57 58 std::env::set_var("RUST_BACKTRACE", "0"); // Disable backtraces to reduce verbosity 59 60 for (func, _) in test_file.functions { 61 let (orig_block_count, orig_inst_count) = (block_count(&func), inst_count(&func)); 62 63 match reduce(isa, func, options.verbose) { 64 Ok((func, crash_msg)) => { 65 println!("Crash message: {crash_msg}"); 66 println!("\n{func}"); 67 println!( 68 "{} blocks {} insts -> {} blocks {} insts", 69 orig_block_count, 70 orig_inst_count, 71 block_count(&func), 72 inst_count(&func) 73 ); 74 } 75 Err(err) => println!("Warning: {err}"), 76 } 77 } 78 79 Ok(()) 80 } 81 82 enum ProgressStatus { 83 /// The mutation raised or reduced the amount of instructions or blocks. 84 ExpandedOrShrinked, 85 86 /// The mutation only changed an instruction. Performing another round of mutations may only 87 /// reduce the test case if another mutation shrank the test case. 88 Changed, 89 90 /// No need to re-test if the program crashes, because the mutation had no effect, but we want 91 /// to keep on iterating. 92 Skip, 93 } 94 95 trait Mutator { 96 fn name(&self) -> &'static str; 97 fn mutation_count(&self, func: &Function) -> usize; 98 fn mutate(&mut self, func: Function) -> Option<(Function, String, ProgressStatus)>; 99 100 /// Gets called when the returned mutated function kept on causing the crash. This can be used 101 /// to update position of the next item to look at. Does nothing by default. 102 fn did_crash(&mut self) {} 103 } 104 105 /// Try to remove instructions. 106 struct RemoveInst { 107 block: Block, 108 inst: Inst, 109 } 110 111 impl RemoveInst { 112 fn new(func: &Function) -> Self { 113 let first_block = func.layout.entry_block().unwrap(); 114 let first_inst = func.layout.first_inst(first_block).unwrap(); 115 Self { 116 block: first_block, 117 inst: first_inst, 118 } 119 } 120 } 121 122 impl Mutator for RemoveInst { 123 fn name(&self) -> &'static str { 124 "remove inst" 125 } 126 127 fn mutation_count(&self, func: &Function) -> usize { 128 inst_count(func) 129 } 130 131 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 132 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map(|(prev_block, prev_inst)| { 133 func.layout.remove_inst(prev_inst); 134 let msg = if func.layout.block_insts(prev_block).next().is_none() { 135 // Make sure empty blocks are removed, as `next_inst_ret_prev` depends on non empty blocks 136 func.layout.remove_block(prev_block); 137 format!("Remove inst {prev_inst} and empty block {prev_block}") 138 } else { 139 format!("Remove inst {prev_inst}") 140 }; 141 (func, msg, ProgressStatus::ExpandedOrShrinked) 142 }) 143 } 144 } 145 146 /// Try to replace instructions with `iconst` or `fconst`. 147 struct ReplaceInstWithConst { 148 block: Block, 149 inst: Inst, 150 } 151 152 impl ReplaceInstWithConst { 153 fn new(func: &Function) -> Self { 154 let first_block = func.layout.entry_block().unwrap(); 155 let first_inst = func.layout.first_inst(first_block).unwrap(); 156 Self { 157 block: first_block, 158 inst: first_inst, 159 } 160 } 161 } 162 163 impl Mutator for ReplaceInstWithConst { 164 fn name(&self) -> &'static str { 165 "replace inst with const" 166 } 167 168 fn mutation_count(&self, func: &Function) -> usize { 169 inst_count(func) 170 } 171 172 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 173 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map( 174 |(_prev_block, prev_inst)| { 175 let num_results = func.dfg.inst_results(prev_inst).len(); 176 177 let opcode = func.dfg.insts[prev_inst].opcode(); 178 if num_results == 0 179 || opcode == ir::Opcode::Iconst 180 || opcode == ir::Opcode::F32const 181 || opcode == ir::Opcode::F64const 182 { 183 return (func, format!(""), ProgressStatus::Skip); 184 } 185 186 // We replace a i128 const with a uextend+iconst, so we need to match that here 187 // to avoid processing those multiple times 188 if opcode == ir::Opcode::Uextend { 189 let ret_ty = func.dfg.value_type(func.dfg.first_result(prev_inst)); 190 let is_uextend_i128 = ret_ty == I128; 191 192 let arg = func.dfg.inst_args(prev_inst)[0]; 193 let arg_def = func.dfg.value_def(arg); 194 let arg_is_iconst = arg_def 195 .inst() 196 .map(|inst| func.dfg.insts[inst].opcode() == ir::Opcode::Iconst) 197 .unwrap_or(false); 198 199 if is_uextend_i128 && arg_is_iconst { 200 return (func, format!(""), ProgressStatus::Skip); 201 } 202 } 203 204 // At least 2 results. Replace each instruction with as many const instructions as 205 // there are results. 206 let mut pos = FuncCursor::new(&mut func).at_inst(prev_inst); 207 208 // Copy result SSA names into our own vector; otherwise we couldn't mutably borrow pos 209 // in the loop below. 210 let results = pos.func.dfg.inst_results(prev_inst).to_vec(); 211 212 // Detach results from the previous instruction, since we're going to reuse them. 213 pos.func.dfg.clear_results(prev_inst); 214 215 let mut inst_names = Vec::new(); 216 for r in &results { 217 let new_inst_name = replace_with_const(&mut pos, *r); 218 inst_names.push(new_inst_name); 219 } 220 221 // Remove the instruction. 222 assert_eq!(pos.remove_inst(), prev_inst); 223 224 let progress = if results.len() == 1 { 225 ProgressStatus::Changed 226 } else { 227 ProgressStatus::ExpandedOrShrinked 228 }; 229 230 ( 231 func, 232 format!("Replace inst {} with {}", prev_inst, inst_names.join(" / ")), 233 progress, 234 ) 235 }, 236 ) 237 } 238 } 239 240 /// Try to replace instructions with `trap`. 241 struct ReplaceInstWithTrap { 242 block: Block, 243 inst: Inst, 244 } 245 246 impl ReplaceInstWithTrap { 247 fn new(func: &Function) -> Self { 248 let first_block = func.layout.entry_block().unwrap(); 249 let first_inst = func.layout.first_inst(first_block).unwrap(); 250 Self { 251 block: first_block, 252 inst: first_inst, 253 } 254 } 255 } 256 257 impl Mutator for ReplaceInstWithTrap { 258 fn name(&self) -> &'static str { 259 "replace inst with trap" 260 } 261 262 fn mutation_count(&self, func: &Function) -> usize { 263 inst_count(func) 264 } 265 266 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 267 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map( 268 |(_prev_block, prev_inst)| { 269 let status = if func.dfg.insts[prev_inst].opcode() == ir::Opcode::Trap { 270 ProgressStatus::Skip 271 } else { 272 func.dfg.replace(prev_inst).trap(TrapCode::User(0)); 273 ProgressStatus::Changed 274 }; 275 (func, format!("Replace inst {prev_inst} with trap"), status) 276 }, 277 ) 278 } 279 } 280 281 /// Try to move instructions to entry block. 282 struct MoveInstToEntryBlock { 283 block: Block, 284 inst: Inst, 285 } 286 287 impl MoveInstToEntryBlock { 288 fn new(func: &Function) -> Self { 289 let first_block = func.layout.entry_block().unwrap(); 290 let first_inst = func.layout.first_inst(first_block).unwrap(); 291 Self { 292 block: first_block, 293 inst: first_inst, 294 } 295 } 296 } 297 298 impl Mutator for MoveInstToEntryBlock { 299 fn name(&self) -> &'static str { 300 "move inst to entry block" 301 } 302 303 fn mutation_count(&self, func: &Function) -> usize { 304 inst_count(func) 305 } 306 307 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 308 next_inst_ret_prev(&func, &mut self.block, &mut self.inst).map(|(prev_block, prev_inst)| { 309 // Don't move instructions that are already in entry block 310 // and instructions that end blocks. 311 let first_block = func.layout.entry_block().unwrap(); 312 if first_block == prev_block || self.block != prev_block { 313 return ( 314 func, 315 format!("did nothing for {prev_inst}"), 316 ProgressStatus::Skip, 317 ); 318 } 319 320 let last_inst_of_first_block = func.layout.last_inst(first_block).unwrap(); 321 func.layout.remove_inst(prev_inst); 322 func.layout.insert_inst(prev_inst, last_inst_of_first_block); 323 324 ( 325 func, 326 format!("Move inst {prev_inst} to entry block"), 327 ProgressStatus::ExpandedOrShrinked, 328 ) 329 }) 330 } 331 } 332 333 /// Try to remove a block. 334 struct RemoveBlock { 335 block: Block, 336 } 337 338 impl RemoveBlock { 339 fn new(func: &Function) -> Self { 340 Self { 341 block: func.layout.entry_block().unwrap(), 342 } 343 } 344 } 345 346 impl Mutator for RemoveBlock { 347 fn name(&self) -> &'static str { 348 "remove block" 349 } 350 351 fn mutation_count(&self, func: &Function) -> usize { 352 block_count(func) 353 } 354 355 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 356 func.layout.next_block(self.block).map(|next_block| { 357 self.block = next_block; 358 while let Some(inst) = func.layout.last_inst(self.block) { 359 func.layout.remove_inst(inst); 360 } 361 func.layout.remove_block(self.block); 362 ( 363 func, 364 format!("Remove block {next_block}"), 365 ProgressStatus::ExpandedOrShrinked, 366 ) 367 }) 368 } 369 } 370 371 /// Try to replace the block params with constants. 372 struct ReplaceBlockParamWithConst { 373 block: Block, 374 params_remaining: usize, 375 } 376 377 impl ReplaceBlockParamWithConst { 378 fn new(func: &Function) -> Self { 379 let first_block = func.layout.entry_block().unwrap(); 380 Self { 381 block: first_block, 382 params_remaining: func.dfg.num_block_params(first_block), 383 } 384 } 385 } 386 387 impl Mutator for ReplaceBlockParamWithConst { 388 fn name(&self) -> &'static str { 389 "replace block parameter with const" 390 } 391 392 fn mutation_count(&self, func: &Function) -> usize { 393 func.layout 394 .blocks() 395 .map(|block| func.dfg.num_block_params(block)) 396 .sum() 397 } 398 399 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 400 while self.params_remaining == 0 { 401 self.block = func.layout.next_block(self.block)?; 402 self.params_remaining = func.dfg.num_block_params(self.block); 403 } 404 405 self.params_remaining -= 1; 406 let param_index = self.params_remaining; 407 408 let param = func.dfg.block_params(self.block)[param_index]; 409 func.dfg.remove_block_param(param); 410 411 let first_inst = func.layout.first_inst(self.block).unwrap(); 412 let mut pos = FuncCursor::new(&mut func).at_inst(first_inst); 413 let new_inst_name = replace_with_const(&mut pos, param); 414 415 let mut cfg = ControlFlowGraph::new(); 416 cfg.compute(&func); 417 418 // Remove parameters in branching instructions that point to this block 419 for pred in cfg.pred_iter(self.block) { 420 let dfg = &mut func.dfg; 421 for branch in dfg.insts[pred.inst].branch_destination_mut(&mut dfg.jump_tables) { 422 if branch.block(&dfg.value_lists) == self.block { 423 branch.remove(param_index, &mut dfg.value_lists); 424 } 425 } 426 } 427 428 if Some(self.block) == func.layout.entry_block() { 429 // Entry block params must match function params 430 func.signature.params.remove(param_index); 431 } 432 433 Some(( 434 func, 435 format!( 436 "Replaced param {} of {} by {}", 437 param, self.block, new_inst_name 438 ), 439 ProgressStatus::ExpandedOrShrinked, 440 )) 441 } 442 } 443 444 /// Try to remove unused entities. 445 struct RemoveUnusedEntities { 446 kind: u32, 447 } 448 449 impl RemoveUnusedEntities { 450 fn new() -> Self { 451 Self { kind: 0 } 452 } 453 } 454 455 impl Mutator for RemoveUnusedEntities { 456 fn name(&self) -> &'static str { 457 "remove unused entities" 458 } 459 460 fn mutation_count(&self, _func: &Function) -> usize { 461 4 462 } 463 464 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 465 let name = match self.kind { 466 0 => { 467 let mut ext_func_usage_map = HashMap::new(); 468 for block in func.layout.blocks() { 469 for inst in func.layout.block_insts(block) { 470 match func.dfg.insts[inst] { 471 // Add new cases when there are new instruction formats taking a `FuncRef`. 472 InstructionData::Call { func_ref, .. } 473 | InstructionData::FuncAddr { func_ref, .. } => { 474 ext_func_usage_map 475 .entry(func_ref) 476 .or_insert_with(Vec::new) 477 .push(inst); 478 } 479 _ => {} 480 } 481 } 482 } 483 484 let mut ext_funcs = PrimaryMap::new(); 485 486 for (func_ref, ext_func_data) in func.dfg.ext_funcs.clone().into_iter() { 487 if let Some(func_ref_usage) = ext_func_usage_map.get(&func_ref) { 488 let new_func_ref = ext_funcs.push(ext_func_data.clone()); 489 for &inst in func_ref_usage { 490 match func.dfg.insts[inst] { 491 // Keep in sync with the above match. 492 InstructionData::Call { 493 ref mut func_ref, .. 494 } 495 | InstructionData::FuncAddr { 496 ref mut func_ref, .. 497 } => { 498 *func_ref = new_func_ref; 499 } 500 _ => unreachable!(), 501 } 502 } 503 } 504 } 505 506 func.dfg.ext_funcs = ext_funcs; 507 508 "Remove unused ext funcs" 509 } 510 1 => { 511 #[derive(Copy, Clone)] 512 enum SigRefUser { 513 Instruction(Inst), 514 ExtFunc(FuncRef), 515 } 516 517 let mut signatures_usage_map = HashMap::new(); 518 for block in func.layout.blocks() { 519 for inst in func.layout.block_insts(block) { 520 // Add new cases when there are new instruction formats taking a `SigRef`. 521 if let InstructionData::CallIndirect { sig_ref, .. } = func.dfg.insts[inst] 522 { 523 signatures_usage_map 524 .entry(sig_ref) 525 .or_insert_with(Vec::new) 526 .push(SigRefUser::Instruction(inst)); 527 } 528 } 529 } 530 for (func_ref, ext_func_data) in func.dfg.ext_funcs.iter() { 531 signatures_usage_map 532 .entry(ext_func_data.signature) 533 .or_insert_with(Vec::new) 534 .push(SigRefUser::ExtFunc(func_ref)); 535 } 536 537 let mut signatures = PrimaryMap::new(); 538 539 for (sig_ref, sig_data) in func.dfg.signatures.clone().into_iter() { 540 if let Some(sig_ref_usage) = signatures_usage_map.get(&sig_ref) { 541 let new_sig_ref = signatures.push(sig_data.clone()); 542 for &sig_ref_user in sig_ref_usage { 543 match sig_ref_user { 544 SigRefUser::Instruction(inst) => match func.dfg.insts[inst] { 545 // Keep in sync with the above match. 546 InstructionData::CallIndirect { 547 ref mut sig_ref, .. 548 } => { 549 *sig_ref = new_sig_ref; 550 } 551 _ => unreachable!(), 552 }, 553 SigRefUser::ExtFunc(func_ref) => { 554 func.dfg.ext_funcs[func_ref].signature = new_sig_ref; 555 } 556 } 557 } 558 } 559 } 560 561 func.dfg.signatures = signatures; 562 563 "Remove unused signatures" 564 } 565 2 => { 566 let mut stack_slot_usage_map = HashMap::new(); 567 for block in func.layout.blocks() { 568 for inst in func.layout.block_insts(block) { 569 match func.dfg.insts[inst] { 570 // Add new cases when there are new instruction formats taking a `StackSlot`. 571 InstructionData::StackLoad { stack_slot, .. } 572 | InstructionData::StackStore { stack_slot, .. } => { 573 stack_slot_usage_map 574 .entry(stack_slot) 575 .or_insert_with(Vec::new) 576 .push(inst); 577 } 578 579 _ => {} 580 } 581 } 582 } 583 584 let mut stack_slots = StackSlots::new(); 585 586 for (stack_slot, stack_slot_data) in func.sized_stack_slots.clone().iter() { 587 if let Some(stack_slot_usage) = stack_slot_usage_map.get(&stack_slot) { 588 let new_stack_slot = stack_slots.push(stack_slot_data.clone()); 589 for &inst in stack_slot_usage { 590 match &mut func.dfg.insts[inst] { 591 // Keep in sync with the above match. 592 InstructionData::StackLoad { stack_slot, .. } 593 | InstructionData::StackStore { stack_slot, .. } => { 594 *stack_slot = new_stack_slot; 595 } 596 _ => unreachable!(), 597 } 598 } 599 } 600 } 601 602 func.sized_stack_slots = stack_slots; 603 604 "Remove unused stack slots" 605 } 606 3 => { 607 let mut global_value_usage_map = HashMap::new(); 608 for block in func.layout.blocks() { 609 for inst in func.layout.block_insts(block) { 610 // Add new cases when there are new instruction formats taking a `GlobalValue`. 611 if let InstructionData::UnaryGlobalValue { global_value, .. } = 612 func.dfg.insts[inst] 613 { 614 global_value_usage_map 615 .entry(global_value) 616 .or_insert_with(Vec::new) 617 .push(inst); 618 } 619 } 620 } 621 622 for (_global_value, global_value_data) in func.global_values.iter() { 623 match *global_value_data { 624 GlobalValueData::VMContext | GlobalValueData::Symbol { .. } => {} 625 // These can create cyclic references, which cause complications. Just skip 626 // the global value removal for now. 627 // FIXME Handle them in a better way. 628 GlobalValueData::Load { .. } 629 | GlobalValueData::IAddImm { .. } 630 | GlobalValueData::DynScaleTargetConst { .. } => return None, 631 } 632 } 633 634 let mut global_values = PrimaryMap::new(); 635 636 for (global_value, global_value_data) in func.global_values.clone().into_iter() { 637 if let Some(global_value_usage) = global_value_usage_map.get(&global_value) { 638 let new_global_value = global_values.push(global_value_data.clone()); 639 for &inst in global_value_usage { 640 match &mut func.dfg.insts[inst] { 641 // Keep in sync with the above match. 642 InstructionData::UnaryGlobalValue { global_value, .. } => { 643 *global_value = new_global_value; 644 } 645 _ => unreachable!(), 646 } 647 } 648 } 649 } 650 651 func.global_values = global_values; 652 653 "Remove unused global values" 654 } 655 _ => return None, 656 }; 657 self.kind += 1; 658 Some((func, name.to_owned(), ProgressStatus::Changed)) 659 } 660 } 661 662 struct MergeBlocks { 663 block: Block, 664 prev_block: Option<Block>, 665 } 666 667 impl MergeBlocks { 668 fn new(func: &Function) -> Self { 669 Self { 670 block: func.layout.entry_block().unwrap(), 671 prev_block: None, 672 } 673 } 674 } 675 676 impl Mutator for MergeBlocks { 677 fn name(&self) -> &'static str { 678 "merge blocks" 679 } 680 681 fn mutation_count(&self, func: &Function) -> usize { 682 // N blocks may result in at most N-1 merges. 683 block_count(func) - 1 684 } 685 686 fn mutate(&mut self, mut func: Function) -> Option<(Function, String, ProgressStatus)> { 687 let block = match func.layout.next_block(self.block) { 688 Some(block) => block, 689 None => return None, 690 }; 691 692 self.block = block; 693 694 let mut cfg = ControlFlowGraph::new(); 695 cfg.compute(&func); 696 697 if cfg.pred_iter(block).count() != 1 { 698 return Some(( 699 func, 700 format!("did nothing for {block}"), 701 ProgressStatus::Skip, 702 )); 703 } 704 705 let pred = cfg.pred_iter(block).next().unwrap(); 706 707 // If the branch instruction that lead us to this block wasn't an unconditional jump, then 708 // we have a conditional jump sequence that we should not break. 709 let branch_dests = func.dfg.insts[pred.inst].branch_destination(&func.dfg.jump_tables); 710 if branch_dests.len() != 1 { 711 return Some(( 712 func, 713 format!("did nothing for {block}"), 714 ProgressStatus::Skip, 715 )); 716 } 717 718 let branch_args = branch_dests[0].args_slice(&func.dfg.value_lists).to_vec(); 719 720 // TODO: should we free the entity list associated with the block params? 721 let block_params = func 722 .dfg 723 .detach_block_params(block) 724 .as_slice(&func.dfg.value_lists) 725 .to_vec(); 726 727 assert_eq!(block_params.len(), branch_args.len()); 728 729 // If there were any block parameters in block, then the last instruction in pred will 730 // fill these parameters. Make the block params aliases of the terminator arguments. 731 for (block_param, arg) in block_params.into_iter().zip(branch_args) { 732 if block_param != arg { 733 func.dfg.change_to_alias(block_param, arg); 734 } 735 } 736 737 // Remove the terminator branch to the current block. 738 func.layout.remove_inst(pred.inst); 739 740 // Move all the instructions to the predecessor. 741 while let Some(inst) = func.layout.first_inst(block) { 742 func.layout.remove_inst(inst); 743 func.layout.append_inst(inst, pred.block); 744 } 745 746 // Remove the predecessor block. 747 func.layout.remove_block(block); 748 749 // Record the previous block: if we caused a crash (as signaled by a call to did_crash), then 750 // we'll start back to this block. 751 self.prev_block = Some(pred.block); 752 753 Some(( 754 func, 755 format!("merged {} and {}", pred.block, block), 756 ProgressStatus::ExpandedOrShrinked, 757 )) 758 } 759 760 fn did_crash(&mut self) { 761 self.block = self.prev_block.unwrap(); 762 } 763 } 764 765 fn replace_with_const(pos: &mut FuncCursor, param: Value) -> &'static str { 766 let ty = pos.func.dfg.value_type(param); 767 if ty == F32 { 768 pos.ins().with_result(param).f32const(0.0); 769 "f32const" 770 } else if ty == F64 { 771 pos.ins().with_result(param).f64const(0.0); 772 "f64const" 773 } else if ty.is_ref() { 774 pos.ins().with_result(param).null(ty); 775 "null" 776 } else if ty.is_vector() { 777 let zero_data = vec![0; ty.bytes() as usize].into(); 778 let zero_handle = pos.func.dfg.constants.insert(zero_data); 779 pos.ins().with_result(param).vconst(ty, zero_handle); 780 "vconst" 781 } else if ty == I128 { 782 let res = pos.ins().iconst(I64, 0); 783 pos.ins().with_result(param).uextend(I128, res); 784 "iconst+uextend" 785 } else { 786 // Default to an integer type and possibly create verifier error 787 pos.ins().with_result(param).iconst(ty, 0); 788 "iconst" 789 } 790 } 791 792 fn next_inst_ret_prev( 793 func: &Function, 794 block: &mut Block, 795 inst: &mut Inst, 796 ) -> Option<(Block, Inst)> { 797 let prev = (*block, *inst); 798 if let Some(next_inst) = func.layout.next_inst(*inst) { 799 *inst = next_inst; 800 return Some(prev); 801 } 802 if let Some(next_block) = func.layout.next_block(*block) { 803 *block = next_block; 804 *inst = func.layout.first_inst(*block).expect("no inst"); 805 return Some(prev); 806 } 807 None 808 } 809 810 fn block_count(func: &Function) -> usize { 811 func.layout.blocks().count() 812 } 813 814 fn inst_count(func: &Function) -> usize { 815 func.layout 816 .blocks() 817 .map(|block| func.layout.block_insts(block).count()) 818 .sum() 819 } 820 821 /// Resolve aliases only if function still crashes after this. 822 fn try_resolve_aliases(context: &mut CrashCheckContext, func: &mut Function) { 823 let mut func_with_resolved_aliases = func.clone(); 824 func_with_resolved_aliases.dfg.resolve_all_aliases(); 825 if let CheckResult::Crash(_) = context.check_for_crash(&func_with_resolved_aliases) { 826 *func = func_with_resolved_aliases; 827 } 828 } 829 830 /// Remove sourcelocs if the function still crashes after they are removed, to make the reduced clif IR easier to read. 831 fn try_remove_srclocs(context: &mut CrashCheckContext, func: &mut Function) { 832 let mut func_with_removed_sourcelocs = func.clone(); 833 func_with_removed_sourcelocs.srclocs.clear(); 834 if let CheckResult::Crash(_) = context.check_for_crash(&func_with_removed_sourcelocs) { 835 *func = func_with_removed_sourcelocs; 836 } 837 } 838 839 fn reduce(isa: &dyn TargetIsa, mut func: Function, verbose: bool) -> Result<(Function, String)> { 840 let mut context = CrashCheckContext::new(isa); 841 842 if let CheckResult::Succeed = context.check_for_crash(&func) { 843 anyhow::bail!("Given function compiled successfully or gave a verifier error."); 844 } 845 846 try_resolve_aliases(&mut context, &mut func); 847 try_remove_srclocs(&mut context, &mut func); 848 849 let progress_bar = ProgressBar::with_draw_target(0, ProgressDrawTarget::stdout()); 850 progress_bar.set_style( 851 ProgressStyle::default_bar().template("{bar:60} {prefix:40} {pos:>4}/{len:>4} {msg}"), 852 ); 853 854 for pass_idx in 0..100 { 855 let mut should_keep_reducing = false; 856 let mut phase = 0; 857 858 loop { 859 let mut mutator: Box<dyn Mutator> = match phase { 860 0 => Box::new(RemoveInst::new(&func)), 861 1 => Box::new(ReplaceInstWithConst::new(&func)), 862 2 => Box::new(ReplaceInstWithTrap::new(&func)), 863 3 => Box::new(MoveInstToEntryBlock::new(&func)), 864 4 => Box::new(RemoveBlock::new(&func)), 865 5 => Box::new(ReplaceBlockParamWithConst::new(&func)), 866 6 => Box::new(RemoveUnusedEntities::new()), 867 7 => Box::new(MergeBlocks::new(&func)), 868 _ => break, 869 }; 870 871 progress_bar.set_prefix(&format!("pass {} phase {}", pass_idx, mutator.name())); 872 progress_bar.set_length(mutator.mutation_count(&func) as u64); 873 874 // Reset progress bar. 875 progress_bar.set_position(0); 876 progress_bar.set_draw_delta(0); 877 878 for _ in 0..10000 { 879 progress_bar.inc(1); 880 881 let (mutated_func, msg, mutation_kind) = match mutator.mutate(func.clone()) { 882 Some(res) => res, 883 None => { 884 break; 885 } 886 }; 887 888 if let ProgressStatus::Skip = mutation_kind { 889 // The mutator didn't change anything, but we want to try more mutator 890 // iterations. 891 continue; 892 } 893 894 progress_bar.set_message(&msg); 895 896 match context.check_for_crash(&mutated_func) { 897 CheckResult::Succeed => { 898 // Mutating didn't hit the problem anymore, discard changes. 899 continue; 900 } 901 CheckResult::Crash(_) => { 902 // Panic remained while mutating, make changes definitive. 903 func = mutated_func; 904 905 // Notify the mutator that the mutation was successful. 906 mutator.did_crash(); 907 908 let verb = match mutation_kind { 909 ProgressStatus::ExpandedOrShrinked => { 910 should_keep_reducing = true; 911 "shrink" 912 } 913 ProgressStatus::Changed => "changed", 914 ProgressStatus::Skip => unreachable!(), 915 }; 916 if verbose { 917 progress_bar.println(format!("{msg}: {verb}")); 918 } 919 } 920 } 921 } 922 923 phase += 1; 924 } 925 926 progress_bar.println(format!( 927 "After pass {}, remaining insts/blocks: {}/{} ({})", 928 pass_idx, 929 inst_count(&func), 930 block_count(&func), 931 if should_keep_reducing { 932 "will keep reducing" 933 } else { 934 "stop reducing" 935 } 936 )); 937 938 if !should_keep_reducing { 939 // No new shrinking opportunities have been found this pass. This means none will ever 940 // be found. Skip the rest of the passes over the function. 941 break; 942 } 943 } 944 945 try_resolve_aliases(&mut context, &mut func); 946 progress_bar.finish(); 947 948 let crash_msg = match context.check_for_crash(&func) { 949 CheckResult::Succeed => unreachable!("Used to crash, but doesn't anymore???"), 950 CheckResult::Crash(crash_msg) => crash_msg, 951 }; 952 953 Ok((func, crash_msg)) 954 } 955 956 struct CrashCheckContext<'a> { 957 /// Cached `Context`, to prevent repeated allocation. 958 context: Context, 959 960 /// Cached code memory, to prevent repeated allocation. 961 code_memory: Vec<u8>, 962 963 /// The target isa to compile for. 964 isa: &'a dyn TargetIsa, 965 } 966 967 fn get_panic_string(panic: Box<dyn std::any::Any>) -> String { 968 let panic = match panic.downcast::<&'static str>() { 969 Ok(panic_msg) => { 970 return panic_msg.to_string(); 971 } 972 Err(panic) => panic, 973 }; 974 match panic.downcast::<String>() { 975 Ok(panic_msg) => *panic_msg, 976 Err(_) => "Box<Any>".to_string(), 977 } 978 } 979 980 enum CheckResult { 981 /// The function compiled fine, or the verifier noticed an error. 982 Succeed, 983 984 /// The compilation of the function panicked. 985 Crash(String), 986 } 987 988 impl<'a> CrashCheckContext<'a> { 989 fn new(isa: &'a dyn TargetIsa) -> Self { 990 CrashCheckContext { 991 context: Context::new(), 992 code_memory: Vec::new(), 993 isa, 994 } 995 } 996 997 #[cfg_attr(test, allow(unreachable_code))] 998 fn check_for_crash(&mut self, func: &Function) -> CheckResult { 999 self.context.clear(); 1000 self.code_memory.clear(); 1001 1002 self.context.func = func.clone(); 1003 1004 use std::io::Write; 1005 std::io::stdout().flush().unwrap(); // Flush stdout to sync with panic messages on stderr 1006 1007 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 1008 cranelift_codegen::verifier::verify_function(&func, self.isa).err() 1009 })) { 1010 Ok(Some(_)) => return CheckResult::Succeed, 1011 Ok(None) => {} 1012 // The verifier panicked. Compiling it will probably give the same panic. 1013 // We treat it as succeeding to make it possible to reduce for the actual error. 1014 // FIXME prevent verifier panic on removing block0. 1015 Err(_) => return CheckResult::Succeed, 1016 } 1017 1018 #[cfg(test)] 1019 { 1020 // For testing purposes we emulate a panic caused by the existence of 1021 // a `call` instruction. 1022 let contains_call = func.layout.blocks().any(|block| { 1023 func.layout 1024 .block_insts(block) 1025 .any(|inst| match func.dfg.insts[inst] { 1026 InstructionData::Call { .. } => true, 1027 _ => false, 1028 }) 1029 }); 1030 if contains_call { 1031 return CheckResult::Crash("test crash".to_string()); 1032 } else { 1033 return CheckResult::Succeed; 1034 } 1035 } 1036 1037 let old_panic_hook = std::panic::take_hook(); 1038 std::panic::set_hook(Box::new(|_| {})); // silence panics 1039 1040 let res = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 1041 let _ = self.context.compile_and_emit( 1042 self.isa, 1043 &mut self.code_memory, 1044 &mut Default::default(), 1045 ); 1046 })) { 1047 Ok(()) => CheckResult::Succeed, 1048 Err(err) => CheckResult::Crash(get_panic_string(err)), 1049 }; 1050 1051 std::panic::set_hook(old_panic_hook); 1052 1053 res 1054 } 1055 } 1056 1057 #[cfg(test)] 1058 mod tests { 1059 use super::*; 1060 1061 fn run_test(test_str: &str, expected_str: &str) { 1062 let test_file = parse_test(test_str, ParseOptions::default()).unwrap(); 1063 1064 // If we have an isa from the command-line, use that. Otherwise if the 1065 // file contains a unique isa, use that. 1066 let isa = test_file.isa_spec.unique_isa().expect("Unknown isa"); 1067 1068 for (func, _) in test_file.functions { 1069 let (reduced_func, crash_msg) = 1070 reduce(isa, func, false).expect("Couldn't reduce test case"); 1071 assert_eq!(crash_msg, "test crash"); 1072 1073 let (func_reduced_twice, crash_msg) = 1074 reduce(isa, reduced_func.clone(), false).expect("Couldn't re-reduce test case"); 1075 assert_eq!(crash_msg, "test crash"); 1076 1077 assert_eq!( 1078 block_count(&func_reduced_twice), 1079 block_count(&reduced_func), 1080 "reduction wasn't maximal for blocks" 1081 ); 1082 assert_eq!( 1083 inst_count(&func_reduced_twice), 1084 inst_count(&reduced_func), 1085 "reduction wasn't maximal for insts" 1086 ); 1087 1088 let actual_ir = format!("{reduced_func}"); 1089 let expected_ir = expected_str.replace("\r\n", "\n"); 1090 assert!( 1091 expected_ir == actual_ir, 1092 "Expected:\n{expected_ir}\nGot:\n{actual_ir}", 1093 ); 1094 } 1095 } 1096 1097 #[test] 1098 fn test_reduce() { 1099 const TEST: &str = include_str!("../tests/bugpoint_test.clif"); 1100 const EXPECTED: &str = include_str!("../tests/bugpoint_test_expected.clif"); 1101 run_test(TEST, EXPECTED); 1102 } 1103 1104 #[test] 1105 fn test_consts() { 1106 const TEST: &str = include_str!("../tests/bugpoint_consts.clif"); 1107 const EXPECTED: &str = include_str!("../tests/bugpoint_consts_expected.clif"); 1108 run_test(TEST, EXPECTED); 1109 } 1110 } 1111