rustc_mir_transform/
add_call_guards.rs1use rustc_index::{Idx, IndexVec};
2use rustc_middle::mir::*;
3use rustc_middle::ty::TyCtxt;
4use tracing::debug;
5
6#[derive(PartialEq)]
7pub(super) enum AddCallGuards {
8 AllCallEdges,
9 CriticalCallEdges,
10}
11pub(super) use self::AddCallGuards::*;
12
13impl<'tcx> crate::MirPass<'tcx> for AddCallGuards {
34 fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
35 let mut pred_count = IndexVec::from_elem(0u8, &body.basic_blocks);
36 for (_, data) in body.basic_blocks.iter_enumerated() {
37 for succ in data.terminator().successors() {
38 pred_count[succ] = pred_count[succ].saturating_add(1);
39 }
40 }
41
42 let mut new_blocks = Vec::new();
44
45 let cur_len = body.basic_blocks.len();
46 let mut new_block = |source_info: SourceInfo, is_cleanup: bool, target: BasicBlock| {
47 let block = BasicBlockData {
48 statements: vec![],
49 is_cleanup,
50 terminator: Some(Terminator { source_info, kind: TerminatorKind::Goto { target } }),
51 };
52 let idx = cur_len + new_blocks.len();
53 new_blocks.push(block);
54 BasicBlock::new(idx)
55 };
56
57 for block in body.basic_blocks_mut() {
58 match block.terminator {
59 Some(Terminator {
60 kind: TerminatorKind::Call { target: Some(ref mut destination), unwind, .. },
61 source_info,
62 }) if pred_count[*destination] > 1
63 && (generates_invoke(unwind) || self == &AllCallEdges) =>
64 {
65 *destination = new_block(source_info, block.is_cleanup, *destination);
67 }
68 Some(Terminator {
69 kind:
70 TerminatorKind::InlineAsm {
71 asm_macro: InlineAsmMacro::Asm,
72 ref mut targets,
73 ref operands,
74 unwind,
75 ..
76 },
77 source_info,
78 }) if self == &CriticalCallEdges => {
79 let has_outputs = operands.iter().any(|op| {
80 matches!(op, InlineAsmOperand::InOut { .. } | InlineAsmOperand::Out { .. })
81 });
82 let has_labels =
83 operands.iter().any(|op| matches!(op, InlineAsmOperand::Label { .. }));
84 if has_outputs && (has_labels || generates_invoke(unwind)) {
85 for target in targets.iter_mut() {
86 if pred_count[*target] > 1 {
87 *target = new_block(source_info, block.is_cleanup, *target);
88 }
89 }
90 }
91 }
92 _ => {}
93 }
94 }
95
96 debug!("Broke {} N edges", new_blocks.len());
97
98 body.basic_blocks_mut().extend(new_blocks);
99 }
100
101 fn is_required(&self) -> bool {
102 true
103 }
104}
105
106fn generates_invoke(unwind: UnwindAction) -> bool {
108 match unwind {
109 UnwindAction::Continue | UnwindAction::Unreachable => false,
110 UnwindAction::Cleanup(_) | UnwindAction::Terminate(_) => true,
111 }
112}