Skip to content

Commit 34093c9

Browse files
committed
Auto merge of rust-lang#115748 - RalfJung:post-mono, r=<try>
move required_consts check to general post-mono-check function I was hoping this would simplify the code. That didn't entirely happen, but I still think it could be useful to have a single place for the "required const" check -- and this does simplify some code in codegen, where the const-eval functions no longer have to return a `Result`. Also this is in preparation for another post-mono check that will be needed for (the current hackfix for) rust-lang#115709: ensuring that all locals are dynamically sized. I didn't expect this to change diagnostics, but the changes seem either harmless (for the cycle errors) or improvements (where more spans are shown when something goes wrong in a constant). r? `@oli-obk`
2 parents e2b3676 + ed1575c commit 34093c9

File tree

98 files changed

+676
-737
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+676
-737
lines changed

Diff for: compiler/rustc_codegen_cranelift/src/base.rs

+12-11
Original file line numberDiff line numberDiff line change
@@ -250,12 +250,16 @@ pub(crate) fn verify_func(
250250
}
251251

252252
fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
253-
if !crate::constant::check_constants(fx) {
254-
fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
255-
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
256-
// compilation should have been aborted
257-
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
258-
return;
253+
match fx.mir.post_mono_checks(fx.tcx, ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c))) {
254+
Ok(()) => {}
255+
Err(err) => {
256+
err.emit_err(fx.tcx);
257+
fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
258+
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
259+
// compilation should have been aborted
260+
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
261+
return;
262+
}
259263
}
260264

261265
let arg_uninhabited = fx
@@ -723,11 +727,8 @@ fn codegen_stmt<'tcx>(
723727
}
724728
Rvalue::Repeat(ref operand, times) => {
725729
let operand = codegen_operand(fx, operand);
726-
let times = fx
727-
.monomorphize(times)
728-
.eval(fx.tcx, ParamEnv::reveal_all())
729-
.try_to_bits(fx.tcx.data_layout.pointer_size)
730-
.unwrap();
730+
let times =
731+
fx.monomorphize(times).eval_target_usize(fx.tcx, ParamEnv::reveal_all());
731732
if operand.layout().size.bytes() == 0 {
732733
// Do nothing for ZST's
733734
} else if fx.clif_type(operand.layout().ty) == Some(types::I8) {

Diff for: compiler/rustc_codegen_cranelift/src/constant.rs

+10-52
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
44
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
55
use rustc_middle::mir::interpret::{
6-
read_target_uint, AllocId, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
6+
read_target_uint, AllocId, ConstAllocation, ConstValue, GlobalAlloc, Scalar,
77
};
88

99
use cranelift_module::*;
@@ -33,16 +33,6 @@ impl ConstantCx {
3333
}
3434
}
3535

36-
pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
37-
let mut all_constants_ok = true;
38-
for constant in &fx.mir.required_consts {
39-
if eval_mir_constant(fx, constant).is_none() {
40-
all_constants_ok = false;
41-
}
42-
}
43-
all_constants_ok
44-
}
45-
4636
pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
4737
let mut constants_cx = ConstantCx::new();
4838
constants_cx.todo.push(TodoItem::Static(def_id));
@@ -76,52 +66,20 @@ pub(crate) fn codegen_tls_ref<'tcx>(
7666
pub(crate) fn eval_mir_constant<'tcx>(
7767
fx: &FunctionCx<'_, '_, 'tcx>,
7868
constant: &Constant<'tcx>,
79-
) -> Option<(ConstValue<'tcx>, Ty<'tcx>)> {
80-
let constant_kind = fx.monomorphize(constant.literal);
81-
let uv = match constant_kind {
82-
ConstantKind::Ty(const_) => match const_.kind() {
83-
ty::ConstKind::Unevaluated(uv) => uv.expand(),
84-
ty::ConstKind::Value(val) => {
85-
return Some((fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty()));
86-
}
87-
err => span_bug!(
88-
constant.span,
89-
"encountered bad ConstKind after monomorphizing: {:?}",
90-
err
91-
),
92-
},
93-
ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
94-
if fx.tcx.is_static(def) =>
95-
{
96-
span_bug!(constant.span, "MIR constant refers to static");
97-
}
98-
ConstantKind::Unevaluated(uv, _) => uv,
99-
ConstantKind::Val(val, _) => return Some((val, constant_kind.ty())),
100-
};
101-
102-
let val = fx
103-
.tcx
104-
.const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None)
105-
.map_err(|err| match err {
106-
ErrorHandled::Reported(_) => {
107-
fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
108-
}
109-
ErrorHandled::TooGeneric => {
110-
span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
111-
}
112-
})
113-
.ok();
114-
val.map(|val| (val, constant_kind.ty()))
69+
) -> (ConstValue<'tcx>, Ty<'tcx>) {
70+
let cv = fx.monomorphize(constant.literal);
71+
// This cannot fail because we checked all required_consts in advance.
72+
let val = cv
73+
.eval(fx.tcx, ty::ParamEnv::reveal_all(), Some(constant.span))
74+
.expect("erroneous constant not captured by required_consts");
75+
(val, cv.ty())
11576
}
11677

