Skip to main content

rustc_mir_transform/
instsimplify.rs

1//! Performs various peephole optimizations.
2
3use rustc_abi::{ExternAbi, Integer};
4use rustc_hir::{LangItem, find_attr};
5use rustc_index::IndexVec;
6use rustc_middle::bug;
7use rustc_middle::mir::visit::MutVisitor;
8use rustc_middle::mir::*;
9use rustc_middle::ty::layout::{IntegerExt, ValidityRequirement};
10use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, layout};
11use rustc_span::{Symbol, sym};
12
13use crate::PassPolicy;
14use crate::simplify::simplify_duplicate_switch_targets;
15
16pub(super) enum InstSimplify {
17    BeforeInline,
18    AfterSimplifyCfg,
19}
20
21impl<'tcx> crate::MirPass<'tcx> for InstSimplify {
22    fn name(&self) -> &'static str {
23        match self {
24            InstSimplify::BeforeInline => "InstSimplify-before-inline",
25            InstSimplify::AfterSimplifyCfg => "InstSimplify-after-simplifycfg",
26        }
27    }
28
29    fn policy(&self, sess: &rustc_session::Session) -> PassPolicy {
30        PassPolicy::optimization(sess.mir_opt_level() > 0)
31    }
32
33    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
34        let preserve_ub_checks = find_attr!(tcx.hir_krate_attrs(), RustcPreserveUbChecks);
35        if !preserve_ub_checks {
36            SimplifyUbCheck { tcx }.visit_body(body);
37        }
38        let mut ctx = InstSimplifyContext {
39            tcx,
40            typing_env: body.typing_env(tcx),
41            local_decls: &mut body.local_decls,
42        };
43        for block in body.basic_blocks.as_mut() {
44            for statement in block.statements.iter_mut() {
45                let StatementKind::Assign((.., rvalue)) = &mut statement.kind else {
46                    continue;
47                };
48
49                ctx.simplify_bool_cmp(rvalue);
50                ctx.simplify_ref_deref(rvalue);
51                ctx.simplify_ptr_aggregate(rvalue);
52                ctx.simplify_cast(rvalue);
53                ctx.simplify_repeated_aggregate(rvalue);
54                ctx.simplify_repeat_once(rvalue);
55            }
56
57            let terminator = block.terminator.as_mut().unwrap();
58            ctx.simplify_primitive_clone(terminator, &mut block.statements);
59            ctx.simplify_size_or_align_of_val(terminator, &mut block.statements);
60            ctx.simplify_raw_eq(terminator, &mut block.statements);
61            ctx.simplify_intrinsic_assert(terminator);
62            ctx.simplify_nounwind_call(terminator);
63            simplify_duplicate_switch_targets(terminator);
64        }
65    }
66}
67
68struct InstSimplifyContext<'a, 'tcx> {
69    tcx: TyCtxt<'tcx>,
70    local_decls: &'a mut IndexVec<Local, LocalDecl<'tcx>>,
71    typing_env: ty::TypingEnv<'tcx>,
72}
73
74impl<'tcx> InstSimplifyContext<'_, 'tcx> {
75    /// Transform aggregates like [0, 0, 0, 0, 0] into [0; 5].
76    /// GVN can also do this optimization, but GVN is only run at mir-opt-level 2 so having this in
77    /// InstSimplify helps unoptimized builds.
78    fn simplify_repeated_aggregate(&self, rvalue: &mut Rvalue<'tcx>) {
79        let Rvalue::Aggregate(AggregateKind::Array(_), fields) = &*rvalue else {
80            return;
81        };
82        if fields.len() < 5 {
83            return;
84        }
85        let (first, rest) = fields[..].split_first().unwrap();
86        let Operand::Constant(first) = first else {
87            return;
88        };
89        let Ok(first_val) = first.const_.eval(self.tcx, self.typing_env, first.span) else {
90            return;
91        };
92        if rest.iter().all(|field| {
93            let Operand::Constant(field) = field else {
94                return false;
95            };
96            let field = field.const_.eval(self.tcx, self.typing_env, field.span);
97            field == Ok(first_val)
98        }) {
99            let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
100            *rvalue = Rvalue::Repeat(Operand::Constant(first.clone()), len);
101        }
102    }
103
104    /// Transform boolean comparisons into logical operations.
105    fn simplify_bool_cmp(&self, rvalue: &mut Rvalue<'tcx>) {
106        let Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), (a, b)) = &*rvalue else { return };
107        *rvalue = match (op, self.try_eval_bool(a), self.try_eval_bool(b)) {
108            // Transform "Eq(a, true)" ==> "a"
109            (BinOp::Eq, _, Some(true)) => Rvalue::Use(a.clone(), WithRetag::Yes),
110
111            // Transform "Ne(a, false)" ==> "a"
112            (BinOp::Ne, _, Some(false)) => Rvalue::Use(a.clone(), WithRetag::Yes),
113
114            // Transform "Eq(true, b)" ==> "b"
115            (BinOp::Eq, Some(true), _) => Rvalue::Use(b.clone(), WithRetag::Yes),
116
117            // Transform "Ne(false, b)" ==> "b"
118            (BinOp::Ne, Some(false), _) => Rvalue::Use(b.clone(), WithRetag::Yes),
119
120            // Transform "Eq(false, b)" ==> "Not(b)"
121            (BinOp::Eq, Some(false), _) => Rvalue::UnaryOp(UnOp::Not, b.clone()),
122
123            // Transform "Ne(true, b)" ==> "Not(b)"
124            (BinOp::Ne, Some(true), _) => Rvalue::UnaryOp(UnOp::Not, b.clone()),
125
126            // Transform "Eq(a, false)" ==> "Not(a)"
127            (BinOp::Eq, _, Some(false)) => Rvalue::UnaryOp(UnOp::Not, a.clone()),
128
129            // Transform "Ne(a, true)" ==> "Not(a)"
130            (BinOp::Ne, _, Some(true)) => Rvalue::UnaryOp(UnOp::Not, a.clone()),
131
132            _ => return,
133        };
134    }
135
136    fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
137        let a = a.constant()?;
138        if a.const_.ty().is_bool() { a.const_.try_to_bool() } else { None }
139    }
140
141    /// Transform `&(*a)` ==> `a`.
142    fn simplify_ref_deref(&self, rvalue: &mut Rvalue<'tcx>) {
143        if let Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) = rvalue
144            && let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection()
145            && rvalue.ty(self.local_decls, self.tcx) == base.ty(self.local_decls, self.tcx).ty
146        {
147            *rvalue = Rvalue::Use(
148                Operand::Copy(Place {
149                    local: base.local,
150                    projection: self.tcx.mk_place_elems(base.projection),
151                }),
152                // This might have been a two-phase borrow, which we should not upgrade
153                // to a full `&mut` reborrow.
154                // FIXME: Once Stacked Borrows is fully removed, we can use `Yes` here as
155                // Tree Borrows treats two-phase and full borrows the same.
156                if matches!(
157                    rvalue,
158                    Rvalue::Ref(_, BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow }, _)
159                ) {
160                    WithRetag::No
161                } else {
162                    WithRetag::Yes
163                },
164            );
165        }
166    }
167
168    /// Transform `Aggregate(RawPtr, [p, ()])` ==> `Cast(PtrToPtr, p)`.
169    fn simplify_ptr_aggregate(&self, rvalue: &mut Rvalue<'tcx>) {
170        if let Rvalue::Aggregate(AggregateKind::RawPtr(pointee_ty, mutability), fields) = rvalue
171            && let meta_ty = fields.raw[1].ty(self.local_decls, self.tcx)
172            && meta_ty.is_unit()
173        {
174            // The mutable borrows we're holding prevent printing `rvalue` here
175            let mut fields = std::mem::take(fields);
176            let _meta = fields.pop().unwrap();
177            let data = fields.pop().unwrap();
178            let ptr_ty = Ty::new_ptr(self.tcx, *pointee_ty, *mutability);
179            *rvalue = Rvalue::Cast(CastKind::PtrToPtr, data, ptr_ty);
180        }
181    }
182
183    fn simplify_cast(&self, rvalue: &mut Rvalue<'tcx>) {
184        let Rvalue::Cast(kind, operand, cast_ty) = rvalue else { return };
185
186        let operand_ty = operand.ty(self.local_decls, self.tcx);
187        if operand_ty == *cast_ty {
188            *rvalue = Rvalue::Use(operand.clone(), WithRetag::Yes);
189        } else if *kind == CastKind::Transmute
190            // Transmuting an integer to another integer is just a signedness cast
191            && let (ty::Int(int), ty::Uint(uint)) | (ty::Uint(uint), ty::Int(int)) =
192                (operand_ty.kind(), cast_ty.kind())
193            && int.bit_width() == uint.bit_width()
194        {
195            // The width check isn't strictly necessary, as different widths
196            // are UB and thus we'd be allowed to turn it into a cast anyway.
197            // But let's keep the UB around for codegen to exploit later.
198            // (If `CastKind::Transmute` ever becomes *not* UB for mismatched sizes,
199            // then the width check is necessary for big-endian correctness.)
200            *kind = CastKind::IntToInt;
201        }
202    }
203
204    /// Simplify `[x; 1]` to just `[x]`.
205    fn simplify_repeat_once(&self, rvalue: &mut Rvalue<'tcx>) {
206        if let Rvalue::Repeat(operand, count) = rvalue
207            && let Some(1) = count.try_to_target_usize(self.tcx)
208        {
209            *rvalue = Rvalue::Aggregate(
210                Box::new(AggregateKind::Array(operand.ty(self.local_decls, self.tcx))),
211                [operand.clone()].into(),
212            );
213        }
214    }
215
216    fn simplify_primitive_clone(
217        &self,
218        terminator: &mut Terminator<'tcx>,
219        statements: &mut Vec<Statement<'tcx>>,
220    ) {
221        let TerminatorKind::Call {
222            func, args, destination, target: Some(destination_block), ..
223        } = &terminator.kind
224        else {
225            return;
226        };
227
228        // It's definitely not a clone if there are multiple arguments
229        let [arg] = &args[..] else { return };
230
231        // Only bother looking more if it's easy to know what we're calling
232        let Some((fn_def_id, ..)) = func.const_fn_def() else { return };
233
234        // These types are easily available from locals, so check that before
235        // doing DefId lookups to figure out what we're actually calling.
236        let arg_ty = arg.node.ty(self.local_decls, self.tcx);
237
238        let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() else { return };
239
240        if !self.tcx.is_lang_item(fn_def_id, LangItem::CloneFn)
241            || !inner_ty.is_trivially_pure_clone_copy()
242        {
243            return;
244        }
245
246        let Some(arg_place) = arg.node.place() else { return };
247
248        statements.push(Statement::new(
249            terminator.source_info,
250            StatementKind::Assign(Box::new((
251                *destination,
252                Rvalue::Use(
253                    Operand::Copy(arg_place.project_deeper(&[ProjectionElem::Deref], self.tcx)),
254                    WithRetag::Yes,
255                ),
256            ))),
257        ));
258        terminator.kind = TerminatorKind::Goto { target: *destination_block };
259    }
260
261    /// Simplify `size_of_val` and `align_of_val` if we don't actually need
262    /// to look at the value in order to calculate the result:
263    /// - For `Sized` types we can always do this for both,
264    /// - For `align_of_val::<[T]>` we can return `align_of::<T>()`, since it
265    ///   doesn't depend on the slice's length and the elements are sized.
266    ///
267    /// This is here so it can run after inlining, where it's more useful.
268    /// (LowerIntrinsics is done in cleanup, before the optimization passes.)
269    ///
270    /// Note that we intentionally just produce the lang item constants so this
271    /// works on generic types and avoids any risk of layout calculation cycles.
272    fn simplify_size_or_align_of_val(
273        &self,
274        terminator: &mut Terminator<'tcx>,
275        statements: &mut Vec<Statement<'tcx>>,
276    ) {
277        let source_info = terminator.source_info;
278        if let TerminatorKind::Call {
279            func, args, destination, target: Some(destination_block), ..
280        } = &terminator.kind
281            && args.len() == 1
282            && let Some((fn_def_id, generics)) = func.const_fn_def()
283        {
284            let lang_item = if self.tcx.is_intrinsic(fn_def_id, sym::size_of_val) {
285                LangItem::SizeOf
286            } else if self.tcx.is_intrinsic(fn_def_id, sym::align_of_val) {
287                LangItem::AlignOf
288            } else {
289                return;
290            };
291            let generic_ty = generics.type_at(0);
292            let ty = if generic_ty.is_sized(self.tcx, self.typing_env) {
293                generic_ty
294            } else if let LangItem::AlignOf = lang_item
295                && let ty::Slice(elem_ty) = *generic_ty.kind()
296            {
297                elem_ty
298            } else {
299                return;
300            };
301
302            let const_def_id = self.tcx.require_lang_item(lang_item, source_info.span);
303            let const_op = Operand::unevaluated_constant(
304                self.tcx,
305                const_def_id,
306                &[ty.into()],
307                source_info.span,
308            );
309            statements.push(Statement::new(
310                source_info,
311                StatementKind::Assign(Box::new((
312                    *destination,
313                    Rvalue::Use(const_op, WithRetag::Yes),
314                ))),
315            ));
316            terminator.kind = TerminatorKind::Goto { target: *destination_block };
317        }
318    }
319
320    /// Simplify `raw_eq` intrinsic calls to `Eq` when the type has the size of a primitive.
321    ///
322    /// For example, replace `raw_eq::<[u8; 4]>(a, b)` with `Eq(Transmute(a), Transmute(b))`.
323    fn simplify_raw_eq(
324        &mut self,
325        terminator: &mut Terminator<'tcx>,
326        statements: &mut Vec<Statement<'tcx>>,
327    ) {
328        let tcx = self.tcx;
329        let source_info = terminator.source_info;
330        let span = source_info.span;
331        if let TerminatorKind::Call {
332            func, args, destination, target: Some(destination_block), ..
333        } = &terminator.kind
334            && args.len() == 2
335            && let Some((fn_def_id, generics)) = func.const_fn_def()
336            && tcx.is_intrinsic(fn_def_id, sym::raw_eq)
337            && let generic_ty = generics.type_at(0)
338            && let Ok(layout) = tcx.layout_of(self.typing_env.as_query_input(generic_ty))
339            && let Ok(integer) = Integer::from_size(layout.size)
340        {
341            let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, generic_ty);
342            let uint_ty = integer.to_ty(tcx, false);
343
344            let mut transmute_operand = |op: &Operand<'tcx>| -> Operand<'tcx> {
345                let ref_local = self.local_decls.push(LocalDecl::new(ref_ty, span));
346                statements.push(Statement::new(
347                    source_info,
348                    StatementKind::Assign(Box::new((
349                        Place::from(ref_local),
350                        Rvalue::Use(op.clone(), WithRetag::Yes),
351                    ))),
352                ));
353                let place = Place::from(ref_local).project_deeper(&[ProjectionElem::Deref], tcx);
354                let int_local = self.local_decls.push(LocalDecl::new(uint_ty, span));
355                statements.push(Statement::new(
356                    source_info,
357                    StatementKind::Assign(Box::new((
358                        Place::from(int_local),
359                        Rvalue::Cast(CastKind::Transmute, Operand::Copy(place), uint_ty),
360                    ))),
361                ));
362                Operand::Move(Place::from(int_local))
363            };
364            let lhs_op = transmute_operand(&args[0].node);
365            let rhs_op = transmute_operand(&args[1].node);
366            statements.push(Statement::new(
367                source_info,
368                StatementKind::Assign(Box::new((
369                    *destination,
370                    Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs_op, rhs_op))),
371                ))),
372            ));
373            terminator.kind = TerminatorKind::Goto { target: *destination_block };
374        }
375    }
376
377    fn simplify_nounwind_call(&self, terminator: &mut Terminator<'tcx>) {
378        let TerminatorKind::Call { ref func, ref mut unwind, .. } = terminator.kind else {
379            return;
380        };
381
382        let Some((def_id, _)) = func.const_fn_def() else {
383            return;
384        };
385
386        let body_ty = self.tcx.type_of(def_id).skip_binder();
387        let body_abi = match body_ty.kind() {
388            ty::FnDef(..) => body_ty.fn_sig(self.tcx).abi(),
389            ty::Closure(..) => ExternAbi::RustCall,
390            ty::Coroutine(..) => ExternAbi::Rust,
391            _ => bug!("unexpected body ty: {body_ty:?}"),
392        };
393
394        if !layout::fn_can_unwind(self.tcx, Some(def_id), body_abi) {
395            *unwind = UnwindAction::Unreachable;
396        }
397    }
398
399    fn simplify_intrinsic_assert(&self, terminator: &mut Terminator<'tcx>) {
400        let TerminatorKind::Call { ref func, target: ref mut target @ Some(target_block), .. } =
401            terminator.kind
402        else {
403            return;
404        };
405        let func_ty = func.ty(self.local_decls, self.tcx);
406        let Some((intrinsic_name, args)) = resolve_rust_intrinsic(self.tcx, func_ty) else {
407            return;
408        };
409        // The intrinsics we are interested in have one generic parameter
410        let [arg, ..] = args[..] else { return };
411
412        let known_is_valid =
413            intrinsic_assert_panics(self.tcx, self.typing_env, arg, intrinsic_name);
414        match known_is_valid {
415            // We don't know the layout or it's not validity assertion at all, don't touch it
416            None => {}
417            Some(true) => {
418                // If we know the assert panics, indicate to later opts that the call diverges
419                *target = None;
420            }
421            Some(false) => {
422                // If we know the assert does not panic, turn the call into a Goto
423                terminator.kind = TerminatorKind::Goto { target: target_block };
424            }
425        }
426    }
427}
428
429fn intrinsic_assert_panics<'tcx>(
430    tcx: TyCtxt<'tcx>,
431    typing_env: ty::TypingEnv<'tcx>,
432    arg: ty::GenericArg<'tcx>,
433    intrinsic_name: Symbol,
434) -> Option<bool> {
435    let requirement = ValidityRequirement::from_intrinsic(intrinsic_name)?;
436    let ty = arg.expect_ty();
437    Some(!tcx.check_validity_requirement((requirement, typing_env.as_query_input(ty))).ok()?)
438}
439
440fn resolve_rust_intrinsic<'tcx>(
441    tcx: TyCtxt<'tcx>,
442    func_ty: Ty<'tcx>,
443) -> Option<(Symbol, GenericArgsRef<'tcx>)> {
444    let ty::FnDef(def_id, args) = *func_ty.kind() else { return None };
445    let intrinsic = tcx.intrinsic(def_id)?;
446    Some((intrinsic.name, args.no_bound_vars().unwrap()))
447}
448
449struct SimplifyUbCheck<'tcx> {
450    tcx: TyCtxt<'tcx>,
451}
452
453impl<'tcx> MutVisitor<'tcx> for SimplifyUbCheck<'tcx> {
454    fn tcx(&self) -> TyCtxt<'tcx> {
455        self.tcx
456    }
457
458    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
459        if let Operand::RuntimeChecks(RuntimeChecks::UbChecks) = operand {
460            *operand = Operand::Constant(Box::new(ConstOperand {
461                span: rustc_span::DUMMY_SP,
462                user_ty: None,
463                const_: Const::Val(
464                    ConstValue::from_bool(self.tcx.sess.ub_checks()),
465                    self.tcx.types.bool,
466                ),
467            }));
468        }
469    }
470}