Add dataflow-based const validation

This commit is contained in:
Dylan MacKenzie 2019-09-17 16:25:40 -07:00
parent 3698d04fef
commit fc92d3b820
4 changed files with 1292 additions and 0 deletions

View File

@ -0,0 +1,45 @@
use rustc::hir::def_id::DefId;
use rustc::mir;
use rustc::ty::{self, TyCtxt};
pub use self::qualifs::Qualif;
mod resolver;
mod qualifs;
pub mod validation;
/// Information about the item currently being validated, as well as a reference to the global
/// context.
pub struct Item<'mir, 'tcx> {
body: &'mir mir::Body<'tcx>,
tcx: TyCtxt<'tcx>,
def_id: DefId,
param_env: ty::ParamEnv<'tcx>,
mode: validation::Mode,
}
impl Item<'mir, 'tcx> {
pub fn new(
tcx: TyCtxt<'tcx>,
def_id: DefId,
body: &'mir mir::Body<'tcx>,
) -> Self {
let param_env = tcx.param_env(def_id);
let mode = validation::Mode::for_item(tcx, def_id)
.expect("const validation must only be run inside a const context");
Item {
body,
tcx,
def_id,
param_env,
mode,
}
}
}
fn is_lang_panic_fn(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
Some(def_id) == tcx.lang_items().panic_fn() ||
Some(def_id) == tcx.lang_items().begin_panic_fn()
}

View File

