Skip to content

Commit

Permalink
Rollup merge of #122801 - celinval:smir-pretty, r=compiler-errors
Browse files Browse the repository at this point in the history
Fix misc printing issues in emit=stable_mir

Trying to continue the work that ````@ouz-a```` started here: #118364

Few modifications beyond fixes:
1. I made the `pretty_*` functions private.
2. I added a function to print the instance body
3. Changed a bunch of signatures to write to the writer directly.
4. Added a function to translate the place to its internal representation, so we could use the internal debug implementation.
5. Also removed `pretty_ty`, replaced by Display implementation of Ty which uses the internal display.
  • Loading branch information
matthiaskrgr committed Mar 21, 2024
2 parents 300d3fb + ebacf7a commit 3331d0d
Show file tree
Hide file tree
Showing 10 changed files with 355 additions and 560 deletions.
46 changes: 45 additions & 1 deletion compiler/rustc_smir/src/rustc_internal/internal.rs
Expand Up @@ -10,7 +10,7 @@ use rustc_span::Symbol;
use stable_mir::abi::Layout;
use stable_mir::mir::alloc::AllocId;
use stable_mir::mir::mono::{Instance, MonoItem, StaticDef};
use stable_mir::mir::{Mutability, Safety};
use stable_mir::mir::{Mutability, Place, ProjectionElem, Safety};
use stable_mir::ty::{
Abi, AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const,
DynKind, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FloatTy, FnSig,
Expand Down Expand Up @@ -492,6 +492,50 @@ impl RustcInternal for Layout {
}
}

impl RustcInternal for Place {
type T<'tcx> = rustc_middle::mir::Place<'tcx>;

fn internal<'tcx>(&self, tables: &mut Tables<'_>, tcx: TyCtxt<'tcx>) -> Self::T<'tcx> {
rustc_middle::mir::Place {
local: rustc_middle::mir::Local::from_usize(self.local),
projection: tcx.mk_place_elems(&self.projection.internal(tables, tcx)),
}
}
}

impl RustcInternal for ProjectionElem {
type T<'tcx> = rustc_middle::mir::PlaceElem<'tcx>;

fn internal<'tcx>(&self, tables: &mut Tables<'_>, tcx: TyCtxt<'tcx>) -> Self::T<'tcx> {
match self {
ProjectionElem::Deref => rustc_middle::mir::PlaceElem::Deref,
ProjectionElem::Field(idx, ty) => {
rustc_middle::mir::PlaceElem::Field((*idx).into(), ty.internal(tables, tcx))
}
ProjectionElem::Index(idx) => rustc_middle::mir::PlaceElem::Index((*idx).into()),
ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
rustc_middle::mir::PlaceElem::ConstantIndex {
offset: *offset,
min_length: *min_length,
from_end: *from_end,
}
}
ProjectionElem::Subslice { from, to, from_end } => {
rustc_middle::mir::PlaceElem::Subslice { from: *from, to: *to, from_end: *from_end }
}
ProjectionElem::Downcast(idx) => {
rustc_middle::mir::PlaceElem::Downcast(None, idx.internal(tables, tcx))
}
ProjectionElem::OpaqueCast(ty) => {
rustc_middle::mir::PlaceElem::OpaqueCast(ty.internal(tables, tcx))
}
ProjectionElem::Subtype(ty) => {
rustc_middle::mir::PlaceElem::Subtype(ty.internal(tables, tcx))
}
}
}
}

impl<T> RustcInternal for &T
where
T: RustcInternal,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_smir/src/rustc_internal/pretty.rs
Expand Up @@ -14,7 +14,7 @@ pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io
)?;
let _ = run(tcx, || {
let items = stable_mir::all_local_items();
let _ = items.iter().map(|item| -> io::Result<()> { item.dump(w) }).collect::<Vec<_>>();
let _ = items.iter().map(|item| -> io::Result<()> { item.emit_mir(w) }).collect::<Vec<_>>();
});
Ok(())
}
15 changes: 13 additions & 2 deletions compiler/rustc_smir/src/rustc_smir/context.rs
Expand Up @@ -19,7 +19,7 @@ use stable_mir::abi::{FnAbi, Layout, LayoutShape};
use stable_mir::compiler_interface::Context;
use stable_mir::mir::alloc::GlobalAlloc;
use stable_mir::mir::mono::{InstanceDef, StaticDef};
use stable_mir::mir::Body;
use stable_mir::mir::{Body, Place};
use stable_mir::target::{MachineInfo, MachineSize};
use stable_mir::ty::{
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FieldDef, FnDef, ForeignDef,
Expand Down Expand Up @@ -423,7 +423,7 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
def_ty.instantiate(tables.tcx, args).stable(&mut *tables)
}

fn const_literal(&self, cnst: &stable_mir::ty::Const) -> String {
fn const_pretty(&self, cnst: &stable_mir::ty::Const) -> String {
let mut tables = self.0.borrow_mut();
let tcx = tables.tcx;
cnst.internal(&mut *tables, tcx).to_string()
Expand All @@ -434,6 +434,11 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
tables.tcx.def_span(tables[def_id]).stable(&mut *tables)
}

fn ty_pretty(&self, ty: stable_mir::ty::Ty) -> String {
let tables = self.0.borrow_mut();
tables.types[ty].to_string()
}

fn ty_kind(&self, ty: stable_mir::ty::Ty) -> TyKind {
let mut tables = self.0.borrow_mut();
tables.types[ty].kind().stable(&mut *tables)
Expand Down Expand Up @@ -654,6 +659,12 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
let tcx = tables.tcx;
id.internal(&mut *tables, tcx).0.stable(&mut *tables)
}

fn place_pretty(&self, place: &Place) -> String {
let mut tables = self.0.borrow_mut();
let tcx = tables.tcx;
format!("{:?}", place.internal(&mut *tables, tcx))
}
}

