1 use std::borrow::Borrow;
4 use rustc_span::symbol::sym;
6 use rustc_target::spec::abi::Abi;
8 use rustc_index::bit_set::BitSet;
9 use rustc_middle::mir::MirPass;
10 use rustc_middle::mir::{self, Body, Local, Location};
11 use rustc_middle::ty::{self, Ty, TyCtxt};
14 DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeLiveLocals, MaybeUninitializedPlaces,
16 use crate::move_paths::{HasMoveData, MoveData};
17 use crate::move_paths::{LookupResult, MovePathIndex};
18 use crate::MoveDataParamEnv;
19 use crate::{Analysis, JoinSemiLattice, Results, ResultsCursor};
21 pub struct SanityCheck;
23 // FIXME: This should be a `MirLint`, but it needs to be moved back to `rustc_mir_transform` first.
24 impl<'tcx> MirPass<'tcx> for SanityCheck {
25 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
26 use crate::has_rustc_mir_with;
27 let def_id = body.source.def_id();
28 if !tcx.has_attr(def_id, sym::rustc_mir) {
29 debug!("skipping rustc_peek::SanityCheck on {}", tcx.def_path_str(def_id));
32 debug!("running rustc_peek::SanityCheck on {}", tcx.def_path_str(def_id));
35 let attributes = tcx.get_attrs(def_id);
36 let param_env = tcx.param_env(def_id);
37 let move_data = MoveData::gather_moves(body, tcx, param_env).unwrap();
38 let mdpe = MoveDataParamEnv { move_data, param_env };
41 if has_rustc_mir_with(sess, &attributes, sym::rustc_peek_maybe_init).is_some() {
42 let flow_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe)
43 .into_engine(tcx, body)
44 .iterate_to_fixpoint();
46 sanity_check_via_rustc_peek(tcx, body, &attributes, &flow_inits);
49 if has_rustc_mir_with(sess, &attributes, sym::rustc_peek_maybe_uninit).is_some() {
50 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
51 .into_engine(tcx, body)
52 .iterate_to_fixpoint();
54 sanity_check_via_rustc_peek(tcx, body, &attributes, &flow_uninits);
57 if has_rustc_mir_with(sess, &attributes, sym::rustc_peek_definite_init).is_some() {
58 let flow_def_inits = DefinitelyInitializedPlaces::new(tcx, body, &mdpe)
59 .into_engine(tcx, body)
60 .iterate_to_fixpoint();
62 sanity_check_via_rustc_peek(tcx, body, &attributes, &flow_def_inits);
65 if has_rustc_mir_with(sess, &attributes, sym::rustc_peek_liveness).is_some() {
66 let flow_liveness = MaybeLiveLocals.into_engine(tcx, body).iterate_to_fixpoint();
68 sanity_check_via_rustc_peek(tcx, body, &attributes, &flow_liveness);
71 if has_rustc_mir_with(sess, &attributes, sym::stop_after_dataflow).is_some() {
72 tcx.sess.fatal("stop_after_dataflow ended compilation");
77 /// This function scans `mir` for all calls to the intrinsic
78 /// `rustc_peek` that have the expression form `rustc_peek(&expr)`.
80 /// For each such call, determines what the dataflow bit-state is for
81 /// the L-value corresponding to `expr`; if the bit-state is a 1, then
82 /// that call to `rustc_peek` is ignored by the sanity check. If the
83 /// bit-state is a 0, then this pass emits an error message saying
84 /// "rustc_peek: bit not set".
86 /// The intention is that one can write unit tests for dataflow by
87 /// putting code into a UI test and using `rustc_peek` to
88 /// make observations about the results of dataflow static analyses.
90 /// (If there are any calls to `rustc_peek` that do not match the
91 /// expression form above, then that emits an error as well, but those
92 /// errors are not intended to be used for unit tests.)
93 pub fn sanity_check_via_rustc_peek<'tcx, A>(
96 _attributes: &[ast::Attribute],
97 results: &Results<'tcx, A>,
101 let def_id = body.source.def_id();
102 debug!("sanity_check_via_rustc_peek def_id: {:?}", def_id);
104 let mut cursor = ResultsCursor::new(body, results);
106 let peek_calls = body.basic_blocks().iter_enumerated().filter_map(|(bb, block_data)| {
107 PeekCall::from_terminator(tcx, block_data.terminator()).map(|call| (bb, block_data, call))
110 for (bb, block_data, call) in peek_calls {
111 // Look for a sequence like the following to indicate that we should be peeking at `_1`:
119 let (statement_index, peek_rval) = block_data
123 .find_map(|(i, stmt)| value_assigned_to_local(stmt, call.arg).map(|rval| (i, rval)))
125 "call to rustc_peek should be preceded by \
126 assignment to temporary holding its argument",
129 match (call.kind, peek_rval) {
130 (PeekCallKind::ByRef, mir::Rvalue::Ref(_, _, place))
133 mir::Rvalue::Use(mir::Operand::Move(place) | mir::Operand::Copy(place)),
135 let loc = Location { block: bb, statement_index };
136 cursor.seek_before_primary_effect(loc);
137 let state = cursor.get();
138 results.analysis.peek_at(tcx, *place, state, call);
142 let msg = "rustc_peek: argument expression \
143 must be either `place` or `&place`";
144 tcx.sess.span_err(call.span, msg);
150 /// If `stmt` is an assignment where the LHS is the given local (with no projections), returns the
151 /// RHS of the assignment.
152 fn value_assigned_to_local<'a, 'tcx>(
153 stmt: &'a mir::Statement<'tcx>,
155 ) -> Option<&'a mir::Rvalue<'tcx>> {
156 if let mir::StatementKind::Assign(box (place, rvalue)) = &stmt.kind {
157 if let Some(l) = place.as_local() {
159 return Some(&*rvalue);
167 #[derive(Clone, Copy, Debug)]
174 fn from_arg_ty(arg: Ty<'_>) -> Self {
176 ty::Ref(_, _, _) => PeekCallKind::ByRef,
177 _ => PeekCallKind::ByVal,
182 #[derive(Clone, Copy, Debug)]
183 pub struct PeekCall {
190 fn from_terminator<'tcx>(
192 terminator: &mir::Terminator<'tcx>,
196 let span = terminator.source_info.span;
197 if let mir::TerminatorKind::Call { func: Operand::Constant(func), args, .. } =
200 if let ty::FnDef(def_id, substs) = *func.literal.ty().kind() {
201 let sig = tcx.fn_sig(def_id);
202 let name = tcx.item_name(def_id);
203 if sig.abi() != Abi::RustIntrinsic || name != sym::rustc_peek {
207 assert_eq!(args.len(), 1);
208 let kind = PeekCallKind::from_arg_ty(substs.type_at(0));
209 let arg = match &args[0] {
210 Operand::Copy(place) | Operand::Move(place) => {
211 if let Some(local) = place.as_local() {
214 tcx.sess.diagnostic().span_err(
216 "dataflow::sanity_check cannot feed a non-temp to rustc_peek.",
222 tcx.sess.diagnostic().span_err(
224 "dataflow::sanity_check cannot feed a non-temp to rustc_peek.",
230 return Some(PeekCall { arg, kind, span });
238 pub trait RustcPeekAt<'tcx>: Analysis<'tcx> {
242 place: mir::Place<'tcx>,
243 flow_state: &Self::Domain,
248 impl<'tcx, A, D> RustcPeekAt<'tcx> for A
250 A: Analysis<'tcx, Domain = D> + HasMoveData<'tcx>,
251 D: JoinSemiLattice + Clone + Borrow<BitSet<MovePathIndex>>,
256 place: mir::Place<'tcx>,
257 flow_state: &Self::Domain,
260 match self.move_data().rev_lookup.find(place.as_ref()) {
261 LookupResult::Exact(peek_mpi) => {
262 let bit_state = flow_state.borrow().contains(peek_mpi);
263 debug!("rustc_peek({:?} = &{:?}) bit_state: {}", call.arg, place, bit_state);
265 tcx.sess.span_err(call.span, "rustc_peek: bit not set");
269 LookupResult::Parent(..) => {
270 tcx.sess.span_err(call.span, "rustc_peek: argument untracked");
276 impl<'tcx> RustcPeekAt<'tcx> for MaybeLiveLocals {
280 place: mir::Place<'tcx>,
281 flow_state: &BitSet<Local>,
284 info!(?place, "peek_at");
285 let Some(local) = place.as_local() else {
286 tcx.sess.span_err(call.span, "rustc_peek: argument was not a local");
290 if !flow_state.contains(local) {
291 tcx.sess.span_err(call.span, "rustc_peek: bit not set");