Skip to content

Commit b5c782d

Browse files
committed
add successors and their formatter
1 parent 5e6b685 commit b5c782d

File tree

4 files changed

+172
-34
lines changed

4 files changed

+172
-34
lines changed

compiler/rustc_smir/src/rustc_smir/mod.rs

+11-10
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use rustc_target::abi::FieldIdx;
2020
use stable_mir::mir::alloc::GlobalAlloc;
2121
use stable_mir::mir::mono::{InstanceDef, StaticDef};
2222
use stable_mir::mir::{
23-
Body, ConstOperand, CopyNonOverlapping, Statement, UserTypeProjection, VarDebugInfoFragment,
24-
VariantIdx,
23+
Body, ConstOperand, CopyNonOverlapping, Statement, Terminator, UserTypeProjection,
24+
VarDebugInfoFragment, VariantIdx,
2525
};
2626
use stable_mir::ty::{
2727
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, ConstId, ConstantKind,
@@ -1196,7 +1196,6 @@ impl<'tcx> Stable<'tcx> for mir::InlineAsmOperand<'tcx> {
11961196
impl<'tcx> Stable<'tcx> for mir::Terminator<'tcx> {
11971197
type T = stable_mir::mir::Terminator;
11981198
fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T {
1199-
use stable_mir::mir::Terminator;
12001199
Terminator { kind: self.kind.stable(tables), span: self.source_info.span.stable(tables) }
12011200
}
12021201
}
@@ -1211,13 +1210,15 @@ impl<'tcx> Stable<'tcx> for mir::TerminatorKind<'tcx> {
12111210
}
12121211
mir::TerminatorKind::SwitchInt { discr, targets } => TerminatorKind::SwitchInt {
12131212
discr: discr.stable(tables),
1214-
targets: targets
1215-
.iter()
1216-
.map(|(value, target)| stable_mir::mir::SwitchTarget {
1217-
value,
1218-
target: target.as_usize(),
1219-
})
1220-
.collect(),
1213+
targets: {
1214+
let mut value_vec = Vec::new();
1215+
let mut target_vec = Vec::new();
1216+
targets.iter().for_each(|(value, target)| {
1217+
value_vec.push(value);
1218+
target_vec.push(target.as_usize());
1219+
});
1220+
stable_mir::mir::SwitchTargets { value: value_vec, targets: target_vec }
1221+
},
12211222
otherwise: targets.otherwise().as_usize(),
12221223
},
12231224
mir::TerminatorKind::UnwindResume => TerminatorKind::Resume,

compiler/stable_mir/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
//!
1717
//! The goal is to eventually be published on
1818
//! [crates.io](https://crates.io).
19-
19+
#![feature(type_alias_impl_trait)]
2020
use crate::mir::mono::{InstanceDef, StaticDef};
2121
use crate::mir::Body;
2222
use std::fmt;

compiler/stable_mir/src/mir/body.rs

+68-8
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ use crate::ty::{
33
AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, RigidTy, Ty, TyKind,
44
};
55
use crate::{Error, Opaque, Span, Symbol};
6-
use std::io;
7-
6+
use std::{io, slice};
87
/// The SMIR representation of a single function.
98
#[derive(Clone, Debug)]
109
pub struct Body {
@@ -83,7 +82,8 @@ impl Body {
8382
Ok(())
8483
})
8584
.collect::<Vec<_>>();
86-
writeln!(w, "{}", pretty_terminator(&block.terminator.kind))?;
85+
pretty_terminator(&block.terminator.kind, w)?;
86+
writeln!(w, "").unwrap();
8787
writeln!(w, " }}").unwrap();
8888
Ok(())
8989
})
@@ -101,7 +101,7 @@ pub struct LocalDecl {
101101
pub mutability: Mutability,
102102
}
103103

104-
#[derive(Clone, Debug)]
104+
#[derive(Clone, PartialEq, Eq, Debug)]
105105
pub struct BasicBlock {
106106
pub statements: Vec<Statement>,
107107
pub terminator: Terminator,
@@ -113,14 +113,22 @@ pub struct Terminator {
113113
pub span: Span,
114114
}
115115

116+
impl Terminator {
117+
pub fn successors(&self) -> Successors<'_> {
118+
self.kind.successors()
119+
}
120+
}
121+
122+
pub type Successors<'a> = impl Iterator<Item = usize> + 'a;
123+
116124
#[derive(Clone, Debug, Eq, PartialEq)]
117125
pub enum TerminatorKind {
118126
Goto {
119127
target: usize,
120128
},
121129
SwitchInt {
122130
discr: Operand,
123-
targets: Vec<SwitchTarget>,
131+
targets: SwitchTargets,
124132
otherwise: usize,
125133
},
126134
Resume,
@@ -157,6 +165,58 @@ pub enum TerminatorKind {
157165
},
158166
}
159167

