Skip to content

Commit c997c6d

Browse files
committed
Add more information to stable Instance
- Retrieve `FnSig`. - Implement CrateDef for InstanceDef. - Add VTable index for Virtual instances.
1 parent 64d7e0d commit c997c6d

File tree

6 files changed

+134
-20
lines changed

6 files changed

+134
-20
lines changed

compiler/rustc_smir/src/rustc_smir/context.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
//! This trait is currently the main interface between the Rust compiler,
44
//! and the `stable_mir` crate.
55
6+
use rustc_middle::ty;
67
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
78
use rustc_middle::ty::{GenericPredicates, Instance, ParamEnv, ScalarInt, ValTree};
89
use rustc_span::def_id::LOCAL_CRATE;
@@ -12,9 +13,9 @@ use stable_mir::mir::mono::{InstanceDef, StaticDef};
1213
use stable_mir::mir::Body;
1314
use stable_mir::ty::{
1415
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FnDef, GenericArgs, LineInfo,
15-
RigidTy, Span, TyKind,
16+
PolyFnSig, RigidTy, Span, TyKind,
1617
};
17-
use stable_mir::{self, Crate, CrateItem, Error, Filename, ItemKind, Symbol};
18+
use stable_mir::{self, Crate, CrateItem, DefId, Error, Filename, ItemKind, Symbol};
1819
use std::cell::RefCell;
1920

2021
use crate::rustc_internal::{internal, RustcInternal};
@@ -39,6 +40,12 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
3940
tables.tcx.instance_mir(rustc_middle::ty::InstanceDef::Item(def_id)).stable(&mut tables)
4041
}
4142

43+
fn has_body(&self, def: DefId) -> bool {
44+
let tables = self.0.borrow();
45+
let def_id = tables[def];
46+
tables.tcx.is_mir_available(def_id)
47+
}
48+
4249
fn all_trait_decls(&self) -> stable_mir::TraitDecls {
4350
let mut tables = self.0.borrow_mut();
4451
tables
@@ -195,6 +202,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
195202
def.internal(&mut *tables).is_box()
196203
}
197204

205+
fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig {
206+
let mut tables = self.0.borrow_mut();
207+
let def_id = def.0.internal(&mut *tables);
208+
let sig = tables.tcx.fn_sig(def_id).instantiate(tables.tcx, args.internal(&mut *tables));
209+
sig.stable(&mut *tables)
210+
}
211+
198212
fn eval_target_usize(&self, cnst: &Const) -> Result<u64, Error> {
199213
let mut tables = self.0.borrow_mut();
200214
let mir_const = cnst.internal(&mut *tables);
@@ -266,6 +280,12 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
266280
tables.tcx.symbol_name(instance).name.to_string()
267281
}
268282

