Skip to content

Commit 185afe0

Browse files
committed
Auto merge of rust-lang#121557 - RalfJung:const-fn-call-promotion, r=<try>
restrict promotion of `const fn` calls We only promote them in `const`/`static` initializers, but even that is still unfortunate -- we still cannot add promoteds to required_consts. But we should add them there to make sure it's always okay to evaluate every const we encounter in a MIR body. That effort of not promoting things that can fail to evaluate is tracked in rust-lang#80619. These `const fn` calls are the last missing piece. So I propose that we do not promote const-fn calls in const when that may fail without the entire const failing, thereby completing rust-lang#80619. Unfortunately we can't just reject promoting these functions outright due to backwards compatibility. So let's see if we can find a hack that makes crater happy... For the record, this is the [crater analysis](rust-lang#80243 (comment)) from when I tried to entirely forbid this kind of promotion. It's a tiny amount of breakage and if we had a nice alternative for code like that, we could conceivably push it through... but sadly, inline const expressions are still blocked on t-lang concerns about post-monomorphization errors and we haven't yet figured out an implementation that can resolve those concerns. So we're forced to make progress via other means, such as terrible hacks like this. Attempt one: only promote calls on the "safe path" at the beginning of a MIR block. This is the path that starts at the start block and continues via gotos and calls, but stops at the first branch. If we had imposed this restriction before stabilizing `if` and `match` in `const`, this would have definitely been sufficient... EDIT: Turns out that works. :) Here's the t-lang [nomination comment](rust-lang#121557 (comment)). r? `@oli-obk`
2 parents 7de1a1f + f205b14 commit 185afe0

11 files changed

+215
-249
lines changed

Diff for: compiler/rustc_mir_transform/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,8 @@ fn mir_promoted(
343343
body.tainted_by_errors = Some(error_reported);
344344
}
345345

346+
// Collect `required_consts` *before* promotion, so if there are any consts being promoted
347+
// we still add them to the list in the outer MIR body.
346348
let mut required_consts = Vec::new();
347349
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
348350
for (bb, bb_data) in traversal::reverse_postorder(&body) {

Diff for: compiler/rustc_mir_transform/src/promote_consts.rs

+107-28
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
//! move analysis runs after promotion on broken MIR.
1414
1515
use either::{Left, Right};
16+
use rustc_data_structures::fx::FxHashSet;
1617
use rustc_hir as hir;
1718
use rustc_middle::mir;
1819
use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
@@ -60,7 +61,7 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
6061

6162
let promotable_candidates = validate_candidates(&ccx, &mut temps, &all_candidates);
6263

63-
let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
64+
let promoted = promote_candidates(body, tcx, ccx.const_kind, temps, promotable_candidates);
6465
self.promoted_fragments.set(promoted);
6566
}
6667
}
@@ -175,6 +176,12 @@ fn collect_temps_and_candidates<'tcx>(
175176
struct Validator<'a, 'tcx> {
176177
ccx: &'a ConstCx<'a, 'tcx>,
177178
temps: &'a mut IndexSlice<Local, TempState>,
179+
/// For backwards compatibility, we are promoting function calls in `const`/`static`
180+
/// initializers. But we want to avoid evaluating code that might panic and that otherwise would
181+
/// not have been evaluated, so we only promote such calls in basic blocks that are guaranteed
182+
/// to execute. In other words, we only promote such calls in basic blocks that are definitely
183+
/// not dead code. Here we cache the result of computing that set of basic blocks.
184+
promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
178185
}
179186

