]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/step.rs
Shrink the size of Rvalue by 16 bytes
[rust.git] / compiler / rustc_mir / src / interpret / step.rs
1 //! This module contains the `InterpCx` methods for executing a single step of the interpreter.
2 //!
3 //! The main entry point is the `step` method.
4
5 use rustc_middle::mir;
6 use rustc_middle::mir::interpret::{InterpResult, Scalar};
7 use rustc_target::abi::LayoutOf;
8
9 use super::{InterpCx, Machine};
10
11 /// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
12 /// same type as the result.
13 #[inline]
14 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
15     use rustc_middle::mir::BinOp::*;
16     match op {
17         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Offset | Shl | Shr => true,
18         Eq | Ne | Lt | Le | Gt | Ge => false,
19     }
20 }
21 /// Classify whether an operator is "right-homogeneous", i.e., the RHS has the
22 /// same type as the LHS.
23 #[inline]
24 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
25     use rustc_middle::mir::BinOp::*;
26     match op {
27         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Eq | Ne | Lt | Le | Gt | Ge => true,
28         Offset | Shl | Shr => false,
29     }
30 }
31
32 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
33     pub fn run(&mut self) -> InterpResult<'tcx> {
34         while self.step()? {}
35         Ok(())
36     }
37
38     /// Returns `true` as long as there are more things to do.
39     ///
40     /// This is used by [priroda](https://github.com/oli-obk/priroda)
41     ///
42     /// This is marked `#inline(always)` to work around adverserial codegen when `opt-level = 3`
43     #[inline(always)]
44     pub fn step(&mut self) -> InterpResult<'tcx, bool> {
45         if self.stack().is_empty() {
46             return Ok(false);
47         }
48
49         let loc = match self.frame().loc {
50             Ok(loc) => loc,
51             Err(_) => {
52                 // We are unwinding and this fn has no cleanup code.
53                 // Just go on unwinding.
54                 trace!("unwinding: skipping frame");
55                 self.pop_stack_frame(/* unwinding */ true)?;
56                 return Ok(true);
57             }
58         };
59         let basic_block = &self.body().basic_blocks()[loc.block];
60
61         let old_frames = self.frame_idx();
62
63         if let Some(stmt) = basic_block.statements.get(loc.statement_index) {
64             assert_eq!(old_frames, self.frame_idx());
65             self.statement(stmt)?;
66             return Ok(true);
67         }
68
69         M::before_terminator(self)?;
70
71         let terminator = basic_block.terminator();
72         assert_eq!(old_frames, self.frame_idx());
73         self.terminator(terminator)?;
74         Ok(true)
75     }
76
77     /// Runs the interpretation logic for the given `mir::Statement` at the current frame and
78     /// statement counter. This also moves the statement counter forward.
79     crate fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
80         info!("{:?}", stmt);
81
82         use rustc_middle::mir::StatementKind::*;
83
84         // Some statements (e.g., box) push new stack frames.
85         // We have to record the stack frame number *before* executing the statement.
86         let frame_idx = self.frame_idx();
87
88         match &stmt.kind {
89             Assign(box (place, rvalue)) => self.eval_rvalue_into_place(rvalue, *place)?,
90
91             SetDiscriminant { place, variant_index } => {
92                 let dest = self.eval_place(**place)?;
93                 self.write_discriminant(*variant_index, &dest)?;
94             }
95
96             // Mark locals as alive
97             StorageLive(local) => {
98                 self.storage_live(*local)?;
99             }
100
101             // Mark locals as dead
102             StorageDead(local) => {
103                 self.storage_dead(*local)?;
104             }
105
106             // No dynamic semantics attached to `FakeRead`; MIR
107             // interpreter is solely intended for borrowck'ed code.
108             FakeRead(..) => {}
109
110             // Stacked Borrows.
111             Retag(kind, place) => {
112                 let dest = self.eval_place(**place)?;
113                 M::retag(self, *kind, &dest)?;
114             }
115
116             // Statements we do not track.
117             AscribeUserType(..) => {}
118
119             // Currently, Miri discards Coverage statements. Coverage statements are only injected
120             // via an optional compile time MIR pass and have no side effects. Since Coverage
121             // statements don't exist at the source level, it is safe for Miri to ignore them, even
122             // for undefined behavior (UB) checks.
123             //
124             // A coverage counter inside a const expression (for example, a counter injected in a
125             // const function) is discarded when the const is evaluated at compile time. Whether
126             // this should change, and/or how to implement a const eval counter, is a subject of the
127             // following issue:
128             //
129             // FIXME(#73156): Handle source code coverage in const eval
130             Coverage(..) => {}
131
132             // Defined to do nothing. These are added by optimization passes, to avoid changing the
133             // size of MIR constantly.
134             Nop => {}
135
136             LlvmInlineAsm { .. } => throw_unsup_format!("inline assembly is not supported"),
137         }
138
139         self.stack_mut()[frame_idx].loc.as_mut().unwrap().statement_index += 1;
140         Ok(())
141     }
142
143     /// Evaluate an assignment statement.
144     ///
145     /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
146     /// type writes its results directly into the memory specified by the place.
147     pub fn eval_rvalue_into_place(
148         &mut self,
149         rvalue: &mir::Rvalue<'tcx>,
150         place: mir::Place<'tcx>,
151     ) -> InterpResult<'tcx> {
152         let dest = self.eval_place(place)?;
153
154         use rustc_middle::mir::Rvalue::*;
155         match *rvalue {
156             ThreadLocalRef(did) => {
157                 let id = M::thread_local_static_alloc_id(self, did)?;
158                 let val = self.global_base_pointer(id.into())?;
159                 self.write_scalar(val, &dest)?;
160             }
161
162             Use(ref operand) => {
163                 // Avoid recomputing the layout
164                 let op = self.eval_operand(operand, Some(dest.layout))?;
165                 self.copy_op(&op, &dest)?;
166             }
167
168             BinaryOp(bin_op, box (ref left, ref right)) => {
169                 let layout = binop_left_homogeneous(bin_op).then_some(dest.layout);
170                 let left = self.read_immediate(&self.eval_operand(left, layout)?)?;
171                 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
172                 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
173                 self.binop_ignore_overflow(bin_op, &left, &right, &dest)?;
174             }
175
176             CheckedBinaryOp(bin_op, box (ref left, ref right)) => {
177                 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
178                 let left = self.read_immediate(&self.eval_operand(left, None)?)?;
179                 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
180                 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
181                 self.binop_with_overflow(bin_op, &left, &right, &dest)?;
182             }
183
184             UnaryOp(un_op, ref operand) => {
185                 // The operand always has the same type as the result.
186                 let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?;
187                 let val = self.unary_op(un_op, &val)?;
188                 assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op);
189                 self.write_immediate(*val, &dest)?;
190             }
191
192             Aggregate(ref kind, ref operands) => {
193                 let (dest, active_field_index) = match **kind {
194                     mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
195                         self.write_discriminant(variant_index, &dest)?;
196                         if adt_def.is_enum() {
197                             (self.place_downcast(&dest, variant_index)?, active_field_index)
198                         } else {
199                             (dest, active_field_index)
200                         }
201                     }
202                     _ => (dest, None),
203                 };
204
205                 for (i, operand) in operands.iter().enumerate() {
206                     let op = self.eval_operand(operand, None)?;
207                     // Ignore zero-sized fields.
208                     if !op.layout.is_zst() {
209                         let field_index = active_field_index.unwrap_or(i);
210                         let field_dest = self.place_field(&dest, field_index)?;
211                         self.copy_op(&op, &field_dest)?;
212                     }
213                 }
214             }
215
216             Repeat(ref operand, _) => {
217                 let op = self.eval_operand(operand, None)?;
218                 let dest = self.force_allocation(&dest)?;
219                 let length = dest.len(self)?;
220
221                 if let Some(first_ptr) = self.check_mplace_access(&dest, None)? {
222                     // Write the first.
223                     let first = self.mplace_field(&dest, 0)?;
224                     self.copy_op(&op, &first.into())?;
225
226                     if length > 1 {
227                         let elem_size = first.layout.size;
228                         // Copy the rest. This is performance-sensitive code
229                         // for big static/const arrays!
230                         let rest_ptr = first_ptr.offset(elem_size, self)?;
231                         self.memory.copy_repeatedly(
232                             first_ptr,
233                             rest_ptr,
234                             elem_size,
235                             length - 1,
236                             /*nonoverlapping:*/ true,
237                         )?;
238                     }
239                 }
240             }
241
242             Len(place) => {
243                 // FIXME(CTFE): don't allow computing the length of arrays in const eval
244                 let src = self.eval_place(place)?;
245                 let mplace = self.force_allocation(&src)?;
246                 let len = mplace.len(self)?;
247                 self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
248             }
249
250             AddressOf(_, place) | Ref(_, _, place) => {
251                 let src = self.eval_place(place)?;
252                 let place = self.force_allocation(&src)?;
253                 if place.layout.size.bytes() > 0 {
254                     // definitely not a ZST
255                     assert!(place.ptr.is_ptr(), "non-ZST places should be normalized to `Pointer`");
256                 }
257                 self.write_immediate(place.to_ref(), &dest)?;
258             }
259
260             NullaryOp(mir::NullOp::Box, _) => {
261                 M::box_alloc(self, &dest)?;
262             }
263
264             NullaryOp(mir::NullOp::SizeOf, ty) => {
265                 let ty = self.subst_from_current_frame_and_normalize_erasing_regions(ty);
266                 let layout = self.layout_of(ty)?;
267                 if layout.is_unsized() {
268                     // FIXME: This should be a span_bug (#80742)
269                     self.tcx.sess.delay_span_bug(
270                         self.frame().current_span(),
271                         &format!("SizeOf nullary MIR operator called for unsized type {}", ty),
272                     );
273                     throw_inval!(SizeOfUnsizedType(ty));
274                 }
275                 self.write_scalar(Scalar::from_machine_usize(layout.size.bytes(), self), &dest)?;
276             }
277
278             Cast(cast_kind, ref operand, cast_ty) => {
279                 let src = self.eval_operand(operand, None)?;
280                 let cast_ty = self.subst_from_current_frame_and_normalize_erasing_regions(cast_ty);
281                 self.cast(&src, cast_kind, cast_ty, &dest)?;
282             }
283
284             Discriminant(place) => {
285                 let op = self.eval_place_to_op(place, None)?;
286                 let discr_val = self.read_discriminant(&op)?.0;
287                 self.write_scalar(discr_val, &dest)?;
288             }
289         }
290
291         trace!("{:?}", self.dump_place(*dest));
292
293         Ok(())
294     }
295
296     fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> {
297         info!("{:?}", terminator.kind);
298
299         self.eval_terminator(terminator)?;
300         if !self.stack().is_empty() {
301             if let Ok(loc) = self.frame().loc {
302                 info!("// executing {:?}", loc.block);
303             }
304         }
305         Ok(())
306     }
307 }