283+
fn is_empty_drop_shim(&self, def: InstanceDef) -> bool {
284+
let tables = self.0.borrow_mut();
285+
let instance = tables.instances[def];
286+
matches!(instance.def, ty::InstanceDef::DropGlue(_, None))
287+
}
288+
269289
fn mono_instance(&self, item: stable_mir::CrateItem) -> stable_mir::mir::mono::Instance {
270290
let mut tables = self.0.borrow_mut();
271291
let def_id = tables[item.0];

compiler/rustc_smir/src/rustc_smir/convert/ty.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,9 @@ impl<'tcx> Stable<'tcx> for ty::Instance<'tcx> {
777777
let kind = match self.def {
778778
ty::InstanceDef::Item(..) => stable_mir::mir::mono::InstanceKind::Item,
779779
ty::InstanceDef::Intrinsic(..) => stable_mir::mir::mono::InstanceKind::Intrinsic,
780-
ty::InstanceDef::Virtual(..) => stable_mir::mir::mono::InstanceKind::Virtual,
780+
ty::InstanceDef::Virtual(_def_id, idx) => {
781+
stable_mir::mir::mono::InstanceKind::Virtual { idx }
782+
}
781783
ty::InstanceDef::VTableShim(..)
782784
| ty::InstanceDef::ReifyShim(..)
783785
| ty::InstanceDef::FnPtrAddrShim(..)

compiler/stable_mir/src/compiler_interface.rs

+13-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use crate::mir::mono::{Instance, InstanceDef, StaticDef};
1010
use crate::mir::Body;
1111
use crate::ty::{
1212
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FnDef, GenericArgs,
13-
GenericPredicates, Generics, ImplDef, ImplTrait, LineInfo, RigidTy, Span, TraitDecl, TraitDef,
14-
Ty, TyKind,
13+
GenericPredicates, Generics, ImplDef, ImplTrait, LineInfo, PolyFnSig, RigidTy, Span, TraitDecl,
14+
TraitDef, Ty, TyKind,
1515
};
1616
use crate::{
1717
mir, Crate, CrateItem, CrateItems, DefId, Error, Filename, ImplTraitDecls, ItemKind, Symbol,
@@ -24,7 +24,11 @@ pub trait Context {
2424
fn entry_fn(&self) -> Option<CrateItem>;
2525
/// Retrieve all items of the local crate that have a MIR associated with them.
2626
fn all_local_items(&self) -> CrateItems;
27+
/// Retrieve the body of a function.
28+
/// This function will panic if the body is not available.
2729
fn mir_body(&self, item: DefId) -> mir::Body;
30+
/// Check whether the body of a function is available.
31+
fn has_body(&self, item: DefId) -> bool;
2832
fn all_trait_decls(&self) -> TraitDecls;
2933
fn trait_decl(&self, trait_def: &TraitDef) -> TraitDecl;
3034
fn all_trait_impls(&self) -> ImplTraitDecls;
@@ -64,6 +68,9 @@ pub trait Context {
6468
/// Returns if the ADT is a box.
6569
fn adt_is_box(&self, def: AdtDef) -> bool;
6670

71+
/// Retrieve the function signature for the given generic arguments.
72+
fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig;
73+
6774
/// Evaluate constant as a target usize.
6875
fn eval_target_usize(&self, cnst: &Const) -> Result<u64, Error>;
6976

@@ -85,8 +92,7 @@ pub trait Context {
8592
/// Obtain the representation of a type.
8693
fn ty_kind(&self, ty: Ty) -> TyKind;
8794

88-
/// Get the body of an Instance.
89-
/// FIXME: Monomorphize the body.
95+
/// Get the body of an Instance which is already monomorphized.
9096
fn instance_body(&self, instance: InstanceDef) -> Option<Body>;
9197

9298
/// Get the instance type with generic substitutions applied and lifetimes erased.
@@ -98,6 +104,9 @@ pub trait Context {
98104
/// Get the instance mangled name.
99105
fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol;
100106

107+
/// Check if this is an empty DropGlue shim.
108+
fn is_empty_drop_shim(&self, def: InstanceDef) -> bool;
109+
101110
/// Convert a non-generic crate item into an instance.
102111
/// This function will panic if the item is generic.
103112
fn mono_instance(&self, item: CrateItem) -> Instance;

compiler/stable_mir/src/mir/mono.rs

+34-9
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, GenericArgs, IndexedVal, Ty};
3+
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, FnSig, GenericArgs, IndexedVal, Ty};
44
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol};
55
use std::fmt::{Debug, Formatter};
66

@@ -27,7 +27,8 @@ pub enum InstanceKind {
2727
/// A compiler intrinsic function.
2828
Intrinsic,
2929
/// A virtual function definition stored in a VTable.
30-
Virtual,
30+
/// The `idx` field indicates the position in the VTable for this instance.
31+
Virtual { idx: usize },
3132
/// A compiler generated shim.
3233
Shim,
3334
}
@@ -106,6 +107,24 @@ impl Instance {
106107
})
107108
})
108109
}
110+
111+
/// Get this function signature with all types already instantiated.
112+
pub fn fn_sig(&self) -> FnSig {
113+
self.ty().kind().fn_sig().unwrap().skip_binder()
114+
}
115+
116+
/// Check whether this instance is an empty shim.
117+
///
118+
/// Allow users to check if this shim can be ignored when called directly.
119+
///
120+
/// We have decided not to export different types of Shims to StableMIR users, however, this
121+
/// is a query that can be very helpful for users when processing DropGlue.
122+
///
123+
/// When generating code for a Drop terminator, users can ignore an empty drop glue.
124+
/// These shims are only needed to generate a valid Drop call done via VTable.
125+
pub fn is_empty_shim(&self) -> bool {
126+
self.kind == InstanceKind::Shim && with(|cx| cx.is_empty_drop_shim(self.def))
127+
}
109128
}
110129

