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