Skip to content

Commit 578758a

Browse files
authored
Rollup merge of #118927 - celinval:smir-missing-info, r=compiler-errors
Erase late bound regions from `Instance::fn_sig()` and add a few more details to StableMIR APIs The Instance `fn_sig()` still included a late bound regions which needed a new compiler function in order to be erased. I've also bundled the following small fixes in this PR, let me know if you want me to isolate any of them. - Add missing `CoroutineKind::AsyncGen`. - Add optional spread argument to function body which is needed to properly analyze compiler shims. - Add a utility method to iterate over all locals together with their declaration. - Add a method to get the description of `AssertMessage`*. * For the last one, we could consider eventually calling the internal `AssertKind::description()` to avoid code duplication. However, we still don't have ways to convert `AssertMessage`, `Operand`, `Place` and others, in order to use that. The other downside of using the internal method is that it will panic for some of the variants. r ? `@ouz-a`
2 parents 1559dd2 + 6004386 commit 578758a

File tree

9 files changed

+95
-20
lines changed

9 files changed

+95
-20
lines changed

compiler/rustc_smir/src/rustc_smir/context.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
66
use rustc_middle::ty;
77
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
8-
use rustc_middle::ty::{GenericPredicates, Instance, ParamEnv, ScalarInt, ValTree};
8+
use rustc_middle::ty::{
9+
GenericPredicates, Instance, ParamEnv, ScalarInt, TypeVisitableExt, ValTree,
10+
};
911
use rustc_span::def_id::LOCAL_CRATE;
1012
use stable_mir::compiler_interface::Context;
1113
use stable_mir::mir::alloc::GlobalAlloc;
@@ -324,7 +326,8 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
324326
fn instance_ty(&self, def: InstanceDef) -> stable_mir::ty::Ty {
325327
let mut tables = self.0.borrow_mut();
326328
let instance = tables.instances[def];
327-
instance.ty(tables.tcx, ParamEnv::empty()).stable(&mut *tables)
329+
assert!(!instance.has_non_region_param(), "{instance:?} needs further substitution");
330+
instance.ty(tables.tcx, ParamEnv::reveal_all()).stable(&mut *tables)
328331
}
329332

330333
fn instance_def_id(&self, def: InstanceDef) -> stable_mir::DefId {

compiler/rustc_smir/src/rustc_smir/convert/mir.rs

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
3636
.collect(),
3737
self.arg_count,
3838
self.var_debug_info.iter().map(|info| info.stable(tables)).collect(),
39+
self.spread_arg.stable(tables),
3940
)
4041
}
4142
}

compiler/rustc_smir/src/rustc_smir/convert/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,9 @@ impl<'tcx> Stable<'tcx> for rustc_hir::CoroutineKind {
5757
stable_mir::mir::CoroutineKind::Gen(source.stable(tables))
5858
}
5959
CoroutineKind::Coroutine => stable_mir::mir::CoroutineKind::Coroutine,
60-
CoroutineKind::AsyncGen(_) => todo!(),
60+
CoroutineKind::AsyncGen(source) => {
61+
stable_mir::mir::CoroutineKind::AsyncGen(source.stable(tables))
62+
}
6163
}
6264
}
6365
}

compiler/stable_mir/src/mir/body.rs

+68-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ pub struct Body {
2222

2323
/// Debug information pertaining to user variables, including captures.
2424
pub var_debug_info: Vec<VarDebugInfo>,
25+
26+
/// Mark an argument (which must be a tuple) as getting passed as its individual components.
27+
///
28+
/// This is used for the "rust-call" ABI such as closures.
29+
pub(super) spread_arg: Option<Local>,
2530
}
2631

2732
pub type BasicBlockIdx = usize;
@@ -36,14 +41,15 @@ impl Body {
3641
locals: LocalDecls,
3742
arg_count: usize,
3843
var_debug_info: Vec<VarDebugInfo>,
44+
spread_arg: Option<Local>,
3945
) -> Self {
4046
// If locals doesn't contain enough entries, it can lead to panics in
4147
// `ret_local`, `arg_locals`, and `inner_locals`.
4248
assert!(
4349
locals.len() > arg_count,
4450
"A Body must contain at least a local for the return value and each of the function's arguments"
4551
);
46-
Self { blocks, locals, arg_count, var_debug_info }
52+
Self { blocks, locals, arg_count, var_debug_info, spread_arg }
4753
}
4854