111130
impl Debug for Instance {
@@ -124,8 +143,6 @@ impl TryFrom<CrateItem> for Instance {
124143

125144
fn try_from(item: CrateItem) -> Result<Self, Self::Error> {
126145
with(|context| {
127-
// FIXME(celinval):
128-
// - Return `Err` if instance does not have a body.
129146
if !context.requires_monomorphization(item.0) {
130147
Ok(context.mono_instance(item))
131148
} else {
@@ -141,11 +158,13 @@ impl TryFrom<Instance> for CrateItem {
141158
type Error = crate::Error;
142159

143160
fn try_from(value: Instance) -> Result<Self, Self::Error> {
144-
if value.kind == InstanceKind::Item {
145-
Ok(CrateItem(with(|context| context.instance_def_id(value.def))))
146-
} else {
147-
Err(Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
148-
}
161+
with(|context| {
162+
if value.kind == InstanceKind::Item && context.has_body(value.def.def_id()) {
163+
Ok(CrateItem(context.instance_def_id(value.def)))
164+
} else {
165+
Err(Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
166+
}
167+
})
149168
}
150169
}
151170

@@ -170,6 +189,12 @@ impl From<StaticDef> for CrateItem {
170189
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171190
pub struct InstanceDef(usize);
172191

192+
impl CrateDef for InstanceDef {
193+
fn def_id(&self) -> DefId {
194+
with(|context| context.instance_def_id(*self))
195+
}
196+
}
197+
173198
crate_def! {
174199
/// Holds information about a static variable definition.
175200
pub StaticDef;

compiler/stable_mir/src/ty.rs

+35-3
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,11 @@ impl TyKind {
168168
}
169169

170170
pub fn is_unit(&self) -> bool {
171-
matches!(self, TyKind::RigidTy(RigidTy::Tuple(data)) if data.len() == 0)
171+
matches!(self, TyKind::RigidTy(RigidTy::Tuple(data)) if data.is_empty())
172+
}
173+
174+
pub fn is_bool(&self) -> bool {
175+
matches!(self, TyKind::RigidTy(RigidTy::Bool))
172176
}
173177

174178
pub fn is_trait(&self) -> bool {
@@ -187,6 +191,14 @@ impl TyKind {
187191
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.kind() == AdtKind::Union)
188192
}
189193

194+
pub fn is_fn(&self) -> bool {
195+
matches!(self, TyKind::RigidTy(RigidTy::FnDef(..)))
196+
}
197+
198+
pub fn is_fn_ptr(&self) -> bool {
199+
matches!(self, TyKind::RigidTy(RigidTy::FnPtr(..)))
200+
}
201+
190202
pub fn trait_principal(&self) -> Option<Binder<ExistentialTraitRef>> {
191203
if let TyKind::RigidTy(RigidTy::Dynamic(predicates, _, _)) = self {
192204
if let Some(Binder { value: ExistentialPredicate::Trait(trait_ref), bound_vars }) =
@@ -227,6 +239,15 @@ impl TyKind {
227239
_ => None,
228240
}
229241
}
242+
243+
/// Get the function signature for function like types (Fn, FnPtr, Closure, Coroutine)
244+
pub fn fn_sig(&self) -> Option<PolyFnSig> {
245+
match self {
246+
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Some(with(|cx| cx.fn_sig(*def, args))),
247+
TyKind::RigidTy(RigidTy::FnPtr(sig)) => Some(sig.clone()),
248+
_ => None,
249+
}
250+
}
230251
}
231252

232253
pub struct TypeAndMut {
@@ -307,8 +328,9 @@ crate_def! {
307328
}
308329

309330
impl FnDef {
310-
pub fn body(&self) -> Body {
311-
with(|ctx| ctx.mir_body(self.0))
331+
// Get the function body if available.
332+
pub fn body(&self) -> Option<Body> {
333+
with(|ctx| ctx.has_body(self.0).then(|| ctx.mir_body(self.0)))
312334
}
313335
}
314336

@@ -488,6 +510,16 @@ pub struct FnSig {
488510
pub abi: Abi,
489511
}
490512

513+
impl FnSig {
514+
pub fn output(&self) -> Ty {
515+
self.inputs_and_output[self.inputs_and_output.len() - 1]
516+
}
517+
518+
pub fn inputs(&self) -> &[Ty] {
519+
&self.inputs_and_output[..self.inputs_and_output.len() - 1]
520+
}
521+
}
522+
491523
#[derive(Clone, PartialEq, Eq, Debug)]
492524
pub enum Abi {
493525
Rust,

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

+27-1
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ extern crate rustc_driver;
1818
extern crate rustc_interface;
1919
extern crate stable_mir;
2020

21+
use std::assert_matches::assert_matches;
2122
use mir::{mono::Instance, TerminatorKind::*};
2223
use rustc_middle::ty::TyCtxt;
2324
use rustc_smir::rustc_internal;
24-
use stable_mir::ty::{RigidTy, TyKind};
25+
use stable_mir::ty::{RigidTy, TyKind, Ty, UintTy};
2526
use stable_mir::*;
2627
use std::io::Write;
2728
use std::ops::ControlFlow;
@@ -39,6 +40,7 @@ fn test_stable_mir(_tcx: TyCtxt<'_>) -> ControlFlow<()> {
3940
assert_eq!(instances.len(), 2);
4041
test_fn(instances[0], "from_u32", "std::char::from_u32", "core");
4142
test_fn(instances[1], "Vec::<u8>::new", "std::vec::Vec::<u8>::new", "alloc");
43+
test_vec_new(instances[1]);
4244
ControlFlow::Continue(())
4345
}
4446

@@ -56,6 +58,30 @@ fn test_fn(instance: Instance, expected_trimmed: &str, expected_qualified: &str,
5658
assert_eq!(&item.krate().name, krate);
5759
}
5860

61+
fn extract_elem_ty(ty: Ty) -> Ty {
62+
match ty.kind() {
63+
TyKind::RigidTy(RigidTy::Adt(_, args)) => {
64+
*args.0[0].expect_ty()
65+
}
66+
_ => unreachable!("Expected Vec ADT, but found: {ty:?}")
67+
}
68+
}
69+
70+
/// Check signature and type of `Vec::<u8>::new` and its generic version.
71+
fn test_vec_new(instance: mir::mono::Instance) {
72+
let sig = instance.fn_sig();
73+
assert_matches!(sig.inputs(), &[]);
74+
let elem_ty = extract_elem_ty(sig.output());
75+
assert_matches!(elem_ty.kind(), TyKind::RigidTy(RigidTy::Uint(UintTy::U8)));
76+
77+
// Get the signature for Vec::<T>::new.
78+
let item = CrateItem::try_from(instance).unwrap();
79+
let ty = item.ty();
80+
let gen_sig = ty.kind().fn_sig().unwrap().skip_binder();
81+
let gen_ty = extract_elem_ty(gen_sig.output());
82+
assert_matches!(gen_ty.kind(), TyKind::Param(_));
83+
}
84+
5985
/// Inspect the instance body
6086
fn get_instances(body: mir::Body) -> Vec<Instance> {
6187
body.blocks.iter().filter_map(|bb| {

0 commit comments

Comments
 (0)