11778
pub(crate) fn codegen_constant_operand<'tcx>(
11879
fx: &mut FunctionCx<'_, '_, 'tcx>,
11980
constant: &Constant<'tcx>,
12081
) -> CValue<'tcx> {
121-
let (const_val, ty) = eval_mir_constant(fx, constant).unwrap_or_else(|| {
122-
span_bug!(constant.span, "erroneous constant not captured by required_consts")
123-
});
124-
82+
let (const_val, ty) = eval_mir_constant(fx, constant);
12583
codegen_const_value(fx, const_val, ty)
12684
}
12785

@@ -479,7 +437,7 @@ pub(crate) fn mir_operand_get_const_val<'tcx>(
479437
operand: &Operand<'tcx>,
480438
) -> Option<ConstValue<'tcx>> {
481439
match operand {
482-
Operand::Constant(const_) => Some(eval_mir_constant(fx, const_).unwrap().0),
440+
Operand::Constant(const_) => Some(eval_mir_constant(fx, const_).0),
483441
// FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
484442
// inside a temporary before being passed to the intrinsic requiring the const argument.
485443
// This code tries to find a single constant defining definition of the referenced local.

Diff for: compiler/rustc_codegen_cranelift/src/inline_asm.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -242,8 +242,7 @@ pub(crate) fn codegen_inline_asm<'tcx>(
242242
}
243243
}
244244
InlineAsmOperand::Const { ref value } => {
245-
let (const_value, ty) = crate::constant::eval_mir_constant(fx, value)
246-
.unwrap_or_else(|| span_bug!(span, "asm const cannot be resolved"));
245+
let (const_value, ty) = crate::constant::eval_mir_constant(fx, value);
247246
let value = rustc_codegen_ssa::common::asm_const_to_str(
248247
fx.tcx,
249248
span,

Diff for: compiler/rustc_codegen_ssa/messages.ftl

-4
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$e
1919
2020
codegen_ssa_create_temp_dir = couldn't create a temp dir: {$error}
2121
22-
codegen_ssa_erroneous_constant = erroneous constant encountered
23-
2422
codegen_ssa_error_creating_remark_dir = failed to create remark directory: {$error}
2523
2624
codegen_ssa_expected_used_symbol = expected `used`, `used(compiler)` or `used(linker)`
@@ -172,8 +170,6 @@ codegen_ssa_no_natvis_directory = error enumerating natvis directory: {$error}
172170
173171
codegen_ssa_option_gcc_only = option `-Z gcc-ld` is used even though linker flavor is not gcc
174172
175-
codegen_ssa_polymorphic_constant_too_generic = codegen encountered polymorphic constant: TooGeneric
176-
177173
codegen_ssa_processing_dymutil_failed = processing debug info with `dsymutil` failed: {$status}
178174
.note = {$output}
179175

Diff for: compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -670,10 +670,8 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S
670670
// avoiding collisions and will make the emitted type names shorter.
671671
let hash_short = tcx.with_stable_hashing_context(|mut hcx| {
672672
let mut hasher = StableHasher::new();
673-
let ct = ct.eval(tcx, ty::ParamEnv::reveal_all());
674-
hcx.while_hashing_spans(false, |hcx| {
675-
ct.to_valtree().hash_stable(hcx, &mut hasher)
676-
});
673+
let ct = ct.eval(tcx, ty::ParamEnv::reveal_all(), None);
674+
hcx.while_hashing_spans(false, |hcx| ct.hash_stable(hcx, &mut hasher));
677675
hasher.finish::<Hash64>()
678676
});
679677

Diff for: compiler/rustc_codegen_ssa/src/errors.rs

-14
Original file line numberDiff line numberDiff line change
@@ -588,20 +588,6 @@ pub struct InvalidWindowsSubsystem {
588588
pub subsystem: Symbol,
589589
}
590590

591-
#[derive(Diagnostic)]
592-
#[diag(codegen_ssa_erroneous_constant)]
593-
pub struct ErroneousConstant {
594-
#[primary_span]
595-
pub span: Span,
596-
}
597-
598-
#[derive(Diagnostic)]
599-
#[diag(codegen_ssa_polymorphic_constant_too_generic)]
600-
pub struct PolymorphicConstantTooGeneric {
601-
#[primary_span]
602-
pub span: Span,
603-
}
604-
605591
#[derive(Diagnostic)]
606592
#[diag(codegen_ssa_shuffle_indices_evaluation)]
607593
pub struct ShuffleIndicesEvaluation {

Diff for: compiler/rustc_codegen_ssa/src/mir/block.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1109,9 +1109,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
11091109
InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
11101110
}
11111111
mir::InlineAsmOperand::Const { ref value } => {
1112-
let const_value = self
1113-
.eval_mir_constant(value)
1114-
.unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
1112+
let const_value = self.eval_mir_constant(value);
11151113
let string = common::asm_const_to_str(
11161114
bx.tcx(),
11171115
span,

Diff for: compiler/rustc_codegen_ssa/src/mir/constant.rs

+11-40
Original file line numberDiff line numberDiff line change
@@ -14,53 +14,24 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1414
&self,
1515
bx: &mut Bx,
1616
constant: &mir::Constant<'tcx>,
17-
) -> Result<OperandRef<'tcx, Bx::Value>, ErrorHandled> {
18-
let val = self.eval_mir_constant(constant)?;
17+
) -> OperandRef<'tcx, Bx::Value> {
18+
let val = self.eval_mir_constant(constant);
1919
let ty = self.monomorphize(constant.ty());
20-
Ok(OperandRef::from_const(bx, val, ty))
20+
OperandRef::from_const(bx, val, ty)
2121
}
2222

23-
pub fn eval_mir_constant(
24-
&self,
25-
constant: &mir::Constant<'tcx>,
26-
) -> Result<ConstValue<'tcx>, ErrorHandled> {
27-
let ct = self.monomorphize(constant.literal);
28-
let uv = match ct {
29-
mir::ConstantKind::Ty(ct) => match ct.kind() {
30-
ty::ConstKind::Unevaluated(uv) => uv.expand(),
31-
ty::ConstKind::Value(val) => {
32-
return Ok(self.cx.tcx().valtree_to_const_val((ct.ty(), val)));
33-
}
34-
err => span_bug!(
35-
constant.span,
36-
"encountered bad ConstKind after monomorphizing: {:?}",
37-
err
38-
),
39-
},
40-
mir::ConstantKind::Unevaluated(uv, _) => uv,
41-
mir::ConstantKind::Val(val, _) => return Ok(val),
42-
};
43-
44-
self.cx.tcx().const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None).map_err(|err| {
45-
match err {
46-
ErrorHandled::Reported(_) => {
47-
self.cx.tcx().sess.emit_err(errors::ErroneousConstant { span: constant.span });
48-
}
49-
ErrorHandled::TooGeneric => {
50-
self.cx
51-
.tcx()
52-
.sess
53-
.diagnostic()
54-
.emit_bug(errors::PolymorphicConstantTooGeneric { span: constant.span });
55-
}
56-
}
57-
err
58-
})
23+
pub fn eval_mir_constant(&self, constant: &mir::Constant<'tcx>) -> ConstValue<'tcx> {
24+
// This cannot fail because we checked all required_consts in advance.
25+
self.monomorphize(constant.literal)
26+
.eval(self.cx.tcx(), ty::ParamEnv::reveal_all(), Some(constant.span))
27+
.expect("erroneous constant not captured by required_consts")
5928
}
6029

6130
/// This is a convenience helper for `simd_shuffle_indices`. It has the precondition
6231
/// that the given `constant` is an `ConstantKind::Unevaluated` and must be convertible to
6332
/// a `ValTree`. If you want a more general version of this, talk to `wg-const-eval` on zulip.
33+
///
34+
/// Note that this function is cursed, since usually MIR consts should not be evaluated to valtrees!
6435
pub fn eval_unevaluated_mir_constant_to_valtree(
6536
&self,
6637
constant: &mir::Constant<'tcx>,
@@ -80,7 +51,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
8051
// `simd_shuffle` call without wrapping the constant argument in a `const {}` block, but
8152
// the user pass through arbitrary expressions.
8253
// FIXME(oli-obk): replace the magic const generic argument of `simd_shuffle` with a real
83-
// const generic.
54+
// const generic, and get rid of this entire function.
8455
other => span_bug!(constant.span, "{other:#?}"),
8556
};
8657
let uv = self.monomorphize(uv);

Diff for: compiler/rustc_codegen_ssa/src/mir/debuginfo.rs

+6-17
Original file line numberDiff line numberDiff line change
@@ -579,23 +579,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
579579
if let Some(dbg_var) = dbg_var {
580580
let Some(dbg_loc) = self.dbg_loc(var.source_info) else { continue };
581581

582-
if let Ok(operand) = self.eval_mir_constant_to_operand(bx, &c) {
583-
self.set_debug_loc(bx, var.source_info);
584-
let base = Self::spill_operand_to_stack(
585-
operand,
586-
Some(var.name.to_string()),
587-
bx,
588-
);
589-
590-
bx.dbg_var_addr(
591-
dbg_var,
592-
dbg_loc,
593-
base.llval,
594-
Size::ZERO,
595-
&[],
596-
fragment,
597-
);
598-
}
582+
let operand = self.eval_mir_constant_to_operand(bx, &c);
583+
self.set_debug_loc(bx, var.source_info);
584+
let base =
585+
Self::spill_operand_to_stack(operand, Some(var.name.to_string()), bx);
586+
587+
bx.dbg_var_addr(dbg_var, dbg_loc, base.llval, Size::ZERO, &[], fragment);
599588
}
600589
}
601590
}