4955
/// Return local that holds this function's return value.
@@ -75,6 +81,11 @@ impl Body {
7581
self.locals.get(local)
7682
}
7783

84+
/// Get an iterator for all local declarations.
85+
pub fn local_decls(&self) -> impl Iterator<Item = (Local, &LocalDecl)> {
86+
self.locals.iter().enumerate()
87+
}
88+
7889
pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
7990
writeln!(w, "{}", function_body(self))?;
8091
self.blocks
@@ -98,6 +109,10 @@ impl Body {
98109
.collect::<Result<Vec<_>, _>>()?;
99110
Ok(())
100111
}
112+
113+
pub fn spread_arg(&self) -> Option<Local> {
114+
self.spread_arg
115+
}
101116
}
102117

103118
type LocalDecls = Vec<LocalDecl>;
@@ -248,6 +263,57 @@ pub enum AssertMessage {
248263
MisalignedPointerDereference { required: Operand, found: Operand },
249264
}
250265

266+
impl AssertMessage {
267+
pub fn description(&self) -> Result<&'static str, Error> {
268+
match self {
269+
AssertMessage::Overflow(BinOp::Add, _, _) => Ok("attempt to add with overflow"),
270+
AssertMessage::Overflow(BinOp::Sub, _, _) => Ok("attempt to subtract with overflow"),
271+
AssertMessage::Overflow(BinOp::Mul, _, _) => Ok("attempt to multiply with overflow"),
272+
AssertMessage::Overflow(BinOp::Div, _, _) => Ok("attempt to divide with overflow"),
273+
AssertMessage::Overflow(BinOp::Rem, _, _) => {
274+
Ok("attempt to calculate the remainder with overflow")
275+
}
276+
AssertMessage::OverflowNeg(_) => Ok("attempt to negate with overflow"),
277+
AssertMessage::Overflow(BinOp::Shr, _, _) => Ok("attempt to shift right with overflow"),
278+
AssertMessage::Overflow(BinOp::Shl, _, _) => Ok("attempt to shift left with overflow"),
279+
AssertMessage::Overflow(op, _, _) => Err(error!("`{:?}` cannot overflow", op)),
280+
AssertMessage::DivisionByZero(_) => Ok("attempt to divide by zero"),
281+
AssertMessage::RemainderByZero(_) => {
282+
Ok("attempt to calculate the remainder with a divisor of zero")
283+
}
284+
AssertMessage::ResumedAfterReturn(CoroutineKind::Coroutine) => {
285+
Ok("coroutine resumed after completion")
286+
}
287+
AssertMessage::ResumedAfterReturn(CoroutineKind::Async(_)) => {
288+
Ok("`async fn` resumed after completion")
289+
}
290+
AssertMessage::ResumedAfterReturn(CoroutineKind::Gen(_)) => {
291+
Ok("`async gen fn` resumed after completion")
292+
}
293+
AssertMessage::ResumedAfterReturn(CoroutineKind::AsyncGen(_)) => {
294+
Ok("`gen fn` should just keep returning `AssertMessage::None` after completion")
295+
}
296+
AssertMessage::ResumedAfterPanic(CoroutineKind::Coroutine) => {
297+
Ok("coroutine resumed after panicking")
298+
}
299+
AssertMessage::ResumedAfterPanic(CoroutineKind::Async(_)) => {
300+
Ok("`async fn` resumed after panicking")
301+
}
302+
AssertMessage::ResumedAfterPanic(CoroutineKind::Gen(_)) => {
303+
Ok("`async gen fn` resumed after panicking")
304+
}
305+
AssertMessage::ResumedAfterPanic(CoroutineKind::AsyncGen(_)) => {
306+
Ok("`gen fn` should just keep returning `AssertMessage::None` after panicking")
307+
}
308+
309+
AssertMessage::BoundsCheck { .. } => Ok("index out of bounds"),
310+
AssertMessage::MisalignedPointerDereference { .. } => {
311+
Ok("misaligned pointer dereference")
312+
}
313+
}
314+
}
315+
}
316+
251317
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
252318
pub enum BinOp {
253319
Add,
@@ -325,6 +391,7 @@ pub enum CoroutineKind {
325391
Async(CoroutineSource),
326392
Coroutine,
327393
Gen(CoroutineSource),
394+
AsyncGen(CoroutineSource),
328395
}
329396

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

compiler/stable_mir/src/mir/mono.rs

+1-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::crate_def::CrateDef;
22
use crate::mir::Body;
3-
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, FnSig, GenericArgs, IndexedVal, Ty};
3+
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty};
44
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol};
55
use std::fmt::{Debug, Formatter};
66