168+
impl TerminatorKind {
169+
pub fn successors(&self) -> Successors<'_> {
170+
use self::TerminatorKind::*;
171+
match *self {
172+
Call { target: Some(t), unwind: UnwindAction::Cleanup(ref u), .. }
173+
| Drop { target: t, unwind: UnwindAction::Cleanup(ref u), .. }
174+
| Assert { target: t, unwind: UnwindAction::Cleanup(ref u), .. }
175+
| InlineAsm { destination: Some(t), unwind: UnwindAction::Cleanup(ref u), .. } => {
176+
Some(t).into_iter().chain(slice::from_ref(u).into_iter().copied())
177+
}
178+
Goto { target: t }
179+
| Call { target: None, unwind: UnwindAction::Cleanup(t), .. }
180+
| Call { target: Some(t), unwind: _, .. }
181+
| Drop { target: t, unwind: _, .. }
182+
| Assert { target: t, unwind: _, .. }
183+
| InlineAsm { destination: None, unwind: UnwindAction::Cleanup(t), .. }
184+
| InlineAsm { destination: Some(t), unwind: _, .. } => {
185+
Some(t).into_iter().chain((&[]).into_iter().copied())
186+
}
187+
188+
CoroutineDrop
189+
| Return
190+
| Resume
191+
| Abort
192+
| Unreachable
193+
| Call { target: None, unwind: _, .. }
194+
| InlineAsm { destination: None, unwind: _, .. } => {
195+
None.into_iter().chain((&[]).into_iter().copied())
196+
}
197+
SwitchInt { ref targets, .. } => {
198+
None.into_iter().chain(targets.targets.iter().copied())
199+
}
200+
}
201+
}
202+
203+
pub fn unwind(&self) -> Option<&UnwindAction> {
204+
match *self {
205+
TerminatorKind::Goto { .. }
206+
| TerminatorKind::Return
207+
| TerminatorKind::Unreachable
208+
| TerminatorKind::CoroutineDrop
209+
| TerminatorKind::Resume
210+
| TerminatorKind::Abort
211+
| TerminatorKind::SwitchInt { .. } => None,
212+
TerminatorKind::Call { ref unwind, .. }
213+
| TerminatorKind::Assert { ref unwind, .. }
214+
| TerminatorKind::Drop { ref unwind, .. }
215+
| TerminatorKind::InlineAsm { ref unwind, .. } => Some(unwind),
216+
}
217+
}
218+
}
219+
160220
#[derive(Clone, Debug, Eq, PartialEq)]
161221
pub struct InlineAsmOperand {
162222
pub in_value: Option<Operand>,
@@ -603,9 +663,9 @@ pub struct Constant {
603663
}
604664

605665
#[derive(Clone, Debug, Eq, PartialEq)]
606-
pub struct SwitchTarget {
607-
pub value: u128,
608-
pub target: usize,
666+
pub struct SwitchTargets {
667+
pub value: Vec<u128>,
668+
pub targets: Vec<usize>,
609669
}
610670

611671
#[derive(Copy, Clone, Debug, Eq, PartialEq)]

compiler/stable_mir/src/mir/pretty.rs

+92-15
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use crate::mir::{Operand, Rvalue, StatementKind};
1+
use std::io::Write;
2+
use std::{io, iter};
3+
4+
use crate::mir::{Operand, Rvalue, StatementKind, UnwindAction};
25
use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
36
use crate::{with, Body, CrateItem, Mutability};
47

@@ -71,21 +74,68 @@ pub fn pretty_statement(statement: &StatementKind) -> String {
7174
pretty
7275
}
7376

74-
pub fn pretty_terminator(terminator: &TerminatorKind) -> String {
77+
pub fn pretty_terminator<W: io::Write>(terminator: &TerminatorKind, w: &mut W) -> io::Result<()> {
78+
write!(w, "{}", pretty_terminator_head(terminator))?;
79+
let successor_count = terminator.successors().count();
80+
let labels = pretty_successor_labels(terminator);
81+
82+
let show_unwind = !matches!(terminator.unwind(), None | Some(UnwindAction::Cleanup(_)));
83+
let fmt_unwind = |fmt: &mut dyn Write| -> io::Result<()> {
84+
write!(fmt, "unwind ")?;
85+
match terminator.unwind() {
86+
None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
87+
Some(UnwindAction::Continue) => write!(fmt, "continue"),
88+
Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
89+
Some(UnwindAction::Terminate) => write!(fmt, "terminate"),
90+
}
91+
};
92+
93+
match (successor_count, show_unwind) {
94+
(0, false) => Ok(()),
95+
(0, true) => {
96+
write!(w, " -> ")?;
97+
fmt_unwind(w)?;
98+
Ok(())
99+
}
100+
(1, false) => {
101+
write!(w, " -> {:?}", terminator.successors().next().unwrap())?;
102+
Ok(())
103+
}
104+
_ => {
105+
write!(w, " -> [")?;
106+
for (i, target) in terminator.successors().enumerate() {
107+
if i > 0 {
108+
write!(w, ", ")?;
109+
}
110+
write!(w, "{}: {:?}", labels[i], target)?;
111+
}
112+
if show_unwind {
113+
write!(w, ", ")?;
114+
fmt_unwind(w)?;
115+
}
116+
write!(w, "]")
117+
}
118+
}?;
119+
120+
Ok(())
121+
}
122+
123+
pub fn pretty_terminator_head(terminator: &TerminatorKind) -> String {
124+
use self::TerminatorKind::*;
75125
let mut pretty = String::new();
76126
match terminator {
77-
TerminatorKind::Goto { .. } => format!(" goto"),
78-
TerminatorKind::SwitchInt { discr, .. } => {
127+
Goto { .. } => format!(" goto"),
128+
SwitchInt { discr, .. } => {
79129
format!(" switch({})", pretty_operand(discr))
80130
}
81-
TerminatorKind::Resume => format!(" resume"),
82-
TerminatorKind::Abort => format!(" abort"),
83-
TerminatorKind::Return => format!(" return"),
84-
TerminatorKind::Unreachable => format!(" unreachable"),
85-
TerminatorKind::Drop { place, .. } => format!(" drop({:?})", place.local),
86-
TerminatorKind::Call { func, args, destination, .. } => {
131+
Resume => format!(" resume"),
132+
Abort => format!(" abort"),
133+
Return => format!(" return"),
134+
Unreachable => format!(" unreachable"),
135+
Drop { place, .. } => format!(" drop(_{:?})", place.local),
136+
Call { func, args, destination, .. } => {
87137
pretty.push_str(" ");
88-
pretty.push_str(format!("{} = ", destination.local).as_str());
138+
pretty.push_str(format!("_{} = ", destination.local).as_str());
89139
pretty.push_str(&pretty_operand(func));
90140
pretty.push_str("(");
91141
args.iter().enumerate().for_each(|(i, arg)| {
@@ -97,18 +147,45 @@ pub fn pretty_terminator(terminator: &TerminatorKind) -> String {
97147
pretty.push_str(")");
98148
pretty
99149
}
100-
TerminatorKind::Assert { cond, expected, msg, target: _, unwind: _ } => {
150+
Assert { cond, expected, msg, target: _, unwind: _ } => {
101151
pretty.push_str(" assert(");
102152
if !expected {
103153
pretty.push_str("!");
104154
}
105-
pretty.push_str(&pretty_operand(cond));
155+
pretty.push_str(format!("{} bool),", &pretty_operand(cond)).as_str());
106156
pretty.push_str(&pretty_assert_message(msg));
107157
pretty.push_str(")");
108158
pretty
109159
}
110-
TerminatorKind::CoroutineDrop => format!(" coroutine_drop"),
111-
TerminatorKind::InlineAsm { .. } => todo!(),
160+
CoroutineDrop => format!(" coroutine_drop"),
161+
InlineAsm { .. } => todo!(),
162+
}
163+
}
164+
165+
pub fn pretty_successor_labels(terminator: &TerminatorKind) -> Vec<String> {
166+
use self::TerminatorKind::*;
167+
match terminator {
168+
Resume | Abort | Return | Unreachable | CoroutineDrop => vec![],
169+
Goto { .. } => vec!["".to_string()],
170+
SwitchInt { targets, .. } => targets
171+
.value
172+
.iter()
173+
.map(|target| format!("{}", target))
174+
.chain(iter::once("otherwise".into()))
175+
.collect(),
176+
Drop { unwind: UnwindAction::Cleanup(_), .. } => vec!["return".into(), "unwind".into()],
177+
Drop { unwind: _, .. } => vec!["return".into()],
178+
Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
179+
vec!["return".into(), "unwind".into()]
180+
}
181+
Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
182+
Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
183+
Call { target: None, unwind: _, .. } => vec![],
184+
Assert { unwind: UnwindAction::Cleanup(_), .. } => {
185+
vec!["success".into(), "unwind".into()]
186+
}
187+
Assert { unwind: _, .. } => vec!["success".into()],
188+
InlineAsm { .. } => todo!(),
112189
}
113190
}
114191

0 commit comments

Comments
 (0)