Skip to content
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

Make libcore pass -Zvalidate-mir #73175

Closed
wants to merge 5 commits into from
Closed
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
82 changes: 72 additions & 10 deletions src/librustc_mir/transform/validate.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
//! Validates the MIR to ensure that invariants are upheld.

use super::{MirPass, MirSource};
use rustc_hir::lang_items::FnOnceTraitLangItem;
use rustc_hir::Constness;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_middle::mir::visit::Visitor;
use rustc_middle::{
mir::{
BasicBlock, Body, Location, Operand, Rvalue, Statement, StatementKind, Terminator,
TerminatorKind,
},
ty::{self, ParamEnv, TyCtxt},
ty::{self, ParamEnv, ToPredicate, Ty, TyCtxt},
};
use rustc_span::def_id::DefId;
use rustc_trait_selection::traits;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;

#[derive(Copy, Clone, Debug)]
enum EdgeKind {
Expand All @@ -26,12 +31,16 @@ impl<'tcx> MirPass<'tcx> for Validator {
fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
let def_id = source.def_id();
let param_env = tcx.param_env(def_id);
TypeChecker { when: &self.when, def_id, body, tcx, param_env }.visit_body(body);
let validating_shim =
if let ty::InstanceDef::Item(_) = source.instance { false } else { true };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's interesting, I thought this would be passed in. But I guess this works, too? I am not very familiar with InstanceDef.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have we found any instances where something that is not Self is being called? Because then you can also special-case this even further by checking that the callee is ty.is_param(0), instead of doing a trait query. And we could also only special-case the specific call shims we care about.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we have, but I think that this approach is a little more liberal in the sense that it allows shim implementations to change without changing the assumptions we require here - there's definitely a trade-off here though

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shims shouldn't grow more ways to violate the assumptions we make here, they should only change so they use an FnDef instead of Self as the callee eventually, fixing the underlying issue

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean to say that another class of shim could be introduced or a previously monomorphic shim could be made polymorphic

Copy link
Contributor Author

@doctorn doctorn Jun 14, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it's tidier to check ty.is_param(0), but we really would like Self to implement FnOnce right? It would almost certainly be malformed MIR if it didn't

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All I can think at the moment is that we include both checks?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would work too

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, you can just compare with tcx.types.self_param too

TypeChecker { when: &self.when, def_id, body, tcx, param_env, validating_shim }
.visit_body(body);
}
}

struct TypeChecker<'a, 'tcx> {
when: &'a str,
validating_shim: bool,
def_id: DefId,
body: &'a Body<'tcx>,
tcx: TyCtxt<'tcx>,
Expand Down Expand Up @@ -83,6 +92,66 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
}
}

fn check_ty_callable(&self, location: Location, ty: Ty<'tcx>) {
if let ty::FnPtr(..) | ty::FnDef(..) = ty.kind {
// We have a `FnPtr` or `FnDef` which is trivially safe to call.
doctorn marked this conversation as resolved.
Show resolved Hide resolved
//
// By this point, calls to closures should already have been lowered to calls to
// `Fn*::call*` so we do not consider them callable.
} else if self.validating_shim && ty == self.tcx.types.self_param {
// FIXME(#69925): we shouldn't be special-casing for call-shims as we'd hope they
// have concrete substs by this point.
//
// We haven't got a `FnPtr` or `FnDef` but if we're looking at a MIR shim, this could
// be due to a `Self` type still hanging about. To avoid rejecting these shims we
// any type in MIR shims as callable so long as:
// 1. it's `Self`
// 2. it implements `FnOnce`
let fn_once_trait = self.tcx.require_lang_item(FnOnceTraitLangItem, None);
let item_def_id = self
.tcx
.associated_items(fn_once_trait)
.in_definition_order()
.next()
.unwrap()
.def_id;
self.tcx.infer_ctxt().enter(|infcx| {
let trait_ref = ty::TraitRef {
def_id: fn_once_trait,
substs: self.tcx.mk_substs_trait(
ty,
infcx.fresh_substs_for_item(self.body.span, item_def_id),
),
};
let predicate = ty::PredicateKind::Trait(
ty::Binder::bind(ty::TraitPredicate { trait_ref }),
Constness::NotConst,
)
.to_predicate(self.tcx);
let obligation = traits::Obligation::new(
traits::ObligationCause::dummy(),
self.param_env,
predicate,
);
if !infcx.predicate_may_hold(&obligation) {
self.fail(
location,
format!(
"encountered {} in `Call` terminator of shim \
which does not implement `FnOnce`",
ty,
),
);
}
});
} else {
self.fail(
location,
format!("encountered non-callable type {} in `Call` terminator", ty),
);
}
}
}

impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
Expand Down Expand Up @@ -151,14 +220,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
}
}
TerminatorKind::Call { func, destination, cleanup, .. } => {
let func_ty = func.ty(&self.body.local_decls, self.tcx);
match func_ty.kind {
ty::FnPtr(..) | ty::FnDef(..) => {}
_ => self.fail(
location,
format!("encountered non-callable type {} in `Call` terminator", func_ty),
),
}
self.check_ty_callable(location, &func.ty(&self.body.local_decls, self.tcx));
if let Some((_, target)) = destination {
self.check_edge(location, *target, EdgeKind::Normal);
}
Expand Down