180187
impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
@@ -260,7 +267,9 @@ impl<'tcx> Validator<'_, 'tcx> {
260267
self.validate_rvalue(rhs)
261268
}
262269
Right(terminator) => match &terminator.kind {
263-
TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
270+
TerminatorKind::Call { func, args, .. } => {
271+
self.validate_call(func, args, loc.block)
272+
}
264273
TerminatorKind::Yield { .. } => Err(Unpromotable),
265274
kind => {
266275
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
@@ -587,53 +596,110 @@ impl<'tcx> Validator<'_, 'tcx> {
587596
Ok(())
588597
}
589598

599+
/// Computes the sets of blocks of this MIR that are definitely going to be executed
600+
/// if the function returns successfully. That makes it safe to promote calls in them
601+
/// that might fail.
602+
fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
603+
let mut safe_blocks = FxHashSet::default();
604+
let mut safe_block = START_BLOCK;
605+
loop {
606+
safe_blocks.insert(safe_block);
607+
// Let's see if we can find another safe block.
608+
safe_block = match body.basic_blocks[safe_block].terminator().kind {
609+
TerminatorKind::Goto { target } => target,
610+
TerminatorKind::Call { target: Some(target), .. }
611+
| TerminatorKind::Drop { target, .. } => {
612+
// This calls a function or the destructor. `target` does not get executed if
613+
// the callee loops or panics. But in both cases the const already fails to
614+
// evaluate, so we are fine considering `target` a safe block for promotion.
615+
target
616+
}
617+
TerminatorKind::Assert { target, .. } => {
618+
// Similar to above, we only consider successful execution.
619+
target
620+
}
621+
_ => {
622+
// No next safe block.
623+
break;
624+
}
625+
};
626+
}
627+
safe_blocks
628+
}
629+
630+
/// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
631+
/// We use this to avoid promoting operations that can fail in dead code.
632+
fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
633+
let body = self.body;
634+
let safe_blocks =
635+
self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
636+
safe_blocks.contains(&block)
637+
}
638+
590639
fn validate_call(
591640
&mut self,
592641
callee: &Operand<'tcx>,
593642
args: &[Spanned<Operand<'tcx>>],
643+
block: BasicBlock,
594644
) -> Result<(), Unpromotable> {
595-
let fn_ty = callee.ty(self.body, self.tcx);
645+
// Validate the operands. If they fail, there's no question -- we cannot promote.
646+
self.validate_operand(callee)?;
647+
for arg in args {
648+
self.validate_operand(&arg.node)?;
649+
}
596650

597-
// Inside const/static items, we promote all (eligible) function calls.
598-
// Everywhere else, we require `#[rustc_promotable]` on the callee.
599-
let promote_all_const_fn = matches!(
600-
self.const_kind,
601-
Some(hir::ConstContext::Static(_) | hir::ConstContext::Const { inline: false })
602-
);
603-
if !promote_all_const_fn {
604-
if let ty::FnDef(def_id, _) = *fn_ty.kind() {
605-
// Never promote runtime `const fn` calls of
606-
// functions without `#[rustc_promotable]`.
607-
if !self.tcx.is_promotable_const_fn(def_id) {
608-
return Err(Unpromotable);
609-
}
651+
// Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
652+
// accept them at this point.
653+
let fn_ty = callee.ty(self.body, self.tcx);
654+
if let ty::FnDef(def_id, _) = *fn_ty.kind() {
655+
if self.tcx.is_promotable_const_fn(def_id) {
656+
return Ok(());
610657
}
611658
}
612659

660+
// Ideally, we'd stop here and reject the rest. But for backward compatibility, we have to
661+
// accept some promotion in const/static initializers.
662+
if !promote_all_fn(self.ccx.const_kind) {
663+
return Err(Unpromotable);
664+
}
665+
// Make sure the callee is a `const fn`.
613666
let is_const_fn = match *fn_ty.kind() {
614667
ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id),
615668
_ => false,
616669
};
617670
if !is_const_fn {
618671
return Err(Unpromotable);
619672
}
620-
621-
self.validate_operand(callee)?;
622-
for arg in args {
623-
self.validate_operand(&arg.node)?;
673+
// The problem is, this may promote calls to functions that panic.
674+
// We don't want to introduce compilation errors if there's a panic in a call in dead code.
675+
// So we ensure that this is not dead code.
676+
if !self.is_promotion_safe_block(block) {
677+
return Err(Unpromotable);
624678
}
625-
679+
// This passed all checks, so let's accept.
626680
Ok(())
627681
}
628682
}
629683

684+
/// Decides whether in this context we are okay with promoting all functions (and not just
685+
/// `#[rustc_promotable]`).
686+
/// For backwards compatibility, we do that in static/const initializers.
687+
fn promote_all_fn(const_kind: Option<hir::ConstContext>) -> bool {
688+
// Inline consts are explicitly excluded, they are more recent so we have no
689+
// backwards compatibility reason to allow more promotion inside of them.
690+
matches!(
691+
const_kind,
692+
Some(hir::ConstContext::Static(_) | hir::ConstContext::Const { inline: false })
693+
)
694+
}
695+
630696
// FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
631697
fn validate_candidates(
632698
ccx: &ConstCx<'_, '_>,
633699
temps: &mut IndexSlice<Local, TempState>,
634700
candidates: &[Candidate],
635701
) -> Vec<Candidate> {
636-
let mut validator = Validator { ccx, temps };
702+
let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
637703

638704
candidates
639705
.iter()
@@ -652,6 +718,9 @@ struct Promoter<'a, 'tcx> {
652718
/// If true, all nested temps are also kept in the
653719
/// source MIR, not moved to the promoted MIR.
654720
keep_original: bool,
721+
722+
/// If true, add the new const (the promoted) to the required_consts of the parent MIR.
723+
add_to_required: bool,
655724
}
656725

657726
impl<'a, 'tcx> Promoter<'a, 'tcx> {
@@ -798,11 +867,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
798867
let args = tcx.erase_regions(GenericArgs::identity_for_item(tcx, def));
799868
let uneval = mir::UnevaluatedConst { def, args, promoted: Some(promoted_id) };
800869

801-
Operand::Constant(Box::new(ConstOperand {
802-
span,
803-
user_ty: None,
804-
const_: Const::Unevaluated(uneval, ty),
805-
}))
870+
ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
806871
};
807872

808873
let blocks = self.source.basic_blocks.as_mut();
@@ -838,11 +903,15 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
838903
let promoted_ref = local_decls.push(promoted_ref);
839904
assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
840905

906+
let promoted_operand = promoted_operand(ref_ty, span);
907+
if self.add_to_required {
908+
self.source.required_consts.push(promoted_operand);
909+
}
841910
let promoted_ref_statement = Statement {
842911
source_info: statement.source_info,
843912
kind: StatementKind::Assign(Box::new((
844913
Place::from(promoted_ref),
845-
Rvalue::Use(promoted_operand(ref_ty, span)),
914+
Rvalue::Use(Operand::Constant(Box::new(promoted_operand))),
846915
))),
847916
};
848917
self.extra_statements.push((loc, promoted_ref_statement));
@@ -885,6 +954,7 @@ impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
885954
fn promote_candidates<'tcx>(
886955
body: &mut Body<'tcx>,
887956
tcx: TyCtxt<'tcx>,
957+
ccx_const_kind: Option<hir::ConstContext>,
888958
mut temps: IndexVec<Local, TempState>,
889959
candidates: Vec<Candidate>,
890960
) -> IndexVec<Promoted, Body<'tcx>> {
@@ -924,6 +994,11 @@ fn promote_candidates<'tcx>(
924994
None,
925995
body.tainted_by_errors,
926996
);
997+
// We keep `required_consts` of the new MIR body empty. All consts mentioned here have
998+
// already been added to the parent MIR's `required_consts` (that is computed before
999+
// promotion), and no matter where this promoted const ends up, our parent MIR must be
1000+
// somewhere in the reachable dependency chain so we can rely on its required consts being
1001+
// evaluated.
9271002
promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
9281003

9291004
let promoter = Promoter {
@@ -933,6 +1008,10 @@ fn promote_candidates<'tcx>(
9331008
temps: &mut temps,
9341009
extra_statements: &mut extra_statements,
9351010
keep_original: false,
1011+
// If we promote all functions, some of these promoteds could fail, so we better make
1012+
// sure they get all checked as `required_consts`. Otherwise, as an optimization we
1013+
// *don't* add the promoteds to the parent's `required_consts`.
1014+
add_to_required: promote_all_fn(ccx_const_kind),
9361015
};
9371016

9381017
let mut promoted = promoter.promote_candidate(candidate, promotions.len());

Diff for: tests/ui/consts/const-eval/promoted_errors.noopt.stderr

-44
This file was deleted.

Diff for: tests/ui/consts/const-eval/promoted_errors.opt.stderr

-44
This file was deleted.

Diff for: tests/ui/consts/const-eval/promoted_errors.opt_with_overflow_checks.stderr

-44
This file was deleted.

0 commit comments

Comments
 (0)