rustc_mir_transform/
deduce_param_attrs.rs

1//! Deduces supplementary parameter attributes from MIR.
2//!
3//! Deduced parameter attributes are those that can only be soundly determined by examining the
4//! body of the function instead of just the signature. These can be useful for optimization
5//! purposes on a best-effort basis. We compute them here and store them into the crate metadata so
6//! dependent crates can use them.
7
8use rustc_hir::def_id::LocalDefId;
9use rustc_index::bit_set::DenseBitSet;
10use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
11use rustc_middle::mir::{Body, Location, Operand, Place, RETURN_PLACE, Terminator, TerminatorKind};
12use rustc_middle::ty::{self, DeducedParamAttrs, Ty, TyCtxt};
13use rustc_session::config::OptLevel;
14
15/// A visitor that determines which arguments have been mutated. We can't use the mutability field
16/// on LocalDecl for this because it has no meaning post-optimization.
17struct DeduceReadOnly {
18    /// Each bit is indexed by argument number, starting at zero (so 0 corresponds to local decl
19    /// 1). The bit is true if the argument may have been mutated or false if we know it hasn't
20    /// been up to the point we're at.
21    mutable_args: DenseBitSet<usize>,
22}
23
24impl DeduceReadOnly {
25    /// Returns a new DeduceReadOnly instance.
26    fn new(arg_count: usize) -> Self {
27        Self { mutable_args: DenseBitSet::new_empty(arg_count) }
28    }
29}
30
31impl<'tcx> Visitor<'tcx> for DeduceReadOnly {
32    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
33        // We're only interested in arguments.
34        if place.local == RETURN_PLACE || place.local.index() > self.mutable_args.domain_size() {
35            return;
36        }
37
38        let mark_as_mutable = match context {
39            PlaceContext::MutatingUse(..) => {
40                // This is a mutation, so mark it as such.
41                true
42            }
43            PlaceContext::NonMutatingUse(NonMutatingUseContext::RawBorrow) => {
44                // Whether mutating though a `&raw const` is allowed is still undecided, so we
45                // disable any sketchy `readonly` optimizations for now. But we only need to do
46                // this if the pointer would point into the argument. IOW: for indirect places,
47                // like `&raw (*local).field`, this surely cannot mutate `local`.
48                !place.is_indirect()
49            }
50            PlaceContext::NonMutatingUse(..) | PlaceContext::NonUse(..) => {
51                // Not mutating, so it's fine.
52                false
53            }
54        };
55
56        if mark_as_mutable {
57            self.mutable_args.insert(place.local.index() - 1);
58        }
59    }
60
61    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
62        // OK, this is subtle. Suppose that we're trying to deduce whether `x` in `f` is read-only
63        // and we have the following:
64        //
65        //     fn f(x: BigStruct) { g(x) }
66        //     fn g(mut y: BigStruct) { y.foo = 1 }
67        //
68        // If, at the generated MIR level, `f` turned into something like:
69        //
70        //      fn f(_1: BigStruct) -> () {
71        //          let mut _0: ();
72        //          bb0: {
73        //              _0 = g(move _1) -> bb1;
74        //          }
75        //          ...
76        //      }
77        //
78        // then it would be incorrect to mark `x` (i.e. `_1`) as `readonly`, because `g`'s write to
79        // its copy of the indirect parameter would actually be a write directly to the pointer that
80        // `f` passes. Note that function arguments are the only situation in which this problem can
81        // arise: every other use of `move` in MIR doesn't actually write to the value it moves
82        // from.
83        if let TerminatorKind::Call { ref args, .. } = terminator.kind {
84            for arg in args {
85                if let Operand::Move(place) = arg.node {
86                    let local = place.local;
87                    if place.is_indirect()
88                        || local == RETURN_PLACE
89                        || local.index() > self.mutable_args.domain_size()
90                    {
91                        continue;
92                    }
93
94                    self.mutable_args.insert(local.index() - 1);
95                }
96            }
97        };
98
99        self.super_terminator(terminator, location);
100    }
101}
102
103/// Returns true if values of a given type will never be passed indirectly, regardless of ABI.
104fn type_will_always_be_passed_directly(ty: Ty<'_>) -> bool {
105    matches!(
106        ty.kind(),
107        ty::Bool
108            | ty::Char
109            | ty::Float(..)
110            | ty::Int(..)
111            | ty::RawPtr(..)
112            | ty::Ref(..)
113            | ty::Slice(..)
114            | ty::Uint(..)
115    )
116}
117
118/// Returns the deduced parameter attributes for a function.
119///
120/// Deduced parameter attributes are those that can only be soundly determined by examining the
121/// body of the function instead of just the signature. These can be useful for optimization
122/// purposes on a best-effort basis. We compute them here and store them into the crate metadata so
123/// dependent crates can use them.
124pub(super) fn deduced_param_attrs<'tcx>(
125    tcx: TyCtxt<'tcx>,
126    def_id: LocalDefId,
127) -> &'tcx [DeducedParamAttrs] {
128    // This computation is unfortunately rather expensive, so don't do it unless we're optimizing.
129    // Also skip it in incremental mode.
130    if tcx.sess.opts.optimize == OptLevel::No || tcx.sess.opts.incremental.is_some() {
131        return &[];
132    }
133
134    // If the Freeze lang item isn't present, then don't bother.
135    if tcx.lang_items().freeze_trait().is_none() {
136        return &[];
137    }
138
139    // Codegen won't use this information for anything if all the function parameters are passed
140    // directly. Detect that and bail, for compilation speed.
141    let fn_ty = tcx.type_of(def_id).instantiate_identity();
142    if matches!(fn_ty.kind(), ty::FnDef(..))
143        && fn_ty
144            .fn_sig(tcx)
145            .inputs()
146            .skip_binder()
147            .iter()
148            .cloned()
149            .all(type_will_always_be_passed_directly)
150    {
151        return &[];
152    }
153
154    // Don't deduce any attributes for functions that have no MIR.
155    if !tcx.is_mir_available(def_id) {
156        return &[];
157    }
158
159    // Grab the optimized MIR. Analyze it to determine which arguments have been mutated.
160    let body: &Body<'tcx> = tcx.optimized_mir(def_id);
161    let mut deduce_read_only = DeduceReadOnly::new(body.arg_count);
162    deduce_read_only.visit_body(body);
163
164    // Set the `readonly` attribute for every argument that we concluded is immutable and that
165    // contains no UnsafeCells.
166    //
167    // FIXME: This is overly conservative around generic parameters: `is_freeze()` will always
168    // return false for them. For a description of alternatives that could do a better job here,
169    // see [1].
170    //
171    // [1]: https://github.com/rust-lang/rust/pull/103172#discussion_r999139997
172    let typing_env = body.typing_env(tcx);
173    let mut deduced_param_attrs = tcx.arena.alloc_from_iter(
174        body.local_decls.iter().skip(1).take(body.arg_count).enumerate().map(
175            |(arg_index, local_decl)| DeducedParamAttrs {
176                read_only: !deduce_read_only.mutable_args.contains(arg_index)
177                    // We must normalize here to reveal opaques and normalize
178                    // their generic parameters, otherwise we'll see exponential
179                    // blow-up in compile times: #113372
180                    && tcx
181                        .normalize_erasing_regions(typing_env, local_decl.ty)
182                        .is_freeze(tcx, typing_env),
183            },
184        ),
185    );
186
187    // Trailing parameters past the size of the `deduced_param_attrs` array are assumed to have the
188    // default set of attributes, so we don't have to store them explicitly. Pop them off to save a
189    // few bytes in metadata.
190    while deduced_param_attrs.last() == Some(&DeducedParamAttrs::default()) {
191        let last_index = deduced_param_attrs.len() - 1;
192        deduced_param_attrs = &mut deduced_param_attrs[0..last_index];
193    }
194
195    deduced_param_attrs
196}