Skip to content

rustc_public: de-StableMIR-ize #143985

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions compiler/rustc_public/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Memory allocation implementation for StableMIR.
//! Memory allocation implementation for rustc_public.
//!
//! This module is responsible for constructing stable components.
//! All operations requiring rustc queries must be delegated
Expand All @@ -7,8 +7,8 @@
use rustc_abi::Align;
use rustc_middle::mir::ConstValue;
use rustc_middle::mir::interpret::AllocRange;
use rustc_public_bridge::bridge::SmirError;
use rustc_public_bridge::context::SmirCtxt;
use rustc_public_bridge::bridge::Error as _;
use rustc_public_bridge::context::CompilerCtxt;
use rustc_public_bridge::{Tables, alloc};

use super::Error;
Expand All @@ -35,7 +35,7 @@ pub(crate) fn new_allocation<'tcx>(
ty: rustc_middle::ty::Ty<'tcx>,
const_value: ConstValue<'tcx>,
tables: &mut Tables<'tcx, BridgeTys>,
cx: &SmirCtxt<'tcx, BridgeTys>,
cx: &CompilerCtxt<'tcx, BridgeTys>,
) -> Allocation {
try_new_allocation(ty, const_value, tables, cx)
.unwrap_or_else(|_| panic!("Failed to convert: {const_value:?} to {ty:?}"))
Expand All @@ -46,7 +46,7 @@ pub(crate) fn try_new_allocation<'tcx>(
ty: rustc_middle::ty::Ty<'tcx>,
const_value: ConstValue<'tcx>,
tables: &mut Tables<'tcx, BridgeTys>,
cx: &SmirCtxt<'tcx, BridgeTys>,
cx: &CompilerCtxt<'tcx, BridgeTys>,
) -> Result<Allocation, Error> {
let layout = alloc::create_ty_and_layout(cx, ty).map_err(|e| Error::from_internal(e))?;
match const_value {
Expand All @@ -59,7 +59,7 @@ pub(crate) fn try_new_allocation<'tcx>(
}
ConstValue::Indirect { alloc_id, offset } => {
let alloc = alloc::try_new_indirect(alloc_id, cx);
use rustc_public_bridge::context::SmirAllocRange;
use rustc_public_bridge::context::AllocRangeHelpers;
Ok(allocation_filter(&alloc.0, cx.alloc_range(offset, layout.size), tables, cx))
}
}
Expand All @@ -70,7 +70,7 @@ pub(super) fn allocation_filter<'tcx>(
alloc: &rustc_middle::mir::interpret::Allocation,
alloc_range: AllocRange,
tables: &mut Tables<'tcx, BridgeTys>,
cx: &SmirCtxt<'tcx, BridgeTys>,
cx: &CompilerCtxt<'tcx, BridgeTys>,
) -> Allocation {
alloc::allocation_filter(alloc, alloc_range, tables, cx)
}
30 changes: 15 additions & 15 deletions compiler/rustc_public/src/compiler_interface.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
//! Define the interface with the Rust compiler.
//!
//! StableMIR users should not use any of the items in this module directly.
//! rustc_public users should not use any of the items in this module directly.
//! These APIs have no stability guarantee.

use std::cell::Cell;

use rustc_hir::def::DefKind;
use rustc_public_bridge::context::SmirCtxt;
use rustc_public_bridge::{Bridge, SmirContainer};
use rustc_public_bridge::context::CompilerCtxt;
use rustc_public_bridge::{Bridge, Container};
use tracing::debug;

use crate::abi::{FnAbi, Layout, LayoutShape, ReprOptions};
Expand Down Expand Up @@ -66,13 +66,13 @@ impl Bridge for BridgeTys {
type Allocation = crate::ty::Allocation;
}

