Rollup merge of #71198 - oli-obk:const_check_cleanup, r=RalfJung

Const check/promotion cleanup and sanity assertion

r? @RalfJung

This is just the part of https://github.com/rust-lang/rust/pull/70042#issuecomment-614592765 that does not change behaviour
This commit is contained in:
Dylan DPC 2020-04-23 15:57:13 +02:00 committed by GitHub
commit 629a613faa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 180 additions and 156 deletions

View File

@ -42,7 +42,10 @@ use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations}
use crate::dataflow::move_paths::MoveData;
use crate::dataflow::MaybeInitializedPlaces;
use crate::dataflow::ResultsCursor;
use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
use crate::transform::{
check_consts::ConstCx,
promote_consts::should_suggest_const_in_array_repeat_expressions_attribute,
};
use crate::borrow_check::{
borrow_set::BorrowSet,
@ -1984,14 +1987,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let span = body.source_info(location).span;
let ty = operand.ty(body, tcx);
if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
let ccx = ConstCx::new_with_param_env(
tcx,
self.mir_def_id,
body,
self.param_env,
);
// To determine if `const_in_array_repeat_expressions` feature gate should
// be mentioned, need to check if the rvalue is promotable.
let should_suggest =
should_suggest_const_in_array_repeat_expressions_attribute(
tcx,
self.mir_def_id,
body,
operand,
&ccx, operand,
);
debug!("check_rvalue: should_suggest={:?}", should_suggest);

View File

@ -20,7 +20,7 @@ pub mod validation;
/// Information about the item currently being const-checked, as well as a reference to the global
/// context.
pub struct Item<'mir, 'tcx> {
pub struct ConstCx<'mir, 'tcx> {
pub body: &'mir mir::Body<'tcx>,
pub tcx: TyCtxt<'tcx>,
pub def_id: DefId,
@ -28,12 +28,21 @@ pub struct Item<'mir, 'tcx> {
pub const_kind: Option<ConstKind>,
}
impl Item<'mir, 'tcx> {
impl ConstCx<'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);
Self::new_with_param_env(tcx, def_id, body, param_env)
}
pub fn new_with_param_env(
tcx: TyCtxt<'tcx>,
def_id: DefId,
body: &'mir mir::Body<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> Self {
let const_kind = ConstKind::for_item(tcx, def_id);
Item { body, tcx, def_id, param_env, const_kind }
ConstCx { body, tcx, def_id, param_env, const_kind }
}
/// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).

View File

@ -7,7 +7,7 @@ use rustc_session::parse::feature_err;
use rustc_span::symbol::sym;
use rustc_span::{Span, Symbol};
use super::{ConstKind, Item};
use super::{ConstCx, ConstKind};
/// An operation that is not *always* allowed in a const context.
pub trait NonConstOp: std::fmt::Debug {
@ -27,19 +27,19 @@ pub trait NonConstOp: std::fmt::Debug {
///
/// By default, it returns `true` if and only if this operation has a corresponding feature
/// gate and that gate is enabled.
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
Self::feature_gate().map_or(false, |gate| item.tcx.features().enabled(gate))
fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
Self::feature_gate().map_or(false, |gate| ccx.tcx.features().enabled(gate))
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0019,
"{} contains unimplemented expression type",
item.const_kind()
ccx.const_kind()
);
if item.tcx.sess.teach(&err.get_code().unwrap()) {
if ccx.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.",
@ -66,9 +66,9 @@ impl NonConstOp for Downcast {
#[derive(Debug)]
pub struct FnCallIndirect;
impl NonConstOp for FnCallIndirect {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err =
item.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn");
ccx.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn");
err.emit();
}
}
@ -77,14 +77,14 @@ impl NonConstOp for FnCallIndirect {
#[derive(Debug)]
pub struct FnCallNonConst(pub DefId);
impl NonConstOp for FnCallNonConst {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0015,
"calls in {}s are limited to constant functions, \
tuple structs and tuple variants",
item.const_kind(),
ccx.const_kind(),
);
err.emit();
}
@ -96,12 +96,12 @@ impl NonConstOp for FnCallNonConst {
#[derive(Debug)]
pub struct FnCallUnstable(pub DefId, pub Symbol);
impl NonConstOp for FnCallUnstable {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let FnCallUnstable(def_id, feature) = *self;
let mut err = item.tcx.sess.struct_span_err(
let mut err = ccx.tcx.sess.struct_span_err(
span,
&format!("`{}` is not yet stable as a const fn", item.tcx.def_path_str(def_id)),
&format!("`{}` is not yet stable as a const fn", ccx.tcx.def_path_str(def_id)),
);
if nightly_options::is_nightly_build() {
err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
@ -113,16 +113,16 @@ impl NonConstOp for FnCallUnstable {
#[derive(Debug)]
pub struct HeapAllocation;
impl NonConstOp for HeapAllocation {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0010,
"allocations are not allowed in {}s",
item.const_kind()
ccx.const_kind()
);
err.span_label(span, format!("allocation not allowed in {}s", item.const_kind()));
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.span_label(span, format!("allocation not allowed in {}s", ccx.const_kind()));
if ccx.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 \
@ -141,9 +141,9 @@ impl NonConstOp for IfOrMatch {
Some(sym::const_if_match)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
// This should be caught by the HIR const-checker.
item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
}
}
@ -154,14 +154,14 @@ impl NonConstOp for InlineAsm {}
#[derive(Debug)]
pub struct LiveDrop;
impl NonConstOp for LiveDrop {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0493,
"destructors cannot be evaluated at compile-time"
)
.span_label(span, format!("{}s cannot evaluate destructors", item.const_kind()))
.span_label(span, format!("{}s cannot evaluate destructors", ccx.const_kind()))
.emit();
}
}
@ -173,18 +173,18 @@ impl NonConstOp for Loop {
Some(sym::const_loop)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
// This should be caught by the HIR const-checker.
item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
}
}
#[derive(Debug)]
pub struct CellBorrow;
impl NonConstOp for CellBorrow {
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0492,
"cannot borrow a constant which may contain \
@ -201,19 +201,19 @@ impl NonConstOp for MutBorrow {
Some(sym::const_mut_refs)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err = feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_mut_refs,
span,
&format!(
"references in {}s may only refer \
to immutable values",
item.const_kind()
ccx.const_kind()
),
);
err.span_label(span, format!("{}s require immutable values", item.const_kind()));
if item.tcx.sess.teach(&err.get_code().unwrap()) {
err.span_label(span, format!("{}s require immutable values", ccx.const_kind()));
if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"References in statics and constants may only refer \
to immutable values.\n\n\
@ -236,12 +236,12 @@ impl NonConstOp for MutAddressOf {
Some(sym::const_mut_refs)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_mut_refs,
span,
&format!("`&raw mut` is not allowed in {}s", item.const_kind()),
&format!("`&raw mut` is not allowed in {}s", ccx.const_kind()),
)
.emit();
}
@ -262,12 +262,12 @@ impl NonConstOp for Panic {
Some(sym::const_panic)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_panic,
span,
&format!("panicking in {}s is unstable", item.const_kind()),
&format!("panicking in {}s is unstable", ccx.const_kind()),
)
.emit();
}
@ -280,12 +280,12 @@ impl NonConstOp for RawPtrComparison {
Some(sym::const_compare_raw_pointers)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_compare_raw_pointers,
span,
&format!("comparing raw pointers inside {}", item.const_kind()),
&format!("comparing raw pointers inside {}", ccx.const_kind()),
)
.emit();
}
@ -298,12 +298,12 @@ impl NonConstOp for RawPtrDeref {
Some(sym::const_raw_ptr_deref)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_raw_ptr_deref,
span,
&format!("dereferencing raw pointers in {}s is unstable", item.const_kind(),),
&format!("dereferencing raw pointers in {}s is unstable", ccx.const_kind(),),
)
.emit();
}
@ -316,12 +316,12 @@ impl NonConstOp for RawPtrToIntCast {
Some(sym::const_raw_ptr_to_usize_cast)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_raw_ptr_to_usize_cast,
span,
&format!("casting pointers to integers in {}s is unstable", item.const_kind(),),
&format!("casting pointers to integers in {}s is unstable", ccx.const_kind(),),
)
.emit();
}
@ -331,22 +331,22 @@ impl NonConstOp for RawPtrToIntCast {
#[derive(Debug)]
pub struct StaticAccess;
impl NonConstOp for StaticAccess {
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
item.const_kind().is_static()
fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
ccx.const_kind().is_static()
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
let mut err = struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0013,
"{}s cannot refer to statics",
item.const_kind()
ccx.const_kind()
);
err.help(
"consider extracting the value of the `static` to a `const`, and referring to that",
);
if item.tcx.sess.teach(&err.get_code().unwrap()) {
if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
err.note(
"`static` and `const` variables can refer to other `const` variables. \
A `const` variable, however, cannot refer to a `static` variable.",
@ -363,9 +363,9 @@ pub struct ThreadLocalAccess;
impl NonConstOp for ThreadLocalAccess {
const IS_SUPPORTED_IN_MIRI: bool = false;
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
struct_span_err!(
item.tcx.sess,
ccx.tcx.sess,
span,
E0625,
"thread-local statics cannot be \
@ -378,19 +378,19 @@ impl NonConstOp for ThreadLocalAccess {
#[derive(Debug)]
pub struct UnionAccess;
impl NonConstOp for UnionAccess {
fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
// Union accesses are stable in all contexts except `const fn`.
item.const_kind() != ConstKind::ConstFn
|| item.tcx.features().enabled(Self::feature_gate().unwrap())
ccx.const_kind() != ConstKind::ConstFn
|| ccx.tcx.features().enabled(Self::feature_gate().unwrap())
}
fn feature_gate() -> Option<Symbol> {
Some(sym::const_fn_union)
}
fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
feature_err(
&item.tcx.sess.parse_sess,
&ccx.tcx.sess.parse_sess,
sym::const_fn_union,
span,
"unions in const fn are unstable",

View File

@ -6,7 +6,7 @@ use rustc_middle::mir::*;
use rustc_middle::ty::{self, AdtDef, Ty};
use rustc_span::DUMMY_SP;
use super::Item as ConstCx;
use super::ConstCx;
pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs {
ConstQualifs {

View File

@ -8,7 +8,7 @@ use rustc_middle::mir::{self, BasicBlock, Local, Location};
use std::marker::PhantomData;
use super::{qualifs, Item, Qualif};
use super::{qualifs, ConstCx, Qualif};
use crate::dataflow;
/// A `Visitor` that propagates qualifs between locals. This defines the transfer function of
@ -18,7 +18,7 @@ use crate::dataflow;
/// the `MaybeMutBorrowedLocals` 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>,
ccx: &'a ConstCx<'mir, 'tcx>,
qualifs_per_local: &'a mut BitSet<Local>,
_qualif: PhantomData<Q>,
@ -28,16 +28,16 @@ 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 new(ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet<Local>) -> Self {
TransferFunction { ccx, 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) {
for arg in self.ccx.body.args_iter() {
let arg_ty = self.ccx.body.local_decls[arg].ty;
if Q::in_any_value_of_ty(self.ccx, arg_ty) {
self.qualifs_per_local.insert(arg);
}
}
@ -72,8 +72,8 @@ where
) {
// We cannot reason about another function's internals, so use conservative type-based
// qualification for the result of a function call.
let return_ty = return_place.ty(self.item.body, self.item.tcx).ty;
let qualif = Q::in_any_value_of_ty(self.item, return_ty);
let return_ty = return_place.ty(self.ccx.body, self.ccx.tcx).ty;
let qualif = Q::in_any_value_of_ty(self.ccx, return_ty);
if !return_place.is_indirect() {
self.assign_qualif_direct(&return_place, qualif);
@ -108,7 +108,7 @@ where
location: Location,
) {
let qualif = qualifs::in_rvalue::<Q, _>(
self.item,
self.ccx,
&mut |l| self.qualifs_per_local.contains(l),
rvalue,
);
@ -127,7 +127,7 @@ where
if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind {
let qualif = qualifs::in_operand::<Q, _>(
self.item,
self.ccx,
&mut |l| self.qualifs_per_local.contains(l),
value,
);
@ -145,7 +145,7 @@ where
/// The dataflow analysis used to propagate qualifs on arbitrary CFGs.
pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> {
item: &'a Item<'mir, 'tcx>,
ccx: &'a ConstCx<'mir, 'tcx>,
_qualif: PhantomData<Q>,
}
@ -153,15 +153,15 @@ impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>
where
Q: Qualif,
{
pub(super) fn new(_: Q, item: &'a Item<'mir, 'tcx>) -> Self {
FlowSensitiveAnalysis { item, _qualif: PhantomData }
pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
FlowSensitiveAnalysis { ccx, _qualif: PhantomData }
}
fn transfer_function(
&self,
state: &'a mut BitSet<Local>,
) -> TransferFunction<'a, 'mir, 'tcx, Q> {
TransferFunction::<Q>::new(self.item, state)
TransferFunction::<Q>::new(self.ccx, state)
}
}

View File

@ -20,7 +20,7 @@ use std::ops::Deref;
use super::ops::{self, NonConstOp};
use super::qualifs::{self, HasMutInterior, NeedsDrop};
use super::resolver::FlowSensitiveAnalysis;
use super::{is_lang_panic_fn, ConstKind, Item, Qualif};
use super::{is_lang_panic_fn, ConstCx, ConstKind, Qualif};
use crate::const_eval::{is_const_fn, is_unstable_const_fn};
use crate::dataflow::MaybeMutBorrowedLocals;
use crate::dataflow::{self, Analysis};
@ -37,15 +37,15 @@ struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
}
impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self {
let cursor = FlowSensitiveAnalysis::new(q, item)
.into_engine(item.tcx, item.body, item.def_id)
pub fn new(q: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
let cursor = FlowSensitiveAnalysis::new(q, ccx)
.into_engine(ccx.tcx, ccx.body, ccx.def_id)
.iterate_to_fixpoint()
.into_results_cursor(item.body);
.into_results_cursor(ccx.body);
let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
for (local, decl) in item.body.local_decls.iter_enumerated() {
if Q::in_any_value_of_ty(item, decl.ty) {
let mut in_any_value_of_ty = BitSet::new_empty(ccx.body.local_decls.len());
for (local, decl) in ccx.body.local_decls.iter_enumerated() {
if Q::in_any_value_of_ty(ccx, decl.ty) {
in_any_value_of_ty.insert(local);
}
}
@ -91,12 +91,12 @@ impl Qualifs<'a, 'mir, 'tcx> {
|| self.indirectly_mutable(local, location)
}
fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
fn in_return_place(&mut self, ccx: &ConstCx<'_, 'tcx>) -> ConstQualifs {
// Find the `Return` terminator if one exists.
//
// If no `Return` terminator exists, this MIR is divergent. Just return the conservative
// qualifs for the return type.
let return_block = item
let return_block = ccx
.body
.basic_blocks()
.iter_enumerated()
@ -107,11 +107,11 @@ impl Qualifs<'a, 'mir, 'tcx> {
.map(|(bb, _)| bb);
let return_block = match return_block {
None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty()),
Some(bb) => bb,
};
let return_loc = item.body.terminator_loc(return_block);
let return_loc = ccx.body.terminator_loc(return_block);
ConstQualifs {
needs_drop: self.needs_drop(RETURN_PLACE, return_loc),
@ -121,7 +121,7 @@ impl Qualifs<'a, 'mir, 'tcx> {
}
pub struct Validator<'a, 'mir, 'tcx> {
item: &'a Item<'mir, 'tcx>,
ccx: &'a ConstCx<'mir, 'tcx>,
qualifs: Qualifs<'a, 'mir, 'tcx>,
/// The span of the current statement.
@ -129,19 +129,19 @@ pub struct Validator<'a, 'mir, 'tcx> {
}
impl Deref for Validator<'_, 'mir, 'tcx> {
type Target = Item<'mir, 'tcx>;
type Target = ConstCx<'mir, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.item
&self.ccx
}
}
impl Validator<'a, 'mir, 'tcx> {
pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
let Item { tcx, body, def_id, param_env, .. } = *item;
pub fn new(ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
let ConstCx { tcx, body, def_id, param_env, .. } = *ccx;
let needs_drop = QualifCursor::new(NeedsDrop, item);
let has_mut_interior = QualifCursor::new(HasMutInterior, item);
let needs_drop = QualifCursor::new(NeedsDrop, ccx);
let has_mut_interior = QualifCursor::new(HasMutInterior, ccx);
// We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not
// allowed in a const.
@ -156,11 +156,11 @@ impl Validator<'a, 'mir, 'tcx> {
let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
Validator { span: item.body.span, item, qualifs }
Validator { span: ccx.body.span, ccx, qualifs }
}
pub fn check_body(&mut self) {
let Item { tcx, body, def_id, const_kind, .. } = *self.item;
let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx;
let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
&& crate::const_eval::is_min_const_fn(tcx, def_id))
@ -175,7 +175,7 @@ impl Validator<'a, 'mir, 'tcx> {
}
}
check_short_circuiting_in_const_local(self.item);
check_short_circuiting_in_const_local(self.ccx);
if body.is_cfg_cyclic() {
// We can't provide a good span for the error here, but this should be caught by the
@ -196,7 +196,7 @@ impl Validator<'a, 'mir, 'tcx> {
}
pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
self.qualifs.in_return_place(self.item)
self.qualifs.in_return_place(self.ccx)
}
/// Emits an error at the given `span` if an expression cannot be evaluated in the current
@ -344,7 +344,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Shallow, ref place)
| Rvalue::AddressOf(Mutability::Not, ref place) => {
let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
&self.item,
&self.ccx,
&mut |local| self.qualifs.has_mut_interior(local, location),
place.as_ref(),
);
@ -608,8 +608,8 @@ fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>)
.emit();
}
fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
let body = item.body;
fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) {
let body = ccx.body;
if body.control_flow_destroyed.is_empty() {
return;
@ -618,12 +618,12 @@ fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
let mut locals = body.vars_iter();
if let Some(local) = locals.next() {
let span = body.local_decls[local].source_info.span;
let mut error = item.tcx.sess.struct_span_err(
let mut error = ccx.tcx.sess.struct_span_err(
span,
&format!(
"new features like let bindings are not permitted in {}s \
which also use short circuiting operators",
item.const_kind(),
ccx.const_kind(),
),
);
for (span, kind) in body.control_flow_destroyed.iter() {

View File

@ -194,10 +194,10 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
return Default::default();
}
let item =
check_consts::Item { body, tcx, def_id, const_kind, param_env: tcx.param_env(def_id) };
let ccx =
check_consts::ConstCx { body, tcx, def_id, const_kind, param_env: tcx.param_env(def_id) };
let mut validator = check_consts::validation::Validator::new(&item);
let mut validator = check_consts::validation::Validator::new(&ccx);
validator.check_body();
// We return the qualifs in the return place for every MIR body, even though it is only used

View File

@ -30,7 +30,7 @@ use std::cell::Cell;
use std::{cmp, iter, mem};
use crate::const_eval::{is_const_fn, is_unstable_const_fn};
use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx, ConstKind};
use crate::transform::{MirPass, MirSource};
/// A `MirPass` for promotion.
@ -62,9 +62,10 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
let def_id = src.def_id();
let mut rpo = traversal::reverse_postorder(body);
let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
let ccx = ConstCx::new(tcx, def_id, body);
let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates);
let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
self.promoted_fragments.set(promoted);
@ -139,8 +140,7 @@ fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
}
struct Collector<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
body: &'a Body<'tcx>,
ccx: &'a ConstCx<'a, 'tcx>,
temps: IndexVec<Local, TempState>,
candidates: Vec<Candidate>,
span: Span,
@ -150,7 +150,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
// We're only interested in temporaries and the return place
match self.body.local_kind(index) {
match self.ccx.body.local_kind(index) {
LocalKind::Temp | LocalKind::ReturnPointer => {}
LocalKind::Arg | LocalKind::Var => return,
}
@ -203,7 +203,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
Rvalue::Ref(..) => {
self.candidates.push(Candidate::Ref(location));
}
Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => {
// FIXME(#49147) only promote the element when it isn't `Copy`
// (so that code that can copy it at runtime is unaffected).
self.candidates.push(Candidate::Repeat(location));
@ -216,10 +216,10 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
self.super_terminator_kind(kind, location);
if let TerminatorKind::Call { ref func, .. } = *kind {
if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
let fn_sig = self.tcx.fn_sig(def_id);
if let ty::FnDef(def_id, _) = func.ty(self.ccx.body, self.ccx.tcx).kind {
let fn_sig = self.ccx.tcx.fn_sig(def_id);
if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
let name = self.tcx.item_name(def_id);
let name = self.ccx.tcx.item_name(def_id);
// FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
if name.as_str().starts_with("simd_shuffle") {
self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
@ -228,7 +228,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
}
}
if let Some(constant_args) = args_required_const(self.tcx, def_id) {
if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) {
for index in constant_args {
self.candidates.push(Candidate::Argument { bb: location.block, index });
}
@ -243,16 +243,14 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
}
pub fn collect_temps_and_candidates(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
ccx: &ConstCx<'mir, 'tcx>,
rpo: &mut ReversePostorder<'_, 'tcx>,
) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
let mut collector = Collector {
tcx,
body,
temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
candidates: vec![],
span: body.span,
span: ccx.body.span,
ccx,
};
for (bb, data) in rpo {
collector.visit_basic_block_data(bb, data);
@ -264,7 +262,7 @@ pub fn collect_temps_and_candidates(
///
/// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
struct Validator<'a, 'tcx> {
item: Item<'a, 'tcx>,
ccx: &'a ConstCx<'a, 'tcx>,
temps: &'a IndexVec<Local, TempState>,
/// Explicit promotion happens e.g. for constant arguments declared via
@ -277,10 +275,10 @@ struct Validator<'a, 'tcx> {
}
impl std::ops::Deref for Validator<'a, 'tcx> {
type Target = Item<'a, 'tcx>;
type Target = ConstCx<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.item
&self.ccx
}
}
@ -413,7 +411,7 @@ impl<'tcx> Validator<'_, 'tcx> {
let statement = &self.body[loc.block].statements[loc.statement_index];
match &statement.kind {
StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
&self.item,
&self.ccx,
&mut |l| self.qualif_local::<Q>(l),
rhs,
),
@ -430,7 +428,7 @@ impl<'tcx> Validator<'_, 'tcx> {
match &terminator.kind {
TerminatorKind::Call { .. } => {
let return_ty = self.body.local_decls[local].ty;
Q::in_any_value_of_ty(&self.item, return_ty)
Q::in_any_value_of_ty(&self.ccx, return_ty)
}
kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
@ -717,13 +715,11 @@ impl<'tcx> Validator<'_, 'tcx> {
// FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
pub fn validate_candidates(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
def_id: DefId,
ccx: &ConstCx<'_, '_>,
temps: &IndexVec<Local, TempState>,
candidates: &[Candidate],
) -> Vec<Candidate> {
let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
let mut validator = Validator { ccx, temps, explicit: false };
candidates
.iter()
@ -735,11 +731,23 @@ pub fn validate_candidates(
// and `#[rustc_args_required_const]` arguments here.
let is_promotable = validator.validate_candidate(candidate).is_ok();
// If we use explicit validation, we carry the risk of turning a legitimate run-time
// operation into a failing compile-time operation. Make sure that does not happen
// by asserting that there is no possible run-time behavior here in case promotion
// fails.
if validator.explicit && !is_promotable {
ccx.tcx.sess.delay_span_bug(
ccx.body.span,
"Explicit promotion requested, but failed to promote",
);
}
match candidate {
Candidate::Argument { bb, index } if !is_promotable => {
let span = body[bb].terminator().source_info.span;
let span = ccx.body[bb].terminator().source_info.span;
let msg = format!("argument {} is required to be a constant", index + 1);
tcx.sess.span_err(span, &msg);
ccx.tcx.sess.span_err(span, &msg);
}
_ => (),
}
@ -1147,22 +1155,19 @@ pub fn promote_candidates<'tcx>(
/// Feature attribute should be suggested if `operand` can be promoted and the feature is not
/// enabled.
crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
tcx: TyCtxt<'tcx>,
mir_def_id: DefId,
body: &Body<'tcx>,
ccx: &ConstCx<'_, 'tcx>,
operand: &Operand<'tcx>,
) -> bool {
let mut rpo = traversal::reverse_postorder(&body);
let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
let validator =
Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
let mut rpo = traversal::reverse_postorder(&ccx.body);
let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo);
let validator = Validator { ccx, temps: &temps, explicit: false };
let should_promote = validator.validate_operand(operand).is_ok();
let feature_flag = tcx.features().const_in_array_repeat_expressions;
let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions;
debug!(
"should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
"should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \
should_promote={:?} feature_flag={:?}",
mir_def_id, should_promote, feature_flag
validator.ccx.def_id, should_promote, feature_flag
);
should_promote && !feature_flag
}

View File

@ -3338,6 +3338,10 @@ impl<'test> TestCx<'test> {
}
fn delete_file(&self, file: &PathBuf) {
if !file.exists() {
// Deleting a nonexistant file would error.
return;
}
if let Err(e) = fs::remove_file(file) {
self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
}
@ -3400,7 +3404,7 @@ impl<'test> TestCx<'test> {
let examined_content =
self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
if examined_path.exists() && canon_content == &examined_content {
if canon_content == &examined_content {
self.delete_file(&examined_path);
}
}