pub struct TablesWrapper<'tcx>(pub RefCell<Tables<'tcx>>);
Expand Down
10 changes: 8 additions & 2 deletions compiler/stable_mir/src/compiler_interface.rs
Expand Up @@ -8,7 +8,7 @@ use std::cell::Cell;
use crate::abi::{FnAbi, Layout, LayoutShape};
use crate::mir::alloc::{AllocId, GlobalAlloc};
use crate::mir::mono::{Instance, InstanceDef, StaticDef};
use crate::mir::Body;
use crate::mir::{Body, Place};
use crate::target::MachineInfo;
use crate::ty::{
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FieldDef, FnDef, ForeignDef,
Expand Down Expand Up @@ -126,11 +126,14 @@ pub trait Context {
fn def_ty_with_args(&self, item: DefId, args: &GenericArgs) -> Ty;

/// Returns literal value of a const as a string.
fn const_literal(&self, cnst: &Const) -> String;
fn const_pretty(&self, cnst: &Const) -> String;

/// `Span` of an item
fn span_of_an_item(&self, def_id: DefId) -> Span;

/// Obtain the representation of a type.
fn ty_pretty(&self, ty: Ty) -> String;

/// Obtain the representation of a type.
fn ty_kind(&self, ty: Ty) -> TyKind;

Expand Down Expand Up @@ -205,6 +208,9 @@ pub trait Context {

/// Get the layout shape.
fn layout_shape(&self, id: Layout) -> LayoutShape;

/// Get a debug string representation of a place.
fn place_pretty(&self, place: &Place) -> String;
}

// A thread local variable that stores a pointer to the tables mapping between TyCtxt
Expand Down
6 changes: 2 additions & 4 deletions compiler/stable_mir/src/lib.rs
Expand Up @@ -27,7 +27,6 @@ use crate::compiler_interface::with;
pub use crate::crate_def::CrateDef;
pub use crate::crate_def::DefId;
pub use crate::error::*;
use crate::mir::pretty::function_name;
use crate::mir::Body;
use crate::mir::Mutability;
use crate::ty::{ForeignModuleDef, ImplDef, IndexedVal, Span, TraitDef, Ty};
Expand Down Expand Up @@ -148,9 +147,8 @@ impl CrateItem {
with(|cx| cx.is_foreign_item(self.0))
}

pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
writeln!(w, "{}", function_name(*self))?;
self.body().dump(w)
pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
self.body().dump(w, &self.name())
}
}

Expand Down
30 changes: 6 additions & 24 deletions compiler/stable_mir/src/mir/body.rs
@@ -1,10 +1,11 @@
use crate::mir::pretty::{function_body, pretty_statement, pretty_terminator};
use crate::mir::pretty::function_body;
use crate::ty::{
AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, RigidTy, Ty, TyKind,
VariantIdx,
};
use crate::{Error, Opaque, Span, Symbol};
use std::io;

/// The SMIR representation of a single function.
#[derive(Clone, Debug)]
pub struct Body {
Expand Down Expand Up @@ -90,28 +91,9 @@ impl Body {
self.locals.iter().enumerate()
}

pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
writeln!(w, "{}", function_body(self))?;
self.blocks
.iter()
.enumerate()
.map(|(index, block)| -> io::Result<()> {
writeln!(w, " bb{}: {{", index)?;
let _ = block
.statements
.iter()
.map(|statement| -> io::Result<()> {
writeln!(w, "{}", pretty_statement(&statement.kind))?;
Ok(())
})
.collect::<Vec<_>>();
pretty_terminator(&block.terminator.kind, w)?;
writeln!(w, "").unwrap();
writeln!(w, " }}").unwrap();
Ok(())
})
.collect::<Result<Vec<_>, _>>()?;
Ok(())
/// Emit the body using the provided name for the signature.
pub fn dump<W: io::Write>(&self, w: &mut W, fn_name: &str) -> io::Result<()> {
function_body(w, self, fn_name)
}

pub fn spread_arg(&self) -> Option<Local> {
Expand Down Expand Up @@ -674,7 +656,7 @@ pub enum Operand {
Constant(Constant),
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Eq, PartialEq)]
pub struct Place {
pub local: Local,
/// projection out of a place (access a field, deref a pointer, etc)
Expand Down
6 changes: 6 additions & 0 deletions compiler/stable_mir/src/mir/mono.rs
Expand Up @@ -4,6 +4,7 @@ use crate::mir::Body;
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty};
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol};
use std::fmt::{Debug, Formatter};
use std::io;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MonoItem {
Expand Down Expand Up @@ -157,6 +158,11 @@ impl Instance {
pub fn try_const_eval(&self, const_ty: Ty) -> Result<Allocation, Error> {
with(|cx| cx.eval_instance(self.def, const_ty))
}

/// Emit the body of this instance if it has one.
pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
if let Some(body) = self.body() { body.dump(w, &self.name()) } else { Ok(()) }
}
}

impl Debug for Instance {
Expand Down

0 comments on commit 3331d0d

Please sign in to comment.