/// Stable public API for querying compiler information.
/// Public API for querying compiler information.
///
/// All queries are delegated to [`rustc_public_bridge::context::SmirCtxt`] that provides
/// All queries are delegated to [`rustc_public_bridge::context::CompilerCtxt`] that provides
/// similar APIs but based on internal rustc constructs.
///
/// Do not use this directly. This is currently used in the macro expansion.
pub(crate) trait SmirInterface {
pub(crate) trait CompilerInterface {
fn entry_fn(&self) -> Option<CrateItem>;
/// Retrieve all items of the local crate that have a MIR associated with them.
fn all_local_items(&self) -> CrateItems;
Expand Down Expand Up @@ -316,7 +316,7 @@ pub(crate) trait SmirInterface {
fn associated_items(&self, def_id: DefId) -> AssocItems;
}

impl<'tcx> SmirInterface for SmirContainer<'tcx, BridgeTys> {
impl<'tcx> CompilerInterface for Container<'tcx, BridgeTys> {
fn entry_fn(&self) -> Option<CrateItem> {
let mut tables = self.tables.borrow_mut();
let cx = &*self.cx.borrow();
Expand Down Expand Up @@ -567,7 +567,7 @@ impl<'tcx> SmirInterface for SmirContainer<'tcx, BridgeTys> {
DefKind::Fn => ForeignItemKind::Fn(tables.fn_def(def_id)),
DefKind::Static { .. } => ForeignItemKind::Static(tables.static_def(def_id)),
DefKind::ForeignTy => {
use rustc_public_bridge::context::SmirTy;
use rustc_public_bridge::context::TyHelpers;
ForeignItemKind::Type(tables.intern_ty(cx.new_foreign(def_id)))
}
def_kind => unreachable!("Unexpected kind for a foreign item: {:?}", def_kind),
Expand Down Expand Up @@ -1059,36 +1059,36 @@ impl<'tcx> SmirInterface for SmirContainer<'tcx, BridgeTys> {
}
}

// A thread local variable that stores a pointer to [`SmirInterface`].
// A thread local variable that stores a pointer to [`CompilerInterface`].
scoped_tls::scoped_thread_local!(static TLV: Cell<*const ()>);

pub(crate) fn run<F, T>(interface: &dyn SmirInterface, f: F) -> Result<T, Error>
pub(crate) fn run<F, T>(interface: &dyn CompilerInterface, f: F) -> Result<T, Error>
where
F: FnOnce() -> T,
{
if TLV.is_set() {
Err(Error::from("StableMIR already running"))
Err(Error::from("rustc_public already running"))
} else {
let ptr: *const () = (&raw const interface) as _;
TLV.set(&Cell::new(ptr), || Ok(f()))
}
}

/// Execute the given function with access the [`SmirInterface`].
/// Execute the given function with access the [`CompilerInterface`].
///
/// I.e., This function will load the current interface and calls a function with it.
/// Do not nest these, as that will ICE.
pub(crate) fn with<R>(f: impl FnOnce(&dyn SmirInterface) -> R) -> R {
pub(crate) fn with<R>(f: impl FnOnce(&dyn CompilerInterface) -> R) -> R {
assert!(TLV.is_set());
TLV.with(|tlv| {
let ptr = tlv.get();
assert!(!ptr.is_null());
f(unsafe { *(ptr as *const &dyn SmirInterface) })
f(unsafe { *(ptr as *const &dyn CompilerInterface) })
})
}

fn smir_crate<'tcx>(
cx: &SmirCtxt<'tcx, BridgeTys>,
cx: &CompilerCtxt<'tcx, BridgeTys>,
crate_num: rustc_span::def_id::CrateNum,
) -> Crate {
let name = cx.crate_name(crate_num);
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_public/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
//! When things go wrong, we need some error handling.
//! There are a few different types of errors in StableMIR:
//! There are a few different types of errors in rustc_public:
//!
//! - [CompilerError]: This represents errors that can be raised when invoking the compiler.
//! - [Error]: Generic error that represents the reason why a request that could not be fulfilled.

use std::fmt::{Debug, Display, Formatter};
use std::{fmt, io};

use rustc_public_bridge::bridge::SmirError;
use rustc_public_bridge::bridge;

macro_rules! error {
($fmt: literal $(,)?) => { Error(format!($fmt)) };
Expand All @@ -32,7 +32,7 @@ pub enum CompilerError<T> {
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error(pub(crate) String);

impl SmirError for Error {
impl bridge::Error for Error {
fn new(msg: String) -> Self {
Self(msg)
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_public/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use std::{fmt, io};

pub(crate) use rustc_public_bridge::IndexedVal;
use rustc_public_bridge::Tables;
use rustc_public_bridge::context::SmirCtxt;
use rustc_public_bridge::context::CompilerCtxt;
/// Export the rustc_internal APIs. Note that this module has no stability
/// guarantees and it is not taken into account for semver.
#[cfg(feature = "rustc_internal")]
Expand Down Expand Up @@ -288,7 +288,7 @@ impl rustc_public_bridge::bridge::Allocation<compiler_interface::BridgeTys>
align: u64,
mutability: rustc_middle::mir::Mutability,
tables: &mut Tables<'tcx, compiler_interface::BridgeTys>,
cx: &SmirCtxt<'tcx, compiler_interface::BridgeTys>,
cx: &CompilerCtxt<'tcx, compiler_interface::BridgeTys>,
) -> Self {
Self {
bytes,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_public/src/mir/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::target::{Endian, MachineInfo};
use crate::ty::{Allocation, Binder, ExistentialTraitRef, Ty};
use crate::{Error, IndexedVal, with};

/// An allocation in the SMIR global memory can be either a function pointer,
/// An allocation in the rustc_public's IR global memory can be either a function pointer,
/// a static, or a "real" allocation with some data in it.
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub enum GlobalAlloc {
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_public/src/mir/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::ty::{
};
use crate::{Error, Opaque, Span, Symbol};

/// The SMIR representation of a single function.
/// The rustc_public's IR representation of a single function.
#[derive(Clone, Debug, Serialize)]
pub struct Body {
pub blocks: Vec<BasicBlock>,
Expand Down Expand Up @@ -771,8 +771,8 @@ pub enum VarDebugInfoContents {
// In MIR ProjectionElem is parameterized on the second Field argument and the Index argument. This
// is so it can be used for both Places (for which the projection elements are of type
// ProjectionElem<Local, Ty>) and user-provided type annotations (for which the projection elements
// are of type ProjectionElem<(), ()>). In SMIR we don't need this generality, so we just use
// ProjectionElem for Places.
// are of type ProjectionElem<(), ()>).
// In rustc_public's IR we don't need this generality, so we just use ProjectionElem for Places.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum ProjectionElem {
/// Dereference projections (e.g. `*_1`) project to the address referenced by the base place.
Expand Down
30 changes: 15 additions & 15 deletions compiler/rustc_public/src/mir/mono.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::{Debug, Formatter};
use std::io;

use rustc_public_bridge::bridge::SmirError;
use rustc_public_bridge::bridge;
use serde::Serialize;

use crate::abi::FnAbi;
Expand Down Expand Up @@ -62,7 +62,7 @@ impl Instance {
/// For more information on fallback body, see <https://github.com/rust-lang/rust/issues/93145>.
///
/// This call is much cheaper than `instance.body().is_some()`, since it doesn't try to build
/// the StableMIR body.
/// the rustc_public's IR body.
pub fn has_body(&self) -> bool {
with(|cx| cx.has_body(self.def.def_id()))
}
Expand Down Expand Up @@ -120,9 +120,9 @@ impl Instance {
/// Resolve an instance starting from a function definition and generic arguments.
pub fn resolve(def: FnDef, args: &GenericArgs) -> Result<Instance, Error> {
with(|context| {
context
.resolve_instance(def, args)
.ok_or_else(|| Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`")))
context.resolve_instance(def, args).ok_or_else(|| {
bridge::Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`"))
})
})
}

Expand All @@ -134,9 +134,9 @@ impl Instance {
/// Resolve an instance for a given function pointer.
pub fn resolve_for_fn_ptr(def: FnDef, args: &GenericArgs) -> Result<Instance, Error> {
with(|context| {
context
.resolve_for_fn_ptr(def, args)
.ok_or_else(|| Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`")))
context.resolve_for_fn_ptr(def, args).ok_or_else(|| {
bridge::Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`"))
})
})
}

Expand All @@ -147,17 +147,17 @@ impl Instance {
kind: ClosureKind,
) -> Result<Instance, Error> {
with(|context| {
context
.resolve_closure(def, args, kind)
.ok_or_else(|| Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`")))
context.resolve_closure(def, args, kind).ok_or_else(|| {
bridge::Error::new(format!("Failed to resolve `{def:?}` with `{args:?}`"))
})
})
}

/// Check whether this instance is an empty shim.
///
/// Allow users to check if this shim can be ignored when called directly.
///
/// We have decided not to export different types of Shims to StableMIR users, however, this
/// We have decided not to export different types of Shims to rustc_public users, however, this
/// is a query that can be very helpful for users when processing DropGlue.
///
/// When generating code for a Drop terminator, users can ignore an empty drop glue.
Expand Down Expand Up @@ -201,7 +201,7 @@ impl TryFrom<CrateItem> for Instance {
if !context.requires_monomorphization(def_id) {
Ok(context.mono_instance(def_id))
} else {
Err(Error::new("Item requires monomorphization".to_string()))
Err(bridge::Error::new("Item requires monomorphization".to_string()))
}
})
}
Expand All @@ -217,7 +217,7 @@ impl TryFrom<Instance> for CrateItem {
if value.kind == InstanceKind::Item && context.has_body(value.def.def_id()) {
Ok(CrateItem(context.instance_def_id(value.def)))
} else {
Err(Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
Err(bridge::Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
}
})
}
Expand Down Expand Up @@ -263,7 +263,7 @@ impl TryFrom<CrateItem> for StaticDef {
if matches!(value.kind(), ItemKind::Static) {
Ok(StaticDef(value.0))
} else {
Err(Error::new(format!("Expected a static item, but found: {value:?}")))
Err(bridge::Error::new(format!("Expected a static item, but found: {value:?}")))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_public/src/mir/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Implement methods to pretty print stable MIR body.
//! Implement methods to pretty print rustc_public's IR body.
use std::fmt::Debug;
use std::io::Write;
use std::{fmt, io, iter};
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_public/src/mir/visit.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! # The Stable MIR Visitor
//! # The rustc_public's IR Visitor
//!
//! ## Overview
//!
Expand Down
Loading
Loading