2023-05-20 08:54:16 +00:00
|
|
|
#![feature(assert_matches)]
|
2021-01-01 01:53:25 +01:00
|
|
|
#![feature(box_patterns)]
|
2024-01-20 14:56:09 +00:00
|
|
|
#![feature(const_type_name)]
|
2023-09-16 09:16:04 +00:00
|
|
|
#![feature(cow_is_borrowed)]
|
2023-09-09 16:39:21 +00:00
|
|
|
#![feature(decl_macro)]
|
2024-01-01 21:52:43 +11:00
|
|
|
#![feature(impl_trait_in_assoc_type)]
|
2024-01-20 14:56:09 +00:00
|
|
|
#![feature(inline_const)]
|
2023-05-21 17:38:34 -07:00
|
|
|
#![feature(is_sorted)]
|
2022-08-20 20:40:08 +02:00
|
|
|
#![feature(let_chains)]
|
2021-01-01 01:53:25 +01:00
|
|
|
#![feature(map_try_insert)]
|
2024-02-10 14:52:57 +11:00
|
|
|
#![cfg_attr(bootstrap, feature(min_specialization))]
|
2021-01-01 01:53:25 +01:00
|
|
|
#![feature(never_type)]
|
2022-03-01 07:43:12 -03:00
|
|
|
#![feature(option_get_or_insert_default)]
|
2023-12-15 14:12:46 +11:00
|
|
|
#![feature(round_char_boundary)]
|
2021-01-01 01:53:25 +01:00
|
|
|
#![feature(try_blocks)]
|
2022-05-29 01:19:52 -07:00
|
|
|
#![feature(yeet_expr)]
|
2022-08-23 00:07:26 +00:00
|
|
|
#![feature(if_let_guard)]
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
#[macro_use]
|
|
|
|
extern crate tracing;
|
|
|
|
#[macro_use]
|
|
|
|
extern crate rustc_middle;
|
|
|
|
|
2023-07-10 14:26:24 +00:00
|
|
|
use hir::ConstContext;
|
2021-01-01 01:53:25 +01:00
|
|
|
use required_consts::RequiredConstsVisitor;
|
2021-01-05 20:08:11 +01:00
|
|
|
use rustc_const_eval::util;
|
2022-01-06 13:27:59 -06:00
|
|
|
use rustc_data_structures::fx::FxIndexSet;
|
2021-01-01 01:53:25 +01:00
|
|
|
use rustc_data_structures::steal::Steal;
|
|
|
|
use rustc_hir as hir;
|
2023-01-29 13:46:55 +00:00
|
|
|
use rustc_hir::def::DefKind;
|
2022-05-08 15:53:19 +02:00
|
|
|
use rustc_hir::def_id::LocalDefId;
|
2021-11-03 18:03:12 -05:00
|
|
|
use rustc_hir::intravisit::{self, Visitor};
|
2023-04-19 10:57:17 +00:00
|
|
|
use rustc_index::IndexVec;
|
2021-01-01 01:53:25 +01:00
|
|
|
use rustc_middle::mir::visit::Visitor as _;
|
2022-07-09 18:04:38 -07:00
|
|
|
use rustc_middle::mir::{
|
2023-09-20 20:51:14 +02:00
|
|
|
traversal, AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs,
|
|
|
|
LocalDecl, MirPass, MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue,
|
|
|
|
SourceInfo, Statement, StatementKind, TerminatorKind, START_BLOCK,
|
2022-07-09 18:04:38 -07:00
|
|
|
};
|
2023-05-15 06:24:45 +02:00
|
|
|
use rustc_middle::query::Providers;
|
2023-02-22 02:18:40 +00:00
|
|
|
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
|
2024-01-12 08:21:42 +01:00
|
|
|
use rustc_span::{source_map::Spanned, sym, DUMMY_SP};
|
2023-04-23 15:38:37 +00:00
|
|
|
use rustc_trait_selection::traits;
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2021-11-29 22:46:32 -08:00
|
|
|
#[macro_use]
|
|
|
|
mod pass_manager;
|
|
|
|
|
2021-12-02 14:38:04 -08:00
|
|
|
use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
|
2021-11-29 22:46:32 -08:00
|
|
|
|
2021-01-01 01:53:25 +01:00
|
|
|
mod abort_unwinding_calls;
|
|
|
|
mod add_call_guards;
|
|
|
|
mod add_moves_for_packed_drops;
|
|
|
|
mod add_retag;
|
|
|
|
mod check_const_item_mutation;
|
|
|
|
mod check_packed_ref;
|
|
|
|
pub mod check_unsafety;
|
2023-03-18 16:11:48 +00:00
|
|
|
mod remove_place_mention;
|
2022-02-09 16:17:42 +01:00
|
|
|
// This pass is public to allow external drivers to perform MIR cleanup
|
2023-08-16 08:43:30 +03:00
|
|
|
mod add_subtyping_projections;
|
2022-02-09 16:17:42 +01:00
|
|
|
pub mod cleanup_post_borrowck;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod const_debuginfo;
|
2023-01-12 18:23:48 +00:00
|
|
|
mod copy_prop;
|
2023-10-19 21:46:28 +00:00
|
|
|
mod coroutine;
|
2023-01-17 21:00:07 +00:00
|
|
|
mod cost_checker;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod coverage;
|
2023-10-06 20:29:42 -04:00
|
|
|
mod cross_crate_inline;
|
2022-12-20 00:51:17 +00:00
|
|
|
mod ctfe_limit;
|
2022-08-25 16:43:46 +00:00
|
|
|
mod dataflow_const_prop;
|
2022-05-09 20:12:03 -04:00
|
|
|
mod dead_store_elimination;
|
Introduce deduced parameter attributes, and use them for deducing `readonly` on
indirect immutable freeze by-value function parameters.
Right now, `rustc` only examines function signatures and the platform ABI when
determining the LLVM attributes to apply to parameters. This results in missed
optimizations, because there are some attributes that can be determined via
analysis of the MIR making up the function body. In particular, `readonly`
could be applied to most indirectly-passed by-value function arguments
(specifically, those that are freeze and are observed not to be mutated), but
it currently is not.
This patch introduces the machinery that allows `rustc` to determine those
attributes. It consists of a query, `deduced_param_attrs`, that, when
evaluated, analyzes the MIR of the function to determine supplementary
attributes. The results of this query for each function are written into the
crate metadata so that the deduced parameter attributes can be applied to
cross-crate functions. In this patch, we simply check the parameter for
mutations to determine whether the `readonly` attribute should be applied to
parameters that are indirect immutable freeze by-value. More attributes could
conceivably be deduced in the future: `nocapture` and `noalias` come to mind.
Adding `readonly` to indirect function parameters where applicable enables some
potential optimizations in LLVM that are discussed in [issue 103103] and [PR
103070] around avoiding stack-to-stack memory copies that appear in functions
like `core::fmt::Write::write_fmt` and `core::panicking::assert_failed`. These
functions pass a large structure unchanged by value to a subfunction that also
doesn't mutate it. Since the structure in this case is passed as an indirect
parameter, it's a pointer from LLVM's perspective. As a result, the
intermediate copy of the structure that our codegen emits could be optimized
away by LLVM's MemCpyOptimizer if it knew that the pointer is `readonly
nocapture noalias` in both the caller and callee. We already pass `nocapture
noalias`, but we're missing `readonly`, as we can't determine whether a
by-value parameter is mutated by examining the signature in Rust. I didn't have
much success with having LLVM infer the `readonly` attribute, even with fat
LTO; it seems that deducing it at the MIR level is necessary.
No large benefits should be expected from this optimization *now*; LLVM needs
some changes (discussed in [PR 103070]) to more aggressively use the `noalias
nocapture readonly` combination in its alias analysis. I have some LLVM patches
for these optimizations and have had them looked over. With all the patches
applied locally, I enabled LLVM to remove all the `memcpy`s from the following
code:
```rust
fn main() {
println!("Hello {}", 3);
}
```
which is a significant codegen improvement over the status quo. I expect that
if this optimization kicks in in multiple places even for such a simple
program, then it will apply to Rust code all over the place.
[issue 103103]: https://github.com/rust-lang/rust/issues/103103
[PR 103070]: https://github.com/rust-lang/rust/pull/103070
2022-10-17 19:42:15 -07:00
|
|
|
mod deduce_param_attrs;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod deduplicate_blocks;
|
2022-04-04 18:51:32 +03:00
|
|
|
mod deref_separator;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod dest_prop;
|
|
|
|
pub mod dump_mir;
|
|
|
|
mod early_otherwise_branch;
|
2022-05-13 21:53:03 -07:00
|
|
|
mod elaborate_box_derefs;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod elaborate_drops;
|
2023-04-30 02:20:53 +01:00
|
|
|
mod errors;
|
2022-05-18 03:51:52 +01:00
|
|
|
mod ffi_unwind_calls;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod function_item_references;
|
2023-03-20 18:05:07 +00:00
|
|
|
mod gvn;
|
2023-08-08 16:25:15 +02:00
|
|
|
pub mod inline;
|
2023-05-06 23:20:58 -04:00
|
|
|
mod instsimplify;
|
2023-01-16 22:12:36 +00:00
|
|
|
mod jump_threading;
|
2024-02-20 07:41:48 +05:30
|
|
|
mod known_panics_lint;
|
2021-06-16 05:46:56 +00:00
|
|
|
mod large_enums;
|
2023-12-12 00:00:00 +00:00
|
|
|
mod lint;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod lower_intrinsics;
|
|
|
|
mod lower_slice_len;
|
|
|
|
mod match_branches;
|
|
|
|
mod multiple_return_terminators;
|
2021-10-06 17:31:35 +02:00
|
|
|
mod normalize_array_len;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod nrvo;
|
2023-05-21 17:38:34 -07:00
|
|
|
mod prettify;
|
2023-05-20 08:21:56 +00:00
|
|
|
mod promote_consts;
|
2022-12-04 18:26:09 +00:00
|
|
|
mod ref_prop;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod remove_noop_landing_pads;
|
|
|
|
mod remove_storage_markers;
|
2021-11-30 15:04:49 -08:00
|
|
|
mod remove_uninit_drops;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod remove_unneeded_drops;
|
|
|
|
mod remove_zsts;
|
|
|
|
mod required_consts;
|
2021-05-13 12:04:41 +02:00
|
|
|
mod reveal_all;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod shim;
|
2023-01-19 22:23:41 +00:00
|
|
|
mod ssa;
|
2022-02-09 16:17:42 +01:00
|
|
|
// This pass is public to allow external drivers to perform MIR cleanup
|
2022-11-10 11:37:28 -05:00
|
|
|
mod check_alignment;
|
2022-02-09 16:17:42 +01:00
|
|
|
pub mod simplify;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod simplify_branches;
|
|
|
|
mod simplify_comparison_integral;
|
2022-05-23 09:27:44 +02:00
|
|
|
mod sroa;
|
2021-01-01 01:53:25 +01:00
|
|
|
mod uninhabited_enum_branching;
|
|
|
|
mod unreachable_prop;
|
|
|
|
|
2021-11-30 17:05:40 -08:00
|
|
|
use rustc_const_eval::transform::check_consts::{self, ConstCx};
|
2021-01-05 20:08:11 +01:00
|
|
|
use rustc_const_eval::transform::validate;
|
2021-01-05 19:53:07 +01:00
|
|
|
use rustc_mir_dataflow::rustc_peek;
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2023-11-22 09:53:07 +11:00
|
|
|
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
|
2023-04-30 02:20:53 +01:00
|
|
|
|
2021-01-01 01:53:25 +01:00
|
|
|
pub fn provide(providers: &mut Providers) {
|
|
|
|
check_unsafety::provide(providers);
|
|
|
|
coverage::query::provide(providers);
|
2022-05-18 03:51:52 +01:00
|
|
|
ffi_unwind_calls::provide(providers);
|
2021-01-01 01:53:25 +01:00
|
|
|
shim::provide(providers);
|
2023-10-06 20:29:42 -04:00
|
|
|
cross_crate_inline::provide(providers);
|
2021-01-01 01:53:25 +01:00
|
|
|
*providers = Providers {
|
|
|
|
mir_keys,
|
|
|
|
mir_const,
|
2022-05-08 15:53:19 +02:00
|
|
|
mir_const_qualif,
|
2021-01-01 01:53:25 +01:00
|
|
|
mir_promoted,
|
|
|
|
mir_drops_elaborated_and_const_checked,
|
|
|
|
mir_for_ctfe,
|
2023-10-19 21:46:28 +00:00
|
|
|
mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
|
2021-01-01 01:53:25 +01:00
|
|
|
optimized_mir,
|
|
|
|
is_mir_available,
|
|
|
|
is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
|
|
|
|
mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
|
|
|
|
mir_inliner_callees: inline::cycle::mir_inliner_callees,
|
2022-05-08 15:53:19 +02:00
|
|
|
promoted_mir,
|
Introduce deduced parameter attributes, and use them for deducing `readonly` on
indirect immutable freeze by-value function parameters.
Right now, `rustc` only examines function signatures and the platform ABI when
determining the LLVM attributes to apply to parameters. This results in missed
optimizations, because there are some attributes that can be determined via
analysis of the MIR making up the function body. In particular, `readonly`
could be applied to most indirectly-passed by-value function arguments
(specifically, those that are freeze and are observed not to be mutated), but
it currently is not.
This patch introduces the machinery that allows `rustc` to determine those
attributes. It consists of a query, `deduced_param_attrs`, that, when
evaluated, analyzes the MIR of the function to determine supplementary
attributes. The results of this query for each function are written into the
crate metadata so that the deduced parameter attributes can be applied to
cross-crate functions. In this patch, we simply check the parameter for
mutations to determine whether the `readonly` attribute should be applied to
parameters that are indirect immutable freeze by-value. More attributes could
conceivably be deduced in the future: `nocapture` and `noalias` come to mind.
Adding `readonly` to indirect function parameters where applicable enables some
potential optimizations in LLVM that are discussed in [issue 103103] and [PR
103070] around avoiding stack-to-stack memory copies that appear in functions
like `core::fmt::Write::write_fmt` and `core::panicking::assert_failed`. These
functions pass a large structure unchanged by value to a subfunction that also
doesn't mutate it. Since the structure in this case is passed as an indirect
parameter, it's a pointer from LLVM's perspective. As a result, the
intermediate copy of the structure that our codegen emits could be optimized
away by LLVM's MemCpyOptimizer if it knew that the pointer is `readonly
nocapture noalias` in both the caller and callee. We already pass `nocapture
noalias`, but we're missing `readonly`, as we can't determine whether a
by-value parameter is mutated by examining the signature in Rust. I didn't have
much success with having LLVM infer the `readonly` attribute, even with fat
LTO; it seems that deducing it at the MIR level is necessary.
No large benefits should be expected from this optimization *now*; LLVM needs
some changes (discussed in [PR 103070]) to more aggressively use the `noalias
nocapture readonly` combination in its alias analysis. I have some LLVM patches
for these optimizations and have had them looked over. With all the patches
applied locally, I enabled LLVM to remove all the `memcpy`s from the following
code:
```rust
fn main() {
println!("Hello {}", 3);
}
```
which is a significant codegen improvement over the status quo. I expect that
if this optimization kicks in in multiple places even for such a simple
program, then it will apply to Rust code all over the place.
[issue 103103]: https://github.com/rust-lang/rust/issues/103103
[PR 103070]: https://github.com/rust-lang/rust/pull/103070
2022-10-17 19:42:15 -07:00
|
|
|
deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
|
2021-01-01 01:53:25 +01:00
|
|
|
..*providers
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-08-23 00:07:26 +00:00
|
|
|
fn remap_mir_for_const_eval_select<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
mut body: Body<'tcx>,
|
|
|
|
context: hir::Constness,
|
|
|
|
) -> Body<'tcx> {
|
|
|
|
for bb in body.basic_blocks.as_mut().iter_mut() {
|
|
|
|
let terminator = bb.terminator.as_mut().expect("invalid terminator");
|
|
|
|
match terminator.kind {
|
|
|
|
TerminatorKind::Call {
|
2023-09-20 20:51:14 +02:00
|
|
|
func: Operand::Constant(box ConstOperand { ref const_, .. }),
|
2022-08-23 00:07:26 +00:00
|
|
|
ref mut args,
|
|
|
|
destination,
|
|
|
|
target,
|
2022-10-08 23:47:59 +01:00
|
|
|
unwind,
|
2022-08-23 00:07:26 +00:00
|
|
|
fn_span,
|
|
|
|
..
|
2023-09-20 20:51:14 +02:00
|
|
|
} if let ty::FnDef(def_id, _) = *const_.ty().kind()
|
2024-01-30 14:20:22 +00:00
|
|
|
&& matches!(tcx.intrinsic(def_id), Some(sym::const_eval_select)) =>
|
2022-08-23 00:07:26 +00:00
|
|
|
{
|
|
|
|
let [tupled_args, called_in_const, called_at_rt]: [_; 3] =
|
|
|
|
std::mem::take(args).try_into().unwrap();
|
2024-01-12 08:21:42 +01:00
|
|
|
let ty = tupled_args.node.ty(&body.local_decls, tcx);
|
2022-08-23 00:07:26 +00:00
|
|
|
let fields = ty.tuple_fields();
|
|
|
|
let num_args = fields.len();
|
|
|
|
let func =
|
|
|
|
if context == hir::Constness::Const { called_in_const } else { called_at_rt };
|
|
|
|
let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
|
2024-01-12 08:21:42 +01:00
|
|
|
match tupled_args.node {
|
2022-08-23 00:07:26 +00:00
|
|
|
Operand::Constant(_) => {
|
|
|
|
// there is no good way of extracting a tuple arg from a constant (const generic stuff)
|
|
|
|
// so we just create a temporary and deconstruct that.
|
|
|
|
let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
|
|
|
|
bb.statements.push(Statement {
|
|
|
|
source_info: SourceInfo::outermost(fn_span),
|
|
|
|
kind: StatementKind::Assign(Box::new((
|
|
|
|
local.into(),
|
2024-01-12 08:21:42 +01:00
|
|
|
Rvalue::Use(tupled_args.node.clone()),
|
2022-08-23 00:07:26 +00:00
|
|
|
))),
|
|
|
|
});
|
|
|
|
(Operand::Move, local.into())
|
|
|
|
}
|
|
|
|
Operand::Move(place) => (Operand::Move, place),
|
|
|
|
Operand::Copy(place) => (Operand::Copy, place),
|
|
|
|
};
|
|
|
|
let place_elems = place.projection;
|
2023-06-18 05:24:38 +00:00
|
|
|
let arguments = (0..num_args)
|
2022-08-23 00:07:26 +00:00
|
|
|
.map(|x| {
|
|
|
|
let mut place_elems = place_elems.to_vec();
|
2023-06-18 05:24:38 +00:00
|
|
|
place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
|
|
|
|
let projection = tcx.mk_place_elems(&place_elems);
|
|
|
|
let place = Place { local: place.local, projection };
|
2024-01-12 08:21:42 +01:00
|
|
|
Spanned { node: method(place), span: DUMMY_SP }
|
2023-10-13 08:58:33 +00:00
|
|
|
})
|
2023-06-18 05:24:38 +00:00
|
|
|
.collect();
|
|
|
|
terminator.kind = TerminatorKind::Call {
|
2024-01-12 08:21:42 +01:00
|
|
|
func: func.node,
|
2023-06-18 05:24:38 +00:00
|
|
|
args: arguments,
|
|
|
|
destination,
|
|
|
|
target,
|
|
|
|
unwind,
|
|
|
|
call_source: CallSource::Misc,
|
|
|
|
fn_span,
|
2023-10-13 08:58:33 +00:00
|
|
|
};
|
2022-08-23 00:07:26 +00:00
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
body
|
|
|
|
}
|
|
|
|
|
2023-03-13 18:54:05 +00:00
|
|
|
fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
|
2021-01-01 01:53:25 +01:00
|
|
|
tcx.mir_keys(()).contains(&def_id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finds the full set of `DefId`s within the current crate that have
|
|
|
|
/// MIR associated with them.
|
2022-01-06 13:27:59 -06:00
|
|
|
fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
|
|
|
|
let mut set = FxIndexSet::default();
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
// All body-owners have MIR associated with them.
|
2021-09-12 11:33:16 +02:00
|
|
|
set.extend(tcx.hir().body_owners());
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
// Additionally, tuple struct/variant constructors have MIR, but
|
|
|
|
// they don't have a BodyId, so we need to build them separately.
|
2022-11-06 19:46:55 +00:00
|
|
|
struct GatherCtors<'a> {
|
2022-01-06 13:27:59 -06:00
|
|
|
set: &'a mut FxIndexSet<LocalDefId>,
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
2022-11-06 19:46:55 +00:00
|
|
|
impl<'tcx> Visitor<'tcx> for GatherCtors<'_> {
|
2022-08-10 11:22:01 +10:00
|
|
|
fn visit_variant_data(&mut self, v: &'tcx hir::VariantData<'tcx>) {
|
2022-11-06 19:46:55 +00:00
|
|
|
if let hir::VariantData::Tuple(_, _, def_id) = *v {
|
|
|
|
self.set.insert(def_id);
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
intravisit::walk_struct_def(self, v)
|
|
|
|
}
|
|
|
|
}
|
2022-11-06 19:46:55 +00:00
|
|
|
tcx.hir().visit_all_item_likes_in_crate(&mut GatherCtors { set: &mut set });
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
set
|
|
|
|
}
|
|
|
|
|
2022-05-08 15:53:19 +02:00
|
|
|
fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
|
|
|
|
let const_kind = tcx.hir().body_const_context(def);
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
// No need to const-check a non-const `fn`.
|
2023-07-10 14:26:24 +00:00
|
|
|
match const_kind {
|
|
|
|
Some(ConstContext::Const { .. } | ConstContext::Static(_))
|
|
|
|
| Some(ConstContext::ConstFn) => {}
|
|
|
|
None => span_bug!(
|
|
|
|
tcx.def_span(def),
|
|
|
|
"`mir_const_qualif` should only be called on const fns and const items"
|
|
|
|
),
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// N.B., this `borrow()` is guaranteed to be valid (i.e., the value
|
|
|
|
// cannot yet be stolen), because `mir_promoted()`, which steals
|
2023-03-03 04:15:15 +01:00
|
|
|
// from `mir_const()`, forces this query to execute before
|
2021-01-01 01:53:25 +01:00
|
|
|
// performing the steal.
|
|
|
|
let body = &tcx.mir_const(def).borrow();
|
|
|
|
|
|
|
|
if body.return_ty().references_error() {
|
2024-02-15 08:31:46 +11:00
|
|
|
// It's possible to reach here without an error being emitted (#121103).
|
|
|
|
tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
|
2021-01-01 01:53:25 +01:00
|
|
|
return Default::default();
|
|
|
|
}
|
|
|
|
|
2022-05-08 15:53:19 +02:00
|
|
|
let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def) };
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
let mut validator = check_consts::check::Checker::new(&ccx);
|
|
|
|
validator.check_body();
|
|
|
|
|
|
|
|
// We return the qualifs in the return place for every MIR body, even though it is only used
|
|
|
|
// when deciding to promote a reference to a `const` for now.
|
|
|
|
validator.qualifs_in_return_place()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
|
2022-07-09 18:04:38 -07:00
|
|
|
/// FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
|
|
|
|
/// We used to have this for pre-miri MIR based const eval.
|
2022-05-08 15:53:19 +02:00
|
|
|
fn mir_const(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
|
2023-12-07 11:56:48 +00:00
|
|
|
// MIR unsafety check uses the raw mir, so make sure it is run.
|
2022-07-06 07:44:47 -05:00
|
|
|
if !tcx.sess.opts.unstable_opts.thir_unsafeck {
|
2023-12-07 11:56:48 +00:00
|
|
|
tcx.ensure_with_value().mir_unsafety_check_result(def);
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
2022-05-18 03:51:52 +01:00
|
|
|
// has_ffi_unwind_calls query uses the raw mir, so make sure it is run.
|
2022-05-08 15:53:19 +02:00
|
|
|
tcx.ensure_with_value().has_ffi_unwind_calls(def);
|
2022-05-18 03:51:52 +01:00
|
|
|
|
2021-01-01 01:53:25 +01:00
|
|
|
let mut body = tcx.mir_built(def).steal();
|
|
|
|
|
2022-09-04 20:00:31 -07:00
|
|
|
pass_manager::dump_mir_for_phase_change(tcx, &body);
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2021-12-02 14:20:03 -08:00
|
|
|
pm::run_passes(
|
2021-01-01 01:53:25 +01:00
|
|
|
tcx,
|
|
|
|
&mut body,
|
2021-12-02 14:20:03 -08:00
|
|
|
&[
|
2021-01-01 01:53:25 +01:00
|
|
|
// MIR-level lints.
|
2021-12-02 09:17:32 -08:00
|
|
|
&Lint(check_packed_ref::CheckPackedRef),
|
|
|
|
&Lint(check_const_item_mutation::CheckConstItemMutation),
|
|
|
|
&Lint(function_item_references::FunctionItemReferences),
|
2024-01-24 23:38:33 +00:00
|
|
|
// If this is an async closure's output coroutine, generate
|
|
|
|
// by-move and by-mut bodies if needed. We do this first so
|
|
|
|
// they can be optimized in lockstep with their parent bodies.
|
|
|
|
&coroutine::ByMoveBody,
|
2021-01-01 01:53:25 +01:00
|
|
|
// What we need to do constant evaluation.
|
2023-04-17 20:17:01 -06:00
|
|
|
&simplify::SimplifyCfg::Initial,
|
2021-12-02 09:17:32 -08:00
|
|
|
&rustc_peek::SanityCheck, // Just a lint
|
2021-12-02 14:20:03 -08:00
|
|
|
],
|
2022-09-26 18:43:35 -07:00
|
|
|
None,
|
2021-01-01 01:53:25 +01:00
|
|
|
);
|
|
|
|
tcx.alloc_steal_mir(body)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Compute the main MIR body and the list of MIR bodies of the promoteds.
|
2022-12-20 22:10:40 +01:00
|
|
|
fn mir_promoted(
|
|
|
|
tcx: TyCtxt<'_>,
|
2022-05-08 15:53:19 +02:00
|
|
|
def: LocalDefId,
|
2022-12-20 22:10:40 +01:00
|
|
|
) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
|
2021-01-01 01:53:25 +01:00
|
|
|
// Ensure that we compute the `mir_const_qualif` for constants at
|
|
|
|
// this point, before we steal the mir-const result.
|
|
|
|
// Also this means promotion can rely on all const checks having been done.
|
2023-07-10 14:26:24 +00:00
|
|
|
|
|
|
|
let const_qualifs = match tcx.def_kind(def) {
|
|
|
|
DefKind::Fn | DefKind::AssocFn | DefKind::Closure
|
|
|
|
if tcx.constness(def) == hir::Constness::Const
|
|
|
|
|| tcx.is_const_default_method(def.to_def_id()) =>
|
|
|
|
{
|
|
|
|
tcx.mir_const_qualif(def)
|
|
|
|
}
|
|
|
|
DefKind::AssocConst
|
|
|
|
| DefKind::Const
|
|
|
|
| DefKind::Static(_)
|
|
|
|
| DefKind::InlineConst
|
|
|
|
| DefKind::AnonConst => tcx.mir_const_qualif(def),
|
|
|
|
_ => ConstQualifs::default(),
|
|
|
|
};
|
2021-01-01 01:53:25 +01:00
|
|
|
let mut body = tcx.mir_const(def).steal();
|
2022-02-07 22:00:15 -08:00
|
|
|
if let Some(error_reported) = const_qualifs.tainted_by_errors {
|
|
|
|
body.tainted_by_errors = Some(error_reported);
|
|
|
|
}
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
let mut required_consts = Vec::new();
|
|
|
|
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
|
|
|
|
for (bb, bb_data) in traversal::reverse_postorder(&body) {
|
|
|
|
required_consts_visitor.visit_basic_block_data(bb, bb_data);
|
|
|
|
}
|
|
|
|
body.required_consts = required_consts;
|
|
|
|
|
2021-12-02 14:20:03 -08:00
|
|
|
// What we need to run borrowck etc.
|
2021-01-01 01:53:25 +01:00
|
|
|
let promote_pass = promote_consts::PromoteTemps::default();
|
2021-12-02 14:20:03 -08:00
|
|
|
pm::run_passes(
|
|
|
|
tcx,
|
|
|
|
&mut body,
|
2023-04-17 20:17:01 -06:00
|
|
|
&[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
|
2022-09-26 18:43:35 -07:00
|
|
|
Some(MirPhase::Analysis(AnalysisPhase::Initial)),
|
2021-12-02 14:20:03 -08:00
|
|
|
);
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
let promoted = promote_pass.promoted_fragments.into_inner();
|
|
|
|
(tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
|
2023-03-13 18:54:05 +00:00
|
|
|
fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
|
2022-05-08 15:53:19 +02:00
|
|
|
tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
2022-05-08 15:53:19 +02:00
|
|
|
fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
|
2021-01-01 01:53:25 +01:00
|
|
|
// FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
|
2022-05-08 15:53:19 +02:00
|
|
|
if tcx.is_constructor(def.to_def_id()) {
|
2021-01-01 01:53:25 +01:00
|
|
|
// There's no reason to run all of the MIR passes on constructors when
|
|
|
|
// we can just output the MIR we want directly. This also saves const
|
|
|
|
// qualification and borrow checking the trouble of special casing
|
|
|
|
// constructors.
|
2022-05-08 15:53:19 +02:00
|
|
|
return shim::build_adt_ctor(tcx, def.to_def_id());
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
2023-08-05 07:55:57 +00:00
|
|
|
let body = tcx.mir_drops_elaborated_and_const_checked(def);
|
|
|
|
let body = match tcx.hir().body_const_context(def) {
|
|
|
|
// consts and statics do not have `optimized_mir`, so we can steal the body instead of
|
|
|
|
// cloning it.
|
2023-09-18 15:30:07 +00:00
|
|
|
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
|
2023-08-05 07:55:57 +00:00
|
|
|
Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
|
|
|
|
None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
|
|
|
|
};
|
2022-08-31 13:28:55 +00:00
|
|
|
|
|
|
|
let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
|
2023-01-04 04:20:14 +00:00
|
|
|
pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None);
|
|
|
|
|
2022-08-31 13:28:55 +00:00
|
|
|
body
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
|
|
|
|
/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
|
|
|
|
/// end up missing the source MIR due to stealing happening.
|
2022-05-08 15:53:19 +02:00
|
|
|
fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
|
2023-11-26 21:05:08 +08:00
|
|
|
if tcx.is_coroutine(def.to_def_id()) {
|
2023-10-19 21:46:28 +00:00
|
|
|
tcx.ensure_with_value().mir_coroutine_witnesses(def);
|
2022-07-26 20:37:25 +02:00
|
|
|
}
|
2022-05-08 15:53:19 +02:00
|
|
|
let mir_borrowck = tcx.mir_borrowck(def);
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2022-05-08 15:53:19 +02:00
|
|
|
let is_fn_like = tcx.def_kind(def).is_fn_like();
|
2021-01-01 01:53:25 +01:00
|
|
|
if is_fn_like {
|
|
|
|
// Do not compute the mir call graph without said call graph actually being used.
|
2023-10-18 16:34:04 +00:00
|
|
|
if pm::should_run_pass(tcx, &inline::Inline) {
|
2022-05-08 15:53:19 +02:00
|
|
|
tcx.ensure_with_value().mir_inliner_callees(ty::InstanceDef::Item(def.to_def_id()));
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let (body, _) = tcx.mir_promoted(def);
|
|
|
|
let mut body = body.steal();
|
2022-02-07 22:00:15 -08:00
|
|
|
if let Some(error_reported) = mir_borrowck.tainted_by_errors {
|
|
|
|
body.tainted_by_errors = Some(error_reported);
|
|
|
|
}
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2023-04-25 17:11:46 +00:00
|
|
|
// Check if it's even possible to satisfy the 'where' clauses
|
|
|
|
// for this item.
|
|
|
|
//
|
|
|
|
// This branch will never be taken for any normal function.
|
|
|
|
// However, it's possible to `#!feature(trivial_bounds)]` to write
|
|
|
|
// a function with impossible to satisfy clauses, e.g.:
|
|
|
|
// `fn foo() where String: Copy {}`
|
|
|
|
//
|
|
|
|
// We don't usually need to worry about this kind of case,
|
|
|
|
// since we would get a compilation error if the user tried
|
|
|
|
// to call it. However, since we optimize even without any
|
|
|
|
// calls to the function, we need to make sure that it even
|
|
|
|
// makes sense to try to evaluate the body.
|
|
|
|
//
|
|
|
|
// If there are unsatisfiable where clauses, then all bets are
|
|
|
|
// off, and we just give up.
|
|
|
|
//
|
|
|
|
// We manually filter the predicates, skipping anything that's not
|
|
|
|
// "global". We are in a potentially generic context
|
2024-02-12 15:39:32 +09:00
|
|
|
// (e.g. we are evaluating a function without instantiating generic
|
2023-04-25 17:11:46 +00:00
|
|
|
// parameters, so this filtering serves two purposes:
|
|
|
|
//
|
|
|
|
// 1. We skip evaluating any predicates that we would
|
|
|
|
// never be able prove are unsatisfiable (e.g. `<T as Foo>`
|
|
|
|
// 2. We avoid trying to normalize predicates involving generic
|
|
|
|
// parameters (e.g. `<T as Foo>::MyItem`). This can confuse
|
|
|
|
// the normalization code (leading to cycle errors), since
|
|
|
|
// it's usually never invoked in this way.
|
|
|
|
let predicates = tcx
|
|
|
|
.predicates_of(body.source.def_id())
|
|
|
|
.predicates
|
|
|
|
.iter()
|
|
|
|
.filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
|
|
|
|
if traits::impossible_predicates(tcx, traits::elaborate(tcx, predicates).collect()) {
|
|
|
|
trace!("found unsatisfiable predicates for {:?}", body.source);
|
|
|
|
// Clear the body to only contain a single `unreachable` statement.
|
|
|
|
let bbs = body.basic_blocks.as_mut();
|
|
|
|
bbs.raw.truncate(1);
|
|
|
|
bbs[START_BLOCK].statements.clear();
|
|
|
|
bbs[START_BLOCK].terminator_mut().kind = TerminatorKind::Unreachable;
|
|
|
|
body.var_debug_info.clear();
|
|
|
|
body.local_decls.raw.truncate(body.arg_count + 1);
|
|
|
|
}
|
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
run_analysis_to_runtime_passes(tcx, &mut body);
|
|
|
|
|
2023-07-20 21:01:27 +02:00
|
|
|
// Now that drop elaboration has been performed, we can check for
|
|
|
|
// unconditional drop recursion.
|
|
|
|
rustc_mir_build::lints::check_drop_recursion(tcx, &body);
|
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
tcx.alloc_steal_mir(body)
|
|
|
|
}
|
|
|
|
|
2023-08-08 17:34:12 +02:00
|
|
|
// Made public such that `mir_drops_elaborated_and_const_checked` can be overridden
|
|
|
|
// by custom rustc drivers, running all the steps by themselves.
|
2023-08-08 16:25:15 +02:00
|
|
|
pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
2022-07-09 18:04:38 -07:00
|
|
|
assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
|
|
|
|
let did = body.source.def_id();
|
|
|
|
|
|
|
|
debug!("analysis_mir_cleanup({:?})", did);
|
|
|
|
run_analysis_cleanup_passes(tcx, body);
|
|
|
|
assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
|
2021-11-30 17:05:40 -08:00
|
|
|
|
|
|
|
// Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
|
2023-11-21 20:07:32 +01:00
|
|
|
if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
|
2021-12-02 14:20:03 -08:00
|
|
|
pm::run_passes(
|
|
|
|
tcx,
|
2022-07-09 18:04:38 -07:00
|
|
|
body,
|
2023-04-17 20:17:01 -06:00
|
|
|
&[&remove_uninit_drops::RemoveUninitDrops, &simplify::SimplifyCfg::RemoveFalseEdges],
|
2022-09-26 18:43:35 -07:00
|
|
|
None,
|
2021-12-02 14:20:03 -08:00
|
|
|
);
|
2023-11-21 20:07:32 +01:00
|
|
|
check_consts::post_drop_elaboration::check_live_drops(tcx, body); // FIXME: make this a MIR lint
|
2021-11-30 17:05:40 -08:00
|
|
|
}
|
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
debug!("runtime_mir_lowering({:?})", did);
|
|
|
|
run_runtime_lowering_passes(tcx, body);
|
|
|
|
assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
|
|
|
|
|
|
|
|
debug!("runtime_mir_cleanup({:?})", did);
|
|
|
|
run_runtime_cleanup_passes(tcx, body);
|
|
|
|
assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
// FIXME(JakobDegen): Can we make these lists of passes consts?
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
/// After this series of passes, no lifetime analysis based on borrowing can be done.
|
|
|
|
fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
|
|
|
let passes: &[&dyn MirPass<'tcx>] = &[
|
2022-12-17 00:00:00 +00:00
|
|
|
&cleanup_post_borrowck::CleanupPostBorrowck,
|
2021-01-01 01:53:25 +01:00
|
|
|
&remove_noop_landing_pads::RemoveNoopLandingPads,
|
2023-04-17 20:17:01 -06:00
|
|
|
&simplify::SimplifyCfg::EarlyOpt,
|
2022-06-13 16:37:41 +03:00
|
|
|
&deref_separator::Derefer,
|
2022-07-09 18:04:38 -07:00
|
|
|
];
|
|
|
|
|
2022-09-26 18:43:35 -07:00
|
|
|
pm::run_passes(tcx, body, passes, Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)));
|
2022-07-09 18:04:38 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the sequence of passes that lowers analysis to runtime MIR.
|
|
|
|
fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
|
|
|
let passes: &[&dyn MirPass<'tcx>] = &[
|
2021-01-01 01:53:25 +01:00
|
|
|
// These next passes must be executed together
|
|
|
|
&add_call_guards::CriticalCallEdges,
|
2023-09-11 15:00:46 +00:00
|
|
|
&reveal_all::RevealAll, // has to be done before drop elaboration, since we need to drop opaque types, too.
|
2023-10-03 13:19:00 +03:00
|
|
|
&add_subtyping_projections::Subtyper, // calling this after reveal_all ensures that we don't deal with opaque types
|
2021-01-01 01:53:25 +01:00
|
|
|
&elaborate_drops::ElaborateDrops,
|
|
|
|
// This will remove extraneous landing pads which are no longer
|
|
|
|
// necessary as well as well as forcing any call in a non-unwinding
|
|
|
|
// function calling a possibly-unwinding function to abort the process.
|
|
|
|
&abort_unwinding_calls::AbortUnwindingCalls,
|
|
|
|
// AddMovesForPackedDrops needs to run after drop
|
|
|
|
// elaboration.
|
|
|
|
&add_moves_for_packed_drops::AddMovesForPackedDrops,
|
|
|
|
// `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
|
|
|
|
// but before optimizations begin.
|
2022-05-13 21:53:03 -07:00
|
|
|
&elaborate_box_derefs::ElaborateBoxDerefs,
|
2023-10-19 21:46:28 +00:00
|
|
|
&coroutine::StateTransform,
|
2021-01-01 01:53:25 +01:00
|
|
|
&add_retag::AddRetag,
|
2024-02-20 07:41:48 +05:30
|
|
|
&Lint(known_panics_lint::KnownPanicsLint),
|
2022-07-09 18:04:38 -07:00
|
|
|
];
|
2022-09-26 18:43:35 -07:00
|
|
|
pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
|
2022-07-09 18:04:38 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
|
|
|
|
fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
2023-03-18 16:11:48 +00:00
|
|
|
let passes: &[&dyn MirPass<'tcx>] = &[
|
|
|
|
&lower_intrinsics::LowerIntrinsics,
|
|
|
|
&remove_place_mention::RemovePlaceMention,
|
|
|
|
&simplify::SimplifyCfg::ElaborateDrops,
|
|
|
|
];
|
2021-01-01 01:53:25 +01:00
|
|
|
|
2022-09-26 18:43:35 -07:00
|
|
|
pm::run_passes(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::PostCleanup)));
|
2023-03-10 10:29:41 +00:00
|
|
|
|
|
|
|
// Clear this by anticipation. Optimizations and runtime MIR have no reason to look
|
|
|
|
// into this information, which is meant for borrowck diagnostics.
|
|
|
|
for decl in &mut body.local_decls {
|
|
|
|
decl.local_info = ClearCrossCrate::Clear;
|
|
|
|
}
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
2021-12-02 14:38:04 -08:00
|
|
|
fn o1<T>(x: T) -> WithMinOptLevel<T> {
|
|
|
|
WithMinOptLevel(1, x)
|
|
|
|
}
|
|
|
|
|
2022-07-09 18:04:38 -07:00
|
|
|
// The main optimizations that we do on MIR.
|
2021-12-02 14:20:03 -08:00
|
|
|
pm::run_passes(
|
2021-01-01 01:53:25 +01:00
|
|
|
tcx,
|
|
|
|
body,
|
|
|
|
&[
|
2022-11-10 11:37:28 -05:00
|
|
|
&check_alignment::CheckAlignment,
|
2024-01-07 00:30:08 +00:00
|
|
|
// Before inlining: trim down MIR with passes to reduce inlining work.
|
|
|
|
|
|
|
|
// Has to be done before inlining, otherwise actual call will be almost always inlined.
|
|
|
|
// Also simple, so can just do first
|
|
|
|
&lower_slice_len::LowerSliceLenCalls,
|
|
|
|
// Perform inlining, which may add a lot of code.
|
2023-07-22 15:34:54 +00:00
|
|
|
&inline::Inline,
|
2024-01-07 00:30:08 +00:00
|
|
|
// Code from other crates may have storage markers, so this needs to happen after inlining.
|
|
|
|
&remove_storage_markers::RemoveStorageMarkers,
|
2024-02-12 15:39:32 +09:00
|
|
|
// Inlining and instantiation may introduce ZST and useless drops.
|
2024-01-07 00:30:08 +00:00
|
|
|
&remove_zsts::RemoveZsts,
|
|
|
|
&remove_unneeded_drops::RemoveUnneededDrops,
|
2024-02-12 15:39:32 +09:00
|
|
|
// Type instantiation may create uninhabited enums.
|
2021-12-02 14:20:03 -08:00
|
|
|
&uninhabited_enum_branching::UninhabitedEnumBranching,
|
2023-07-22 15:34:54 +00:00
|
|
|
&unreachable_prop::UnreachablePropagation,
|
2023-04-17 20:17:01 -06:00
|
|
|
&o1(simplify::SimplifyCfg::AfterUninhabitedEnumBranching),
|
2024-01-07 00:30:08 +00:00
|
|
|
// Inlining may have introduced a lot of redundant code and a large move pattern.
|
|
|
|
// Now, we need to shrink the generated MIR.
|
|
|
|
|
|
|
|
// Has to run after `slice::len` lowering
|
|
|
|
&normalize_array_len::NormalizeArrayLen,
|
2023-03-12 14:10:30 +00:00
|
|
|
&ref_prop::ReferencePropagation,
|
2022-05-23 09:27:44 +02:00
|
|
|
&sroa::ScalarReplacementOfAggregates,
|
2021-12-02 14:20:03 -08:00
|
|
|
&match_branches::MatchBranchSimplification,
|
|
|
|
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
|
|
|
|
&multiple_return_terminators::MultipleReturnTerminators,
|
2023-05-06 23:20:58 -04:00
|
|
|
&instsimplify::InstSimplify,
|
2023-04-17 20:17:01 -06:00
|
|
|
&simplify::SimplifyLocals::BeforeConstProp,
|
2024-01-06 18:34:25 +00:00
|
|
|
&dead_store_elimination::DeadStoreElimination::Initial,
|
|
|
|
&gvn::GVN,
|
|
|
|
&simplify::SimplifyLocals::AfterGVN,
|
2022-08-25 16:43:46 +00:00
|
|
|
&dataflow_const_prop::DataflowConstProp,
|
2022-05-09 20:12:03 -04:00
|
|
|
&const_debuginfo::ConstDebugInfo,
|
2023-04-21 15:45:25 -06:00
|
|
|
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
|
2023-01-16 22:12:36 +00:00
|
|
|
&jump_threading::JumpThreading,
|
2021-12-02 14:20:03 -08:00
|
|
|
&early_otherwise_branch::EarlyOtherwiseBranch,
|
|
|
|
&simplify_comparison_integral::SimplifyComparisonIntegral,
|
|
|
|
&dest_prop::DestinationPropagation,
|
2023-04-21 15:45:25 -06:00
|
|
|
&o1(simplify_branches::SimplifyConstCondition::Final),
|
2021-12-02 14:38:04 -08:00
|
|
|
&o1(remove_noop_landing_pads::RemoveNoopLandingPads),
|
2023-04-17 20:17:01 -06:00
|
|
|
&o1(simplify::SimplifyCfg::Final),
|
2024-01-06 18:34:25 +00:00
|
|
|
©_prop::CopyProp,
|
|
|
|
&dead_store_elimination::DeadStoreElimination::Final,
|
2021-12-02 14:20:03 -08:00
|
|
|
&nrvo::RenameReturnPlace,
|
2023-04-17 20:17:01 -06:00
|
|
|
&simplify::SimplifyLocals::Final,
|
2021-12-02 14:20:03 -08:00
|
|
|
&multiple_return_terminators::MultipleReturnTerminators,
|
|
|
|
&deduplicate_blocks::DeduplicateBlocks,
|
2023-02-05 22:14:40 +00:00
|
|
|
&large_enums::EnumSizeOpt { discrepancy: 128 },
|
2021-12-02 14:20:03 -08:00
|
|
|
// Some cleanup necessary at least for LLVM and potentially other codegen backends.
|
|
|
|
&add_call_guards::CriticalCallEdges,
|
2023-05-21 17:38:34 -07:00
|
|
|
// Cleanup for human readability, off by default.
|
|
|
|
&prettify::ReorderBasicBlocks,
|
|
|
|
&prettify::ReorderLocals,
|
2021-12-02 14:20:03 -08:00
|
|
|
// Dump the end result for testing and debugging purposes.
|
|
|
|
&dump_mir::Marker("PreCodegen"),
|
2021-01-01 01:53:25 +01:00
|
|
|
],
|
2022-09-26 18:43:35 -07:00
|
|
|
Some(MirPhase::Runtime(RuntimePhase::Optimized)),
|
2021-01-01 01:53:25 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Optimize the MIR and prepare it for codegen.
|
2023-03-13 18:54:05 +00:00
|
|
|
fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
|
2021-01-01 01:53:25 +01:00
|
|
|
tcx.arena.alloc(inner_optimized_mir(tcx, did))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
|
|
|
|
if tcx.is_constructor(did.to_def_id()) {
|
|
|
|
// There's no reason to run all of the MIR passes on constructors when
|
|
|
|
// we can just output the MIR we want directly. This also saves const
|
|
|
|
// qualification and borrow checking the trouble of special casing
|
|
|
|
// constructors.
|
|
|
|
return shim::build_adt_ctor(tcx, did.to_def_id());
|
|
|
|
}
|
|
|
|
|
|
|
|
match tcx.hir().body_const_context(did) {
|
|
|
|
// Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
|
|
|
|
// which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
|
|
|
|
// computes and caches its result.
|
2023-03-07 08:34:47 +00:00
|
|
|
Some(hir::ConstContext::ConstFn) => tcx.ensure_with_value().mir_for_ctfe(did),
|
2021-01-01 01:53:25 +01:00
|
|
|
None => {}
|
2023-07-25 23:17:39 +02:00
|
|
|
Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
2022-02-16 10:56:01 +01:00
|
|
|
debug!("about to call mir_drops_elaborated...");
|
2022-05-08 15:53:19 +02:00
|
|
|
let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
|
2022-08-31 13:28:55 +00:00
|
|
|
let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
|
2023-09-13 22:54:22 +08:00
|
|
|
|
|
|
|
if body.tainted_by_errors.is_some() {
|
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
2023-10-08 12:08:09 +00:00
|
|
|
// If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable
|
|
|
|
// predicates, it will shrink the MIR to a single `unreachable` terminator.
|
|
|
|
// More generally, if MIR is a lone `unreachable`, there is nothing to optimize.
|
|
|
|
if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
|
|
|
|
&& body.basic_blocks[START_BLOCK].statements.is_empty()
|
|
|
|
{
|
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
2021-01-01 01:53:25 +01:00
|
|
|
run_optimization_passes(tcx, &mut body);
|
|
|
|
|
2022-08-31 13:28:55 +00:00
|
|
|
body
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
|
2024-02-12 15:39:32 +09:00
|
|
|
/// constant evaluation once all generic parameters become known.
|
2022-05-08 15:53:19 +02:00
|
|
|
fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
|
|
|
|
if tcx.is_constructor(def.to_def_id()) {
|
2021-01-01 01:53:25 +01:00
|
|
|
return tcx.arena.alloc(IndexVec::new());
|
|
|
|
}
|
|
|
|
|
2023-04-30 00:00:00 +00:00
|
|
|
tcx.ensure_with_value().mir_borrowck(def);
|
2022-02-07 22:00:15 -08:00
|
|
|
let mut promoted = tcx.mir_promoted(def).1.steal();
|
2021-01-01 01:53:25 +01:00
|
|
|
|
|
|
|
for body in &mut promoted {
|
2022-07-09 18:04:38 -07:00
|
|
|
run_analysis_to_runtime_passes(tcx, body);
|
2021-01-01 01:53:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
tcx.arena.alloc(promoted)
|
|
|
|
}
|