@ -0,0 +1,327 @@
use rustc::mir::visit::Visitor;
use rustc::mir::{self, BasicBlock, Local, Location};
use rustc_data_structures::bit_set::BitSet;
use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
use crate::dataflow::{self as old_dataflow, generic as dataflow};
use super::{Item, Qualif};
use self::old_dataflow::IndirectlyMutableLocals;
/// A `Visitor` that propagates qualifs between locals. This defines the transfer function of
/// `FlowSensitiveAnalysis` as well as the logic underlying `TempPromotionResolver`.
///
/// This transfer does nothing when encountering an indirect assignment. Consumers should rely on
/// the `IndirectlyMutableLocals` dataflow pass to see if a `Local` may have become qualified via
/// an indirect assignment or function call.
struct TransferFunction<'a, 'mir, 'tcx, Q> {
item: &'a Item<'mir, 'tcx>,
qualifs_per_local: &'a mut BitSet<Local>,
_qualif: PhantomData<Q>,
}
impl<Q> TransferFunction<'a, 'mir, 'tcx, Q>
where
Q: Qualif,
{
fn new(
item: &'a Item<'mir, 'tcx>,
qualifs_per_local: &'a mut BitSet<Local>,
) -> Self {
TransferFunction {
item,
qualifs_per_local,
_qualif: PhantomData,
}
}
fn initialize_state(&mut self) {
self.qualifs_per_local.clear();
for arg in self.item.body.args_iter() {
let arg_ty = self.item.body.local_decls[arg].ty;
if Q::in_any_value_of_ty(self.item, arg_ty).unwrap() {
self.qualifs_per_local.insert(arg);
}
}
}
fn assign_qualif_direct(&mut self, place: &mir::Place<'tcx>, value: bool) {
debug_assert!(!place.is_indirect());
match (value, place) {
(true, mir::Place { base: mir::PlaceBase::Local(local), .. }) => {
self.qualifs_per_local.insert(*local);
}
// For now, we do not clear the qualif if a local is overwritten in full by
// an unqualified rvalue (e.g. `y = 5`). This is to be consistent
// with aggregates where we overwrite all fields with assignments, which would not
// get this feature.
(false, mir::Place { base: mir::PlaceBase::Local(_local), projection: box [] }) => {
// self.qualifs_per_local.remove(*local);
}
_ => {}
}
}
fn apply_call_return_effect(
&mut self,
_block: BasicBlock,
func: &mir::Operand<'tcx>,
args: &[mir::Operand<'tcx>],
return_place: &mir::Place<'tcx>,
) {
let return_ty = return_place.ty(self.item.body, self.item.tcx).ty;
let qualif = Q::in_call(self.item, &mut self.qualifs_per_local, func, args, return_ty);
if !return_place.is_indirect() {
self.assign_qualif_direct(return_place, qualif);
}
}
}
impl<Q> Visitor<'tcx> for TransferFunction<'_, '_, 'tcx, Q>
where
Q: Qualif,
{
fn visit_operand(&mut self, operand: &mir::Operand<'tcx>, location: Location) {
self.super_operand(operand, location);
if !Q::IS_CLEARED_ON_MOVE {
return;
}
// If a local with no projections is moved from (e.g. `x` in `y = x`), record that
// it no longer needs to be dropped.
if let mir::Operand::Move(mir::Place {
base: mir::PlaceBase::Local(local),
projection: box [],
}) = *operand {
self.qualifs_per_local.remove(local);
}
}
fn visit_assign(
&mut self,
place: &mir::Place<'tcx>,
rvalue: &mir::Rvalue<'tcx>,
location: Location,
) {
let qualif = Q::in_rvalue(self.item, self.qualifs_per_local, rvalue);
if !place.is_indirect() {
self.assign_qualif_direct(place, qualif);
}
// We need to assign qualifs to the left-hand side before visiting `rvalue` since
// qualifs can be cleared on move.
self.super_assign(place, rvalue, location);
}
fn visit_terminator_kind(&mut self, kind: &mir::TerminatorKind<'tcx>, location: Location) {
// The effect of assignment to the return place in `TerminatorKind::Call` is not applied
// here; that occurs in `apply_call_return_effect`.
if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind {
let qualif = Q::in_operand(self.item, self.qualifs_per_local, value);
if !dest.is_indirect() {
self.assign_qualif_direct(dest, qualif);
}
}
// We need to assign qualifs to the dropped location before visiting the operand that
// replaces it since qualifs can be cleared on move.
self.super_terminator_kind(kind, location);
}
}
/// Types that can compute the qualifs of each local at each location in a `mir::Body`.
///
/// Code that wishes to use a `QualifResolver` must call `visit_{statement,terminator}` for each
/// statement or terminator, processing blocks in reverse post-order beginning from the
/// `START_BLOCK`. Calling code may optionally call `get` after visiting each statement or
/// terminator to query the qualification state immediately before that statement or terminator.
///
/// These conditions are much more restrictive than woud be required by `FlowSensitiveResolver`
/// alone. This is to allow a linear, on-demand `TempPromotionResolver` that can operate
/// efficiently on simple CFGs.
pub trait QualifResolver<Q> {
/// Get the qualifs of each local at the last location visited.
///
/// This takes `&mut self` so qualifs can be computed lazily.
fn get(&mut self) -> &BitSet<Local>;
/// A convenience method for `self.get().contains(local)`.
fn contains(&mut self, local: Local) -> bool {
self.get().contains(local)
}
/// Resets the resolver to the `START_BLOCK`. This allows a resolver to be reused
/// for multiple passes over a `mir::Body`.
fn reset(&mut self);
}
type IndirectlyMutableResults<'mir, 'tcx> =
old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
/// A resolver for qualifs that works on arbitrarily complex CFGs.
///
/// As soon as a `Local` becomes writable through a reference (as determined by the
/// `IndirectlyMutableLocals` dataflow pass), we must assume that it takes on all other qualifs
/// possible for its type. This is because no effort is made to track qualifs across indirect
/// assignments (e.g. `*p = x` or calls to opaque functions).
///
/// It is possible to be more precise here by waiting until an indirect assignment actually occurs
/// before marking a borrowed `Local` as qualified.
pub struct FlowSensitiveResolver<'a, 'mir, 'tcx, Q>
where
Q: Qualif,
{
location: Location,
indirectly_mutable_locals: Rc<RefCell<IndirectlyMutableResults<'mir, 'tcx>>>,
cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
qualifs_per_local: BitSet<Local>,
}
impl<Q> FlowSensitiveResolver<'a, 'mir, 'tcx, Q>
where
Q: Qualif,
{
pub fn new(
_: Q,
item: &'a Item<'mir, 'tcx>,
indirectly_mutable_locals: Rc<RefCell<IndirectlyMutableResults<'mir, 'tcx>>>,
dead_unwinds: &BitSet<BasicBlock>,
) -> Self {
let analysis = FlowSensitiveAnalysis {
item,
_qualif: PhantomData,
};
let results =
dataflow::Engine::new(item.body, dead_unwinds, analysis).iterate_to_fixpoint();
let cursor = dataflow::ResultsCursor::new(item.body, results);
FlowSensitiveResolver {
cursor,
indirectly_mutable_locals,
qualifs_per_local: BitSet::new_empty(item.body.local_decls.len()),
location: Location { block: mir::START_BLOCK, statement_index: 0 },
}
}
}
impl<Q> Visitor<'tcx> for FlowSensitiveResolver<'_, '_, 'tcx, Q>
where
Q: Qualif
{
fn visit_statement(&mut self, _: &mir::Statement<'tcx>, location: Location) {
self.location = location;
}
fn visit_terminator(&mut self, _: &mir::Terminator<'tcx>, location: Location) {
self.location = location;
}
}
impl<Q> QualifResolver<Q> for FlowSensitiveResolver<'_, '_, '_, Q>
where
Q: Qualif
{
fn get(&mut self) -> &BitSet<Local> {
let mut indirectly_mutable_locals = self.indirectly_mutable_locals.borrow_mut();
indirectly_mutable_locals.seek(self.location);
self.cursor.seek_before(self.location);
self.qualifs_per_local.overwrite(indirectly_mutable_locals.get());
self.qualifs_per_local.union(self.cursor.get());
&self.qualifs_per_local
}
fn contains(&mut self, local: Local) -> bool {
self.cursor.seek_before(self.location);
if self.cursor.get().contains(local) {
return true;
}
let mut indirectly_mutable_locals = self.indirectly_mutable_locals.borrow_mut();
indirectly_mutable_locals.seek(self.location);
indirectly_mutable_locals.get().contains(local)
}
fn reset(&mut self) {
self.location = Location { block: mir::START_BLOCK, statement_index: 0 };
}
}
/// The dataflow analysis used to propagate qualifs on arbitrary CFGs.
pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> {
item: &'a Item<'mir, 'tcx>,
_qualif: PhantomData<Q>,
}
impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>
where
Q: Qualif,
{
fn transfer_function(
&self,
state: &'a mut BitSet<Local>,
) -> TransferFunction<'a, 'mir, 'tcx, Q> {
TransferFunction::<Q>::new(self.item, state)
}
}
impl<Q> old_dataflow::BottomValue for FlowSensitiveAnalysis<'_, '_, '_, Q> {
const BOTTOM_VALUE: bool = false;
}
impl<Q> dataflow::Analysis<'tcx> for FlowSensitiveAnalysis<'_, '_, 'tcx, Q>
where
Q: Qualif,
{
type Idx = Local;
const NAME: &'static str = "flow_sensitive_qualif";
fn bits_per_block(&self, body: &mir::Body<'tcx>) -> usize {
body.local_decls.len()
}
fn initialize_start_block(&self, _body: &mir::Body<'tcx>, state: &mut BitSet<Self::Idx>) {
self.transfer_function(state).initialize_state();
}
fn apply_statement_effect(
&self,
state: &mut BitSet<Self::Idx>,
statement: &mir::Statement<'tcx>,
location: Location,
) {
self.transfer_function(state).visit_statement(statement, location);
}
fn apply_terminator_effect(
&self,
state: &mut BitSet<Self::Idx>,
terminator: &mir::Terminator<'tcx>,
location: Location,
) {
self.transfer_function(state).visit_terminator(terminator, location);
}
fn apply_call_return_effect(
&self,
state: &mut BitSet<Self::Idx>,
block: BasicBlock,
func: &mir::Operand<'tcx>,
args: &[mir::Operand<'tcx>],
return_place: &mir::Place<'tcx>,
) {
self.transfer_function(state).apply_call_return_effect(block, func, args, return_place)
}
}

View File

@ -0,0 +1,919 @@
use rustc::hir::{self, def_id::DefId};
use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
use rustc::mir::*;
use rustc::session::config::nightly_options;
use rustc::ty::cast::CastTy;
use rustc::ty::{self, TyCtxt};
use rustc_data_structures::bit_set::BitSet;
use rustc_target::spec::abi::Abi;
use syntax::feature_gate::{emit_feature_err, GateIssue};
use syntax::symbol::sym;
use syntax_pos::{Span, Symbol};
use std::cell::RefCell;
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
use crate::dataflow as old_dataflow;
use super::{Item, Qualif, is_lang_panic_fn};
use super::resolver::{QualifResolver, FlowSensitiveResolver};
use super::qualifs::{HasMutInterior, NeedsDrop};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CheckOpResult {
Forbidden,
Unleashed,
Allowed,
}
/// What kind of item we are in.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Mode {
/// A `static` item.
Static,
/// A `static mut` item.
StaticMut,
/// A `const fn` item.
ConstFn,
/// A `const` item or an anonymous constant (e.g. in array lengths).
Const,
}
impl Mode {
/// Returns the validation mode for the item with the given `DefId`, or `None` if this item
/// does not require validation (e.g. a non-const `fn`).
pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Self> {
use hir::BodyOwnerKind as HirKind;
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
let mode = match tcx.hir().body_owner_kind(hir_id) {
HirKind::Closure => return None,
HirKind::Fn if tcx.is_const_fn(def_id) => Mode::ConstFn,
HirKind::Fn => return None,
HirKind::Const => Mode::Const,
HirKind::Static(hir::MutImmutable) => Mode::Static,
HirKind::Static(hir::MutMutable) => Mode::StaticMut,
};
Some(mode)
}
pub fn is_static(self) -> bool {
match self {
Mode::Static | Mode::StaticMut => true,
Mode::ConstFn | Mode::Const => false,
}
}
/// Returns `true` if the value returned by this item must be `Sync`.
///
/// This returns false for `StaticMut` since all accesses to one are `unsafe` anyway.
pub fn requires_sync(self) -> bool {
match self {
Mode::Static => true,
Mode::ConstFn | Mode::Const | Mode::StaticMut => false,
}
}
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Mode::Const => write!(f, "constant"),
Mode::Static | Mode::StaticMut => write!(f, "static"),
Mode::ConstFn => write!(f, "constant function"),
}
}
}
/// An operation that is not *always* allowed in a const context.
pub trait NonConstOp {
/// Whether this operation can be evaluated by miri.
const IS_SUPPORTED_IN_MIRI: bool = true;
/// Returns a boolean indicating whether the feature gate that would allow this operation is
/// enabled, or `None` if such a feature gate does not exist.
fn feature_gate(_tcx: TyCtxt<'tcx>) -> Option<bool> {
None
}
/// Returns `true` if this operation is allowed in the given item.
///
/// This check should assume that we are not in a non-const `fn`, where all operations are
/// legal.
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
Self::feature_gate(item.tcx).unwrap_or(false)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
span,
E0019,
"{} contains unimplemented expression type",
item.mode
);
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.note("A function call isn't allowed in the const's initialization expression \
because the expression's value must be known at compile-time.");
err.note("Remember: you can't use a function call inside a const's initialization \
expression! However, you can use it anywhere else.");
}
err.emit();
}
}
pub struct Qualifs<'a, 'mir, 'tcx> {
has_mut_interior: FlowSensitiveResolver<'a, 'mir, 'tcx, HasMutInterior>,
needs_drop: FlowSensitiveResolver<'a, 'mir, 'tcx, NeedsDrop>,
}
pub struct Validator<'a, 'mir, 'tcx> {
item: &'a Item<'mir, 'tcx>,
qualifs: Qualifs<'a, 'mir, 'tcx>,
/// The span of the current statement.
span: Span,
/// True if the local was assigned the result of an illegal borrow (`ops::MutBorrow`).
///
/// This is used to hide errors from {re,}borrowing the newly-assigned local, instead pointing
/// the user to the place where the illegal borrow occurred. This set is only populated once an
/// error has been emitted, so it will never cause an erroneous `mir::Body` to pass validation.
///
/// FIXME(ecstaticmorse): assert at the end of checking that if `tcx.has_errors() == false`,
/// this set is empty. Note that if we start removing locals from
/// `derived_from_illegal_borrow`, just checking at the end won't be enough.
derived_from_illegal_borrow: BitSet<Local>,
errors: Vec<(Span, String)>,
/// Whether to actually emit errors or just store them in `errors`.
pub(crate) suppress_errors: bool,
}
impl Deref for Validator<'_, 'mir, 'tcx> {
type Target = Item<'mir, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.item
}
}
impl Validator<'a, 'mir, 'tcx> {
pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
let indirectly_mutable_locals = old_dataflow::do_dataflow(
item.tcx,
item.body,
item.def_id,
&[],
&dead_unwinds,
old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
|_, local| old_dataflow::DebugFormatted::new(&local),
);
let indirectly_mutable_locals = old_dataflow::DataflowResultsCursor::new(
indirectly_mutable_locals,
item.body,
);
let indirectly_mutable_locals = Rc::new(RefCell::new(indirectly_mutable_locals));
let needs_drop = FlowSensitiveResolver::new(
NeedsDrop,
item,
indirectly_mutable_locals.clone(),
&dead_unwinds,
);
let has_mut_interior = FlowSensitiveResolver::new(
HasMutInterior,
item,
indirectly_mutable_locals.clone(),
&dead_unwinds,
);
let qualifs = Qualifs {
needs_drop,
has_mut_interior,
};
Validator {
span: item.body.span,
item,
qualifs,
errors: vec![],
derived_from_illegal_borrow: BitSet::new_empty(item.body.local_decls.len()),
suppress_errors: false,
}
}
/// Resets the `QualifResolver`s used by this `Validator` and returns them so they can be
/// reused.
pub fn into_qualifs(mut self) -> Qualifs<'a, 'mir, 'tcx> {
self.qualifs.needs_drop.reset();
self.qualifs.has_mut_interior.reset();
self.qualifs
}
pub fn take_errors(&mut self) -> Vec<(Span, String)> {
std::mem::replace(&mut self.errors, vec![])
}
/// Emits an error at the given `span` if an expression cannot be evaluated in the current
/// context. Returns `Forbidden` if an error was emitted.
pub fn check_op_spanned<O>(&mut self, op: O, span: Span) -> CheckOpResult
where
O: NonConstOp + fmt::Debug
{
trace!("check_op: op={:?}", op);
if op.is_allowed_in_item(self) {
return CheckOpResult::Allowed;
}
// If an operation is supported in miri (and is not already controlled by a feature gate) it
// can be turned on with `-Zunleash-the-miri-inside-of-you`.
let is_unleashable = O::IS_SUPPORTED_IN_MIRI
&& O::feature_gate(self.tcx).is_none();
if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
self.tcx.sess.span_warn(span, "skipping const checks");
return CheckOpResult::Unleashed;
}
if !self.suppress_errors {
op.emit_error(self, span);
}
self.errors.push((span, format!("{:?}", op)));
CheckOpResult::Forbidden
}
/// Emits an error if an expression cannot be evaluated in the current context.
pub fn check_op(&mut self, op: impl NonConstOp + fmt::Debug) -> CheckOpResult {
let span = self.span;
self.check_op_spanned(op, span)
}
}
impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
// Check nested operands and places.
if let Rvalue::Ref(_, kind, ref place) = *rvalue {
// Special-case reborrows to be more like a copy of a reference.
let mut reborrow_place = None;
if let box [proj_base @ .., elem] = &place.projection {
if *elem == ProjectionElem::Deref {
let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
if let ty::Ref(..) = base_ty.sty {
reborrow_place = Some(proj_base);
}
}
}
if let Some(proj) = reborrow_place {
let ctx = match kind {
BorrowKind::Shared => PlaceContext::NonMutatingUse(
NonMutatingUseContext::SharedBorrow,
),
BorrowKind::Shallow => PlaceContext::NonMutatingUse(
NonMutatingUseContext::ShallowBorrow,
),
BorrowKind::Unique => PlaceContext::NonMutatingUse(
NonMutatingUseContext::UniqueBorrow,
),
BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
MutatingUseContext::Borrow,
),
};
self.visit_place_base(&place.base, ctx, location);
self.visit_projection(&place.base, proj, ctx, location);
} else {
self.super_rvalue(rvalue, location);
}
} else {
self.super_rvalue(rvalue, location);
}
match *rvalue {
Rvalue::Use(_) |
Rvalue::Repeat(..) |
Rvalue::UnaryOp(UnOp::Neg, _) |
Rvalue::UnaryOp(UnOp::Not, _) |
Rvalue::NullaryOp(NullOp::SizeOf, _) |
Rvalue::CheckedBinaryOp(..) |
Rvalue::Cast(CastKind::Pointer(_), ..) |
Rvalue::Discriminant(..) |
Rvalue::Len(_) |
Rvalue::Ref(..) |
Rvalue::Aggregate(..) => {}
Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
let operand_ty = operand.ty(self.body, self.tcx);
let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
if let (CastTy::Ptr(_), CastTy::Int(_))
| (CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
self.check_op(ops::RawPtrToIntCast);
}
}
Rvalue::BinaryOp(op, ref lhs, _) => {
if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).sty {
assert!(op == BinOp::Eq || op == BinOp::Ne ||
op == BinOp::Le || op == BinOp::Lt ||
op == BinOp::Ge || op == BinOp::Gt ||
op == BinOp::Offset);
self.check_op(ops::RawPtrComparison);
}
}
Rvalue::NullaryOp(NullOp::Box, _) => {
self.check_op(ops::HeapAllocation);
}
}
}
fn visit_place_base(
&mut self,
place_base: &PlaceBase<'tcx>,
context: PlaceContext,
location: Location,
) {
trace!(
"visit_place_base: place_base={:?} context={:?} location={:?}",
place_base,
context,
location,
);
self.super_place_base(place_base, context, location);
match place_base {
PlaceBase::Local(_) => {}
PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_, _), .. }) => {
bug!("Promotion must be run after const validation");
}
PlaceBase::Static(box Static{ kind: StaticKind::Static, def_id, .. }) => {
let is_thread_local = self.tcx.has_attr(*def_id, sym::thread_local);
if is_thread_local {
self.check_op(ops::ThreadLocalAccess);
} else if self.mode == Mode::Static && context.is_mutating_use() {
// this is not strictly necessary as miri will also bail out
// For interior mutability we can't really catch this statically as that
// goes through raw pointers and intermediate temporaries, so miri has
// to catch this anyway
self.tcx.sess.span_err(
self.span,
"cannot mutate statics in the initializer of another static",
);
} else {
self.check_op(ops::StaticAccess);
}
}
}
}
fn visit_assign(&mut self, dest: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
trace!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
// Error on mutable borrows or shared borrows of values with interior mutability.
//
// This replicates the logic at the start of `assign` in the old const checker. Note that
// it depends on `HasMutInterior` being set for mutable borrows as well as values with
// interior mutability.
if let Rvalue::Ref(_, kind, ref borrowed_place) = *rvalue {
let rvalue_has_mut_interior = HasMutInterior::in_rvalue(
&self.item,
self.qualifs.has_mut_interior.get(),
rvalue,
);
if rvalue_has_mut_interior {
let is_derived_from_illegal_borrow = match *borrowed_place {
// If an unprojected local was borrowed and its value was the result of an
// illegal borrow, suppress this error and mark the result of this borrow as
// illegal as well.
Place { base: PlaceBase::Local(borrowed_local), projection: box [] }
if self.derived_from_illegal_borrow.contains(borrowed_local) => true,
// Otherwise proceed normally: check the legality of a mutable borrow in this
// context.
_ => self.check_op(ops::MutBorrow(kind)) == CheckOpResult::Forbidden,
};
// When the target of the assignment is a local with no projections, mark it as
// derived from an illegal borrow if necessary.
//
// FIXME: should we also clear `derived_from_illegal_borrow` when a local is
// assigned a new value?
if is_derived_from_illegal_borrow {
if let Place { base: PlaceBase::Local(dest), projection: box [] } = *dest {
self.derived_from_illegal_borrow.insert(dest);
}
}
}
}
self.super_assign(dest, rvalue, location);
}
fn visit_projection(
&mut self,
place_base: &PlaceBase<'tcx>,
proj: &[PlaceElem<'tcx>],
context: PlaceContext,
location: Location,
) {
trace!(
"visit_place_projection: proj={:?} context={:?} location={:?}",
proj,
context,
location,
);
self.super_projection(place_base, proj, context, location);
let (elem, proj_base) = match proj.split_last() {
Some(x) => x,
None => return,
};
match elem {
ProjectionElem::Deref => {
if context.is_mutating_use() {
self.check_op(ops::MutDeref);
}
let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
if let ty::RawPtr(_) = base_ty.sty {
self.check_op(ops::RawPtrDeref);
}
}
ProjectionElem::ConstantIndex {..} |
ProjectionElem::Subslice {..} |
ProjectionElem::Field(..) |
ProjectionElem::Index(_) => {
let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
match base_ty.ty_adt_def() {
Some(def) if def.is_union() => {
self.check_op(ops::UnionAccess);
}
_ => {}
}
}
ProjectionElem::Downcast(..) => {
self.check_op(ops::Downcast);
}
}
}
fn visit_source_info(&mut self, source_info: &SourceInfo) {
trace!("visit_source_info: source_info={:?}", source_info);
self.span = source_info.span;
}
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
trace!("visit_statement: statement={:?} location={:?}", statement, location);
self.qualifs.needs_drop.visit_statement(statement, location);
self.qualifs.has_mut_interior.visit_statement(statement, location);
debug!("needs_drop: {:?}", self.qualifs.needs_drop.get());
debug!("has_mut_interior: {:?}", self.qualifs.has_mut_interior.get());
match statement.kind {
StatementKind::Assign(..) => {
self.super_statement(statement, location);
}
StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
self.check_op(ops::IfOrMatch);
}
// FIXME(eddyb) should these really do nothing?
StatementKind::FakeRead(..) |
StatementKind::SetDiscriminant { .. } |
StatementKind::StorageLive(_) |
StatementKind::StorageDead(_) |
StatementKind::InlineAsm {..} |
StatementKind::Retag { .. } |
StatementKind::AscribeUserType(..) |
StatementKind::Nop => {}
}
}
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
trace!("visit_terminator: terminator={:?} location={:?}", terminator, location);
self.qualifs.needs_drop.visit_terminator(terminator, location);
self.qualifs.has_mut_interior.visit_terminator(terminator, location);
debug!("needs_drop: {:?}", self.qualifs.needs_drop.get());
debug!("has_mut_interior: {:?}", self.qualifs.has_mut_interior.get());
self.super_terminator(terminator, location);
}
fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
self.super_terminator_kind(kind, location);
match kind {
TerminatorKind::Call { func, .. } => {
let fn_ty = func.ty(self.body, self.tcx);
let def_id = match fn_ty.sty {
ty::FnDef(def_id, _) => def_id,
ty::FnPtr(_) => {
self.check_op(ops::FnCallIndirect);
return;
}
_ => {
self.check_op(ops::FnCallOther);
return;
}
};
// At this point, we are calling a function whose `DefId` is known...
if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
assert!(!self.tcx.is_const_fn(def_id));
if self.tcx.item_name(def_id) == sym::transmute {
self.check_op(ops::Transmute);
return;
}
// To preserve the current semantics, we return early, allowing all
// intrinsics (except `transmute`) to pass unchecked to miri.
//
// FIXME: We should keep a whitelist of allowed intrinsics (or at least a
// blacklist of unimplemented ones) and fail here instead.
return;
}
if self.tcx.is_const_fn(def_id) {
return;
}
if is_lang_panic_fn(self.tcx, def_id) {
self.check_op(ops::Panic);
} else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
// Exempt unstable const fns inside of macros with
// `#[allow_internal_unstable]`.
if !self.span.allows_unstable(feature) {
self.check_op(ops::FnCallUnstable(def_id, feature));
}
} else {
self.check_op(ops::FnCallNonConst(def_id));
}
}
// Forbid all `Drop` terminators unless the place being dropped is a local with no
// projections that cannot be `NeedsDrop`.
| TerminatorKind::Drop { location: dropped_place, .. }
| TerminatorKind::DropAndReplace { location: dropped_place, .. }
=> {
let mut err_span = self.span;
// Check to see if the type of this place can ever have a drop impl. If not, this
// `Drop` terminator is frivolous.
let ty_needs_drop = dropped_place
.ty(self.body, self.tcx)
.ty
.needs_drop(self.tcx, self.param_env);
if !ty_needs_drop {
return;
}
let needs_drop = if let Place {
base: PlaceBase::Local(local),
projection: box [],
} = *dropped_place {
// Use the span where the local was declared as the span of the drop error.
err_span = self.body.local_decls[local].source_info.span;
self.qualifs.needs_drop.contains(local)
} else {
true
};
if needs_drop {
self.check_op_spanned(ops::LiveDrop, err_span);
}
}
_ => {}
}
}
}
/// All implementers of `NonConstOp`.
pub mod ops {
use super::*;
/// A `Downcast` projection.
#[derive(Debug)]
pub struct Downcast;
impl NonConstOp for Downcast {}
/// A function call where the callee is a pointer.
#[derive(Debug)]
pub struct FnCallIndirect;
impl NonConstOp for FnCallIndirect {
const IS_SUPPORTED_IN_MIRI: bool = false;
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let mut err = item.tcx.sess.struct_span_err(
span,
&format!("function pointers are not allowed in const fn"));
err.emit();
}
}
/// A function call where the callee is not marked as `const`.
#[derive(Debug)]
pub struct FnCallNonConst(pub DefId);
impl NonConstOp for FnCallNonConst {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
span,
E0015,
"calls in {}s are limited to constant functions, \
tuple structs and tuple variants",
item.mode,
);
err.emit();
}
}
/// A function call where the callee is not a function definition or function pointer, e.g. a
/// closure.
///
/// This can be subdivided in the future to produce a better error message.
#[derive(Debug)]
pub struct FnCallOther;
impl NonConstOp for FnCallOther {
const IS_SUPPORTED_IN_MIRI: bool = false;
}
/// A call to a `#[unstable]` const fn or `#[rustc_const_unstable]` function.
///
/// Contains the name of the feature that would allow the use of this function.
#[derive(Debug)]
pub struct FnCallUnstable(pub DefId, pub Symbol);
impl NonConstOp for FnCallUnstable {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let FnCallUnstable(def_id, feature) = *self;
let mut err = item.tcx.sess.struct_span_err(span,
&format!("`{}` is not yet stable as a const fn",
item.tcx.def_path_str(def_id)));
if nightly_options::is_nightly_build() {
help!(&mut err,
"add `#![feature({})]` to the \
crate attributes to enable",
feature);
}
err.emit();
}
}
#[derive(Debug)]
pub struct HeapAllocation;
impl NonConstOp for HeapAllocation {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let mut err = struct_span_err!(item.tcx.sess, span, E0010,
"allocations are not allowed in {}s", item.mode);
err.span_label(span, format!("allocation not allowed in {}s", item.mode));
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"The value of statics and constants must be known at compile time, \
and they live for the entire lifetime of a program. Creating a boxed \
value allocates memory on the heap at runtime, and therefore cannot \
be done at compile time."
);
}
err.emit();
}
}
#[derive(Debug)]
pub struct IfOrMatch;
impl NonConstOp for IfOrMatch {}
#[derive(Debug)]
pub struct LiveDrop;
impl NonConstOp for LiveDrop {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
struct_span_err!(item.tcx.sess, span, E0493,
"destructors cannot be evaluated at compile-time")
.span_label(span, format!("{}s cannot evaluate destructors",
item.mode))
.emit();
}
}
#[derive(Debug)]
pub struct Loop;
impl NonConstOp for Loop {}
#[derive(Debug)]
pub struct MutBorrow(pub BorrowKind);
impl NonConstOp for MutBorrow {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let kind = self.0;
if let BorrowKind::Mut { .. } = kind {
let mut err = struct_span_err!(item.tcx.sess, span, E0017,
"references in {}s may only refer \
to immutable values", item.mode);
err.span_label(span, format!("{}s require immutable values",
item.mode));
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.note("References in statics and constants may only refer \
to immutable values.\n\n\
Statics are shared everywhere, and if they refer to \
mutable data one might violate memory safety since \
holding multiple mutable references to shared data \
is not allowed.\n\n\
If you really want global mutable state, try using \
static mut or a global UnsafeCell.");
}
err.emit();
} else {
span_err!(item.tcx.sess, span, E0492,
"cannot borrow a constant which may contain \
interior mutability, create a static instead");
}
}
}
#[derive(Debug)]
pub struct MutDeref;
impl NonConstOp for MutDeref {}
#[derive(Debug)]
pub struct Panic;
impl NonConstOp for Panic {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_panic)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess,
sym::const_panic,
span,
GateIssue::Language,
&format!("panicking in {}s is unstable", item.mode),
);
}
}
#[derive(Debug)]
pub struct RawPtrComparison;
impl NonConstOp for RawPtrComparison {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_compare_raw_pointers)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess,
sym::const_compare_raw_pointers,
span,
GateIssue::Language,
&format!("comparing raw pointers inside {}", item.mode),
);
}
}
#[derive(Debug)]
pub struct RawPtrDeref;
impl NonConstOp for RawPtrDeref {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_raw_ptr_deref)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess, sym::const_raw_ptr_deref,
span, GateIssue::Language,
&format!(
"dereferencing raw pointers in {}s is unstable",
item.mode,
),
);
}
}
#[derive(Debug)]
pub struct RawPtrToIntCast;
impl NonConstOp for RawPtrToIntCast {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_raw_ptr_to_usize_cast)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast,
span, GateIssue::Language,
&format!(
"casting pointers to integers in {}s is unstable",
item.mode,
),
);
}
}
/// An access to a (non-thread-local) `static`.
#[derive(Debug)]
pub struct StaticAccess;
impl NonConstOp for StaticAccess {
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
item.mode.is_static()
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
let mut err = struct_span_err!(item.tcx.sess, span, E0013,
"{}s cannot refer to statics, use \
a constant instead", item.mode);
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"Static and const variables can refer to other const variables. \
But a const variable cannot refer to a static variable."
);
err.help(
"To fix this, the value can be extracted as a const and then used."
);
}
err.emit();
}
}
/// An access to a thread-local `static`.
#[derive(Debug)]
pub struct ThreadLocalAccess;
impl NonConstOp for ThreadLocalAccess {
const IS_SUPPORTED_IN_MIRI: bool = false;
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
span_err!(item.tcx.sess, span, E0625,
"thread-local statics cannot be \
accessed at compile-time");
}
}
#[derive(Debug)]
pub struct Transmute;
impl NonConstOp for Transmute {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_transmute)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess, sym::const_transmute,
span, GateIssue::Language,
&format!("The use of std::mem::transmute() \
is gated in {}s", item.mode));
}
}
#[derive(Debug)]
pub struct UnionAccess;
impl NonConstOp for UnionAccess {
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
// Union accesses are stable in all contexts except `const fn`.
item.mode != Mode::ConstFn || Self::feature_gate(item.tcx).unwrap()
}
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_fn_union)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
emit_feature_err(
&item.tcx.sess.parse_sess, sym::const_fn_union,
span, GateIssue::Language,
"unions in const fn are unstable",
);
}
}
}

View File

@ -15,6 +15,7 @@ use syntax_pos::Span;
pub mod add_retag;
pub mod add_moves_for_packed_drops;
pub mod cleanup_post_borrowck;
pub mod check_consts;
pub mod check_unsafety;
pub mod simplify_branches;
pub mod simplify;