rustc_mir_transform/
add_retag.rs

1//! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate.
2//! It has to be run really early, before transformations like inlining, because
3//! introducing these calls *adds* UB -- so, conceptually, this pass is actually part
4//! of MIR building, and only after this pass we think of the program has having the
5//! normal MIR semantics.
6
7use rustc_middle::mir::*;
8use rustc_middle::ty::{self, Ty, TyCtxt};
9
10pub(super) struct AddRetag;
11
12/// Determine whether this type may contain a reference (or box), and thus needs retagging.
13/// We will only recurse `depth` times into Tuples/ADTs to bound the cost of this.
14fn may_contain_reference<'tcx>(ty: Ty<'tcx>, depth: u32, tcx: TyCtxt<'tcx>) -> bool {
15    match ty.kind() {
16        // Primitive types that are not references
17        ty::Bool
18        | ty::Char
19        | ty::Float(_)
20        | ty::Int(_)
21        | ty::Uint(_)
22        | ty::RawPtr(..)
23        | ty::FnPtr(..)
24        | ty::Str
25        | ty::FnDef(..)
26        | ty::Never => false,
27        // References and Boxes (`noalias` sources)
28        ty::Ref(..) => true,
29        ty::Adt(..) if ty.is_box() => true,
30        // Compound types: recurse
31        ty::Array(ty, _) | ty::Slice(ty) => {
32            // This does not branch so we keep the depth the same.
33            may_contain_reference(*ty, depth, tcx)
34        }
35        ty::Tuple(tys) => {
36            depth == 0 || tys.iter().any(|ty| may_contain_reference(ty, depth - 1, tcx))
37        }
38        ty::Adt(adt, args) => {
39            depth == 0
40                || adt.variants().iter().any(|v| {
41                    v.fields.iter().any(|f| may_contain_reference(f.ty(tcx, args), depth - 1, tcx))
42                })
43        }
44        // Conservative fallback
45        _ => true,
46    }
47}
48
49impl<'tcx> crate::MirPass<'tcx> for AddRetag {
50    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
51        sess.opts.unstable_opts.mir_emit_retag
52    }
53
54    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
55        // We need an `AllCallEdges` pass before we can do any work.
56        super::add_call_guards::AllCallEdges.run_pass(tcx, body);
57
58        let basic_blocks = body.basic_blocks.as_mut();
59        let local_decls = &body.local_decls;
60        let needs_retag = |place: &Place<'tcx>| {
61            // We're not really interested in stores to "outside" locations, they are hard to keep
62            // track of anyway.
63            !place.is_indirect_first_projection()
64                && may_contain_reference(place.ty(&*local_decls, tcx).ty, /*depth*/ 3, tcx)
65                && !local_decls[place.local].is_deref_temp()
66        };
67
68        // PART 1
69        // Retag arguments at the beginning of the start block.
70        {
71            // Gather all arguments, skip return value.
72            let places = local_decls.iter_enumerated().skip(1).take(body.arg_count).filter_map(
73                |(local, decl)| {
74                    let place = Place::from(local);
75                    needs_retag(&place).then_some((place, decl.source_info))
76                },
77            );
78
79            // Emit their retags.
80            basic_blocks[START_BLOCK].statements.splice(
81                0..0,
82                places.map(|(place, source_info)| {
83                    Statement::new(
84                        source_info,
85                        StatementKind::Retag(RetagKind::FnEntry, Box::new(place)),
86                    )
87                }),
88            );
89        }
90
91        // PART 2
92        // Retag return values of functions.
93        // We collect the return destinations because we cannot mutate while iterating.
94        let returns = basic_blocks
95            .iter_mut()
96            .filter_map(|block_data| {
97                match block_data.terminator().kind {
98                    TerminatorKind::Call { target: Some(target), destination, .. }
99                        if needs_retag(&destination) =>
100                    {
101                        // Remember the return destination for later
102                        Some((block_data.terminator().source_info, destination, target))
103                    }
104
105                    // `Drop` is also a call, but it doesn't return anything so we are good.
106                    TerminatorKind::Drop { .. } => None,
107                    // Not a block ending in a Call -> ignore.
108                    _ => None,
109                }
110            })
111            .collect::<Vec<_>>();
112        // Now we go over the returns we collected to retag the return values.
113        for (source_info, dest_place, dest_block) in returns {
114            basic_blocks[dest_block].statements.insert(
115                0,
116                Statement::new(
117                    source_info,
118                    StatementKind::Retag(RetagKind::Default, Box::new(dest_place)),
119                ),
120            );
121        }
122
123        // PART 3
124        // Add retag after assignments.
125        for block_data in basic_blocks {
126            // We want to insert statements as we iterate. To this end, we
127            // iterate backwards using indices.
128            for i in (0..block_data.statements.len()).rev() {
129                let (retag_kind, place) = match block_data.statements[i].kind {
130                    // Retag after assignments of reference type.
131                    StatementKind::Assign(box (ref place, ref rvalue)) => {
132                        let add_retag = match rvalue {
133                            // Ptr-creating operations already do their own internal retagging, no
134                            // need to also add a retag statement. *Except* if we are deref'ing a
135                            // Box, because those get desugared to directly working with the inner
136                            // raw pointer! That's relevant for `RawPtr` as Miri otherwise makes it
137                            // a NOP when the original pointer is already raw.
138                            Rvalue::RawPtr(_mutbl, place) => {
139                                // Using `is_box_global` here is a bit sketchy: if this code is
140                                // generic over the allocator, we'll not add a retag! This is a hack
141                                // to make Stacked Borrows compatible with custom allocator code.
142                                // It means the raw pointer inherits the tag of the box, which mostly works
143                                // but can sometimes lead to unexpected aliasing errors.
144                                // Long-term, we'll want to move to an aliasing model where "cast to
145                                // raw pointer" is a complete NOP, and then this will no longer be
146                                // an issue.
147                                if place.is_indirect_first_projection()
148                                    && body.local_decls[place.local].ty.is_box_global(tcx)
149                                {
150                                    Some(RetagKind::Raw)
151                                } else {
152                                    None
153                                }
154                            }
155                            Rvalue::Ref(..) => None,
156                            _ => {
157                                if needs_retag(place) {
158                                    Some(RetagKind::Default)
159                                } else {
160                                    None
161                                }
162                            }
163                        };
164                        if let Some(kind) = add_retag {
165                            (kind, *place)
166                        } else {
167                            continue;
168                        }
169                    }
170                    // Do nothing for the rest
171                    _ => continue,
172                };
173                // Insert a retag after the statement.
174                let source_info = block_data.statements[i].source_info;
175                block_data.statements.insert(
176                    i + 1,
177                    Statement::new(source_info, StatementKind::Retag(retag_kind, Box::new(place))),
178                );
179            }
180        }
181    }
182
183    fn is_required(&self) -> bool {
184        true
185    }
186}