1 //! Performs various peephole optimizations.
4 use rustc_hir::Mutability;
5 use rustc_middle::mir::{
6 BinOp, Body, Constant, ConstantKind, LocalDecls, Operand, Place, ProjectionElem, Rvalue,
7 SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UnOp,
9 use rustc_middle::ty::{self, layout::TyAndLayout, ParamEnv, ParamEnvAnd, SubstsRef, Ty, TyCtxt};
10 use rustc_span::symbol::{sym, Symbol};
12 pub struct InstCombine;
14 impl<'tcx> MirPass<'tcx> for InstCombine {
15 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
16 sess.mir_opt_level() > 0
19 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
20 let ctx = InstCombineContext {
22 local_decls: &body.local_decls,
23 param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
25 for block in body.basic_blocks.as_mut() {
26 for statement in block.statements.iter_mut() {
27 match statement.kind {
28 StatementKind::Assign(box (_place, ref mut rvalue)) => {
29 ctx.combine_bool_cmp(&statement.source_info, rvalue);
30 ctx.combine_ref_deref(&statement.source_info, rvalue);
31 ctx.combine_len(&statement.source_info, rvalue);
37 ctx.combine_primitive_clone(
38 &mut block.terminator.as_mut().unwrap(),
39 &mut block.statements,
41 ctx.combine_intrinsic_assert(
42 &mut block.terminator.as_mut().unwrap(),
43 &mut block.statements,
49 struct InstCombineContext<'tcx, 'a> {
51 local_decls: &'a LocalDecls<'tcx>,
52 param_env: ParamEnv<'tcx>,
55 impl<'tcx> InstCombineContext<'tcx, '_> {
56 fn should_combine(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool {
57 self.tcx.consider_optimizing(|| {
58 format!("InstCombine - Rvalue: {:?} SourceInfo: {:?}", rvalue, source_info)
62 /// Transform boolean comparisons into logical operations.
63 fn combine_bool_cmp(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
65 Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), box (a, b)) => {
66 let new = match (op, self.try_eval_bool(a), self.try_eval_bool(b)) {
67 // Transform "Eq(a, true)" ==> "a"
68 (BinOp::Eq, _, Some(true)) => Some(Rvalue::Use(a.clone())),
70 // Transform "Ne(a, false)" ==> "a"
71 (BinOp::Ne, _, Some(false)) => Some(Rvalue::Use(a.clone())),
73 // Transform "Eq(true, b)" ==> "b"
74 (BinOp::Eq, Some(true), _) => Some(Rvalue::Use(b.clone())),
76 // Transform "Ne(false, b)" ==> "b"
77 (BinOp::Ne, Some(false), _) => Some(Rvalue::Use(b.clone())),
79 // Transform "Eq(false, b)" ==> "Not(b)"
80 (BinOp::Eq, Some(false), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
82 // Transform "Ne(true, b)" ==> "Not(b)"
83 (BinOp::Ne, Some(true), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
85 // Transform "Eq(a, false)" ==> "Not(a)"
86 (BinOp::Eq, _, Some(false)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
88 // Transform "Ne(a, true)" ==> "Not(a)"
89 (BinOp::Ne, _, Some(true)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
94 if let Some(new) = new && self.should_combine(source_info, rvalue) {
103 fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
104 let a = a.constant()?;
105 if a.literal.ty().is_bool() { a.literal.try_to_bool() } else { None }
108 /// Transform "&(*a)" ==> "a".
109 fn combine_ref_deref(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
110 if let Rvalue::Ref(_, _, place) = rvalue {
111 if let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
112 if let ty::Ref(_, _, Mutability::Not) =
113 base.ty(self.local_decls, self.tcx).ty.kind()
115 // The dereferenced place must have type `&_`, so that we don't copy `&mut _`.
120 if !self.should_combine(source_info, rvalue) {
124 *rvalue = Rvalue::Use(Operand::Copy(Place {
126 projection: self.tcx.intern_place_elems(base.projection),
132 /// Transform "Len([_; N])" ==> "N".
133 fn combine_len(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
134 if let Rvalue::Len(ref place) = *rvalue {
135 let place_ty = place.ty(self.local_decls, self.tcx).ty;
136 if let ty::Array(_, len) = *place_ty.kind() {
137 if !self.should_combine(source_info, rvalue) {
141 let literal = ConstantKind::from_const(len, self.tcx);
142 let constant = Constant { span: source_info.span, literal, user_ty: None };
143 *rvalue = Rvalue::Use(Operand::Constant(Box::new(constant)));
148 fn combine_primitive_clone(
150 terminator: &mut Terminator<'tcx>,
151 statements: &mut Vec<Statement<'tcx>>,
153 let TerminatorKind::Call { func, args, destination, target, .. } = &mut terminator.kind
156 // It's definitely not a clone if there are multiple arguments
161 let Some(destination_block) = *target
164 // Only bother looking more if it's easy to know what we're calling
165 let Some((fn_def_id, fn_substs)) = func.const_fn_def()
168 // Clone needs one subst, so we can cheaply rule out other stuff
169 if fn_substs.len() != 1 {
173 // These types are easily available from locals, so check that before
174 // doing DefId lookups to figure out what we're actually calling.
175 let arg_ty = args[0].ty(self.local_decls, self.tcx);
177 let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind()
180 if !inner_ty.is_trivially_pure_clone_copy() {
184 let trait_def_id = self.tcx.trait_of_item(fn_def_id);
185 if trait_def_id.is_none() || trait_def_id != self.tcx.lang_items().clone_trait() {
189 if !self.tcx.consider_optimizing(|| {
191 "InstCombine - Call: {:?} SourceInfo: {:?}",
192 (fn_def_id, fn_substs),
193 terminator.source_info
199 let Some(arg_place) = args.pop().unwrap().place()
202 statements.push(Statement {
203 source_info: terminator.source_info,
204 kind: StatementKind::Assign(Box::new((
206 Rvalue::Use(Operand::Copy(
207 arg_place.project_deeper(&[ProjectionElem::Deref], self.tcx),
211 terminator.kind = TerminatorKind::Goto { target: destination_block };
214 fn combine_intrinsic_assert(
216 terminator: &mut Terminator<'tcx>,
217 _statements: &mut Vec<Statement<'tcx>>,
219 let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { return; };
220 let Some(target_block) = target else { return; };
221 let func_ty = func.ty(self.local_decls, self.tcx);
222 let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(self.tcx, func_ty) else {
225 // The intrinsics we are interested in have one generic parameter
226 if substs.is_empty() {
229 let ty = substs.type_at(0);
231 // Check this is a foldable intrinsic before we query the layout of our generic parameter
232 let Some(assert_panics) = intrinsic_assert_panics(intrinsic_name) else { return; };
233 let Ok(layout) = self.tcx.layout_of(self.param_env.and(ty)) else { return; };
234 if assert_panics(self.tcx, self.param_env.and(layout)) {
235 // If we know the assert panics, indicate to later opts that the call diverges
238 // If we know the assert does not panic, turn the call into a Goto
239 terminator.kind = TerminatorKind::Goto { target: *target_block };
244 fn intrinsic_assert_panics<'tcx>(
245 intrinsic_name: Symbol,
246 ) -> Option<fn(TyCtxt<'tcx>, ParamEnvAnd<'tcx, TyAndLayout<'tcx>>) -> bool> {
247 fn inhabited_predicate<'tcx>(
249 param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>,
251 let (_param_env, layout) = param_env_and_layout.into_parts();
252 layout.abi.is_uninhabited()
254 fn zero_valid_predicate<'tcx>(
256 param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>,
258 !tcx.permits_zero_init(param_env_and_layout)
260 fn mem_uninitialized_valid_predicate<'tcx>(
262 param_env_and_layout: ParamEnvAnd<'tcx, TyAndLayout<'tcx>>,
264 !tcx.permits_uninit_init(param_env_and_layout)
267 match intrinsic_name {
268 sym::assert_inhabited => Some(inhabited_predicate),
269 sym::assert_zero_valid => Some(zero_valid_predicate),
270 sym::assert_mem_uninitialized_valid => Some(mem_uninitialized_valid_predicate),
275 fn resolve_rust_intrinsic<'tcx>(
278 ) -> Option<(Symbol, SubstsRef<'tcx>)> {
279 if let ty::FnDef(def_id, substs) = *func_ty.kind() {
280 if tcx.is_intrinsic(def_id) {
281 return Some((tcx.item_name(def_id), substs));