@@ -115,11 +115,6 @@ impl Instance {
115115
})
116116
}
117117

118-
/// Get this function signature with all types already instantiated.
119-
pub fn fn_sig(&self) -> FnSig {
120-
self.ty().kind().fn_sig().unwrap().skip_binder()
121-
}
122-
123118
/// Check whether this instance is an empty shim.
124119
///
125120
/// Allow users to check if this shim can be ignored when called directly.

compiler/stable_mir/src/mir/pretty.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,7 @@ pub fn pretty_assert_message(msg: &AssertMessage) -> String {
260260
);
261261
pretty
262262
}
263+
AssertMessage::Overflow(op, _, _) => unreachable!("`{:?}` cannot overflow", op),
263264
AssertMessage::OverflowNeg(op) => {
264265
let pretty_op = pretty_operand(op);
265266
pretty.push_str(
@@ -279,17 +280,15 @@ pub fn pretty_assert_message(msg: &AssertMessage) -> String {
279280
);
280281
pretty
281282
}
282-
AssertMessage::ResumedAfterReturn(_) => {
283-
format!("attempt to resume a generator after completion")
284-
}
285-
AssertMessage::ResumedAfterPanic(_) => format!("attempt to resume a panicked generator"),
286283
AssertMessage::MisalignedPointerDereference { required, found } => {
287284
let pretty_required = pretty_operand(required);
288285
let pretty_found = pretty_operand(found);
289286
pretty.push_str(format!("\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\",{pretty_required}, {pretty_found}").as_str());
290287
pretty
291288
}
292-
_ => todo!(),
289+
AssertMessage::ResumedAfterReturn(_) | AssertMessage::ResumedAfterPanic(_) => {
290+
msg.description().unwrap().to_string()
291+
}
293292
}
294293
}
295294

compiler/stable_mir/src/mir/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ pub trait MirVisitor {
133133
}
134134

135135
fn super_body(&mut self, body: &Body) {
136-
let Body { blocks, locals: _, arg_count, var_debug_info } = body;
136+
let Body { blocks, locals: _, arg_count, var_debug_info, spread_arg: _ } = body;
137137

138138
for bb in blocks {
139139
self.visit_basic_block(bb);

compiler/stable_mir/src/ty.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ impl Debug for Ty {
2222
/// Constructors for `Ty`.
2323
impl Ty {
2424
/// Create a new type from a given kind.
25-
///
26-
/// Note that not all types may be supported at this point.
27-
fn from_rigid_kind(kind: RigidTy) -> Ty {
25+
pub fn from_rigid_kind(kind: RigidTy) -> Ty {
2826
with(|cx| cx.new_rigid_ty(kind))
2927
}
3028

@@ -77,6 +75,16 @@ impl Ty {
7775
pub fn bool_ty() -> Ty {
7876
Ty::from_rigid_kind(RigidTy::Bool)
7977
}
78+
79+
/// Create a type representing a signed integer.
80+
pub fn signed_ty(inner: IntTy) -> Ty {
81+
Ty::from_rigid_kind(RigidTy::Int(inner))
82+
}
83+
84+
/// Create a type representing an unsigned integer.
85+
pub fn unsigned_ty(inner: UintTy) -> Ty {
86+
Ty::from_rigid_kind(RigidTy::Uint(inner))
87+
}
8088
}
8189

8290
impl Ty {

tests/ui-fulldeps/stable-mir/check_defs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ fn extract_elem_ty(ty: Ty) -> Ty {
6969

7070
/// Check signature and type of `Vec::<u8>::new` and its generic version.
7171
fn test_vec_new(instance: mir::mono::Instance) {
72-
let sig = instance.fn_sig();
72+
let sig = instance.ty().kind().fn_sig().unwrap().skip_binder();
7373
assert_matches!(sig.inputs(), &[]);
7474
let elem_ty = extract_elem_ty(sig.output());
7575
assert_matches!(elem_ty.kind(), TyKind::RigidTy(RigidTy::Uint(UintTy::U8)));

0 commit comments

Comments
 (0)