clif_util/
bugpoint.rs

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