]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/step.rs
4ca865cc8449945ffbbf642515d3ba1c4046f0ac
[rust.git] / src / librustc_mir / interpret / step.rs
1 //! This module contains the `InterpretCx` 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::{EvalResult, Scalar, PointerArithmetic};
8
9 use super::{InterpretCx, 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<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tcx, M> {
39     pub fn run(&mut self) -> EvalResult<'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) -> EvalResult<'tcx, bool> {
48         if self.stack.is_empty() {
49             return Ok(false);
50         }
51
52         let block = self.frame().block;
53         let stmt_id = self.frame().stmt;
54         let mir = self.mir();
55         let basic_block = &mir.basic_blocks()[block];
56
57         let old_frames = self.cur_frame();
58
59         if let Some(stmt) = basic_block.statements.get(stmt_id) {
60             assert_eq!(old_frames, self.cur_frame());
61             self.statement(stmt)?;
62             return Ok(true);
63         }
64
65         M::before_terminator(self)?;
66
67         let terminator = basic_block.terminator();
68         assert_eq!(old_frames, self.cur_frame());
69         self.terminator(terminator)?;
70         Ok(true)
71     }
72
73     fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
74         info!("{:?}", stmt);
75
76         use rustc::mir::StatementKind::*;
77
78         // Some statements (e.g., box) push new stack frames.
79         // We have to record the stack frame number *before* executing the statement.
80         let frame_idx = self.cur_frame();
81         self.tcx.span = stmt.source_info.span;
82         self.memory.tcx.span = stmt.source_info.span;
83
84         match stmt.kind {
85             Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,
86
87             SetDiscriminant {
88                 ref place,
89                 variant_index,
90             } => {
91                 let dest = self.eval_place(place)?;
92                 self.write_discriminant_index(variant_index, dest)?;
93             }
94
95             // Mark locals as alive
96             StorageLive(local) => {
97                 let old_val = self.storage_live(local)?;
98                 self.deallocate_local(old_val)?;
99             }
100
101             // Mark locals as dead
102             StorageDead(local) => {
103                 let old_val = self.storage_dead(local);
104                 self.deallocate_local(old_val)?;
105             }
106
107             // No dynamic semantics attached to `FakeRead`; MIR
108             // interpreter is solely intended for borrowck'ed code.
109             FakeRead(..) => {}
110
111             // Stacked Borrows.
112             Retag(kind, ref place) => {
113                 let dest = self.eval_place(place)?;
114                 M::retag(self, kind, dest)?;
115             }
116
117             // Statements we do not track.
118             AscribeUserType(..) => {}
119
120             // Defined to do nothing. These are added by optimization passes, to avoid changing the
121             // size of MIR constantly.
122             Nop => {}
123
124             InlineAsm { .. } => return err!(InlineAsm),
125         }
126
127         self.stack[frame_idx].stmt += 1;
128         Ok(())
129     }
130
131     /// Evaluate an assignment statement.
132     ///
133     /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
134     /// type writes its results directly into the memory specified by the place.
135     fn eval_rvalue_into_place(
136         &mut self,
137         rvalue: &mir::Rvalue<'tcx>,
138         place: &mir::Place<'tcx>,
139     ) -> EvalResult<'tcx> {
140         let dest = self.eval_place(place)?;
141
142         use rustc::mir::Rvalue::*;
143         match *rvalue {
144             Use(ref operand) => {
145                 // Avoid recomputing the layout
146                 let op = self.eval_operand(operand, Some(dest.layout))?;
147                 self.copy_op(op, dest)?;
148             }
149
150             BinaryOp(bin_op, ref left, ref right) => {
151                 let layout = if binop_left_homogeneous(bin_op) { Some(dest.layout) } else { None };
152                 let left = self.read_immediate(self.eval_operand(left, layout)?)?;
153                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
154                 let right = self.read_immediate(self.eval_operand(right, layout)?)?;
155                 self.binop_ignore_overflow(
156                     bin_op,
157                     left,
158                     right,
159                     dest,
160                 )?;
161             }
162
163             CheckedBinaryOp(bin_op, ref left, ref right) => {
164                 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
165                 let left = self.read_immediate(self.eval_operand(left, None)?)?;
166                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
167                 let right = self.read_immediate(self.eval_operand(right, layout)?)?;
168                 self.binop_with_overflow(
169                     bin_op,
170                     left,
171                     right,
172                     dest,
173                 )?;
174             }
175
176             UnaryOp(un_op, ref operand) => {
177                 // The operand always has the same type as the result.
178                 let val = self.read_immediate(self.eval_operand(operand, Some(dest.layout))?)?;
179                 let val = self.unary_op(un_op, val)?;
180                 self.write_scalar(val, dest)?;
181             }
182
183             Aggregate(ref kind, ref operands) => {
184                 let (dest, active_field_index) = match **kind {
185                     mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
186                         self.write_discriminant_index(variant_index, dest)?;
187                         if adt_def.is_enum() {
188                             (self.place_downcast(dest, variant_index)?, active_field_index)
189                         } else {
190                             (dest, active_field_index)
191                         }
192                     }
193                     _ => (dest, None)
194                 };
195
196                 for (i, operand) in operands.iter().enumerate() {
197                     let op = self.eval_operand(operand, None)?;
198                     // Ignore zero-sized fields.
199                     if !op.layout.is_zst() {
200                         let field_index = active_field_index.unwrap_or(i);
201                         let field_dest = self.place_field(dest, field_index as u64)?;
202                         self.copy_op(op, field_dest)?;
203                     }
204                 }
205             }
206
207             Repeat(ref operand, _) => {
208                 let op = self.eval_operand(operand, None)?;
209                 let dest = self.force_allocation(dest)?;
210                 let length = dest.len(self)?;
211
212                 if length > 0 {
213                     // write the first
214                     let first = self.mplace_field(dest, 0)?;
215                     self.copy_op(op, first.into())?;
216
217                     if length > 1 {
218                         // copy the rest
219                         let (dest, dest_align) = first.to_scalar_ptr_align();
220                         let rest = dest.ptr_offset(first.layout.size, self)?;
221                         self.memory.copy_repeatedly(
222                             dest, dest_align, rest, dest_align, first.layout.size, length - 1, true
223                         )?;
224                     }
225                 }
226             }
227
228             Len(ref place) => {
229                 // FIXME(CTFE): don't allow computing the length of arrays in const eval
230                 let src = self.eval_place(place)?;
231                 let mplace = self.force_allocation(src)?;
232                 let len = mplace.len(self)?;
233                 let size = self.pointer_size();
234                 self.write_scalar(
235                     Scalar::from_uint(len, size),
236                     dest,
237                 )?;
238             }
239
240             Ref(_, _, ref place) => {
241                 let src = self.eval_place(place)?;
242                 let val = self.force_allocation(src)?;
243                 self.write_immediate(val.to_ref(), dest)?;
244             }
245
246             NullaryOp(mir::NullOp::Box, _) => {
247                 M::box_alloc(self, dest)?;
248             }
249
250             NullaryOp(mir::NullOp::SizeOf, ty) => {
251                 let ty = self.monomorphize(ty)?;
252                 let layout = self.layout_of(ty)?;
253                 assert!(!layout.is_unsized(),
254                         "SizeOf nullary MIR operator called for unsized type");
255                 let size = self.pointer_size();
256                 self.write_scalar(
257                     Scalar::from_uint(layout.size.bytes(), size),
258                     dest,
259                 )?;
260             }
261
262             Cast(kind, ref operand, _) => {
263                 let src = self.eval_operand(operand, None)?;
264                 self.cast(src, kind, dest)?;
265             }
266
267             Discriminant(ref place) => {
268                 let op = self.eval_place_to_op(place, None)?;
269                 let discr_val = self.read_discriminant(op)?.0;
270                 let size = dest.layout.size;
271                 self.write_scalar(Scalar::from_uint(discr_val, size), dest)?;
272             }
273         }
274
275         self.dump_place(*dest);
276
277         Ok(())
278     }
279
280     fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
281         info!("{:?}", terminator.kind);
282         self.tcx.span = terminator.source_info.span;
283         self.memory.tcx.span = terminator.source_info.span;
284
285         let old_stack = self.cur_frame();
286         let old_bb = self.frame().block;
287         self.eval_terminator(terminator)?;
288         if !self.stack.is_empty() {
289             // This should change *something*
290             debug_assert!(self.cur_frame() != old_stack || self.frame().block != old_bb);
291             info!("// {:?}", self.frame().block);
292         }
293         Ok(())
294     }
295 }