Diff for: compiler/rustc_codegen_ssa/src/mir/mod.rs

+9-18
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use crate::traits::*;
33
use rustc_index::bit_set::BitSet;
44
use rustc_index::IndexVec;
55
use rustc_middle::mir;
6-
use rustc_middle::mir::interpret::ErrorHandled;
76
use rustc_middle::mir::traversal;
87
use rustc_middle::mir::UnwindTerminateReason;
98
use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
@@ -212,25 +211,17 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
212211

213212
fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut start_bx);
214213

215-
// Evaluate all required consts; codegen later assumes that CTFE will never fail.
216-
let mut all_consts_ok = true;
217-
for const_ in &mir.required_consts {
218-
if let Err(err) = fx.eval_mir_constant(const_) {
219-
all_consts_ok = false;
220-
match err {
221-
// errored or at least linted
222-
ErrorHandled::Reported(_) => {}
223-
ErrorHandled::TooGeneric => {
224-
span_bug!(const_.span, "codegen encountered polymorphic constant: {:?}", err)
225-
}
226-
}
214+
// Rust post-monomorphization checks; we later rely on them.
215+
match mir.post_mono_checks(cx.tcx(), ty::ParamEnv::reveal_all(), |c| Ok(fx.monomorphize(c))) {
216+
Ok(()) => {}
217+
Err(err) => {
218+
err.emit_err(cx.tcx());
219+
// This IR shouldn't ever be emitted, but let's try to guard against any of this code
220+
// ever running.
221+
start_bx.abort();
222+
return;
227223
}
228224
}
229-
if !all_consts_ok {
230-
// We leave the IR in some half-built state here, and rely on this code not even being
231-
// submitted to LLVM once an error was raised.
232-
return;
233-
}
234225

235226
let memory_locals = analyze::non_ssa_locals(&fx);
236227

Diff for: compiler/rustc_codegen_ssa/src/mir/operand.rs

+1-6
Original file line numberDiff line numberDiff line change
@@ -569,12 +569,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
569569
self.codegen_consume(bx, place.as_ref())
570570
}
571571

572-
mir::Operand::Constant(ref constant) => {
573-
// This cannot fail because we checked all required_consts in advance.
574-
self.eval_mir_constant_to_operand(bx, constant).unwrap_or_else(|_err| {
575-
span_bug!(constant.span, "erroneous constant not captured by required_consts")
576-
})
577-
}
572+
mir::Operand::Constant(ref constant) => self.eval_mir_constant_to_operand(bx, constant),
578573
}
579574
}
580575
}

Diff for: compiler/rustc_const_eval/messages.ftl

-3
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,6 @@ const_eval_dyn_call_vtable_mismatch =
8383
const_eval_dyn_star_call_vtable_mismatch =
8484
`dyn*` call on a pointer whose vtable does not match its type
8585
86-
const_eval_erroneous_constant =
87-
erroneous constant used
88-
8986
const_eval_error = {$error_kind ->
9087
[static] could not evaluate static initializer
9188
[const] evaluation of constant value failed

0 commit comments

Comments
 (0)