]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/step.rs
d5e87154480256b99a521da1df89a81c1f163ab0
[rust.git] / src / librustc_mir / interpret / step.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This module contains the `EvalContext` methods for executing a single step of the interpreter.
12 //!
13 //! The main entry point is the `step` method.
14
15 use rustc::mir;
16 use rustc::ty::layout::LayoutOf;
17 use rustc::mir::interpret::{EvalResult, Scalar, PointerArithmetic};
18
19 use super::{EvalContext, Machine};
20
21 /// Classify whether an operator is "left-homogeneous", i.e. the LHS has the
22 /// same type as the result.
23 #[inline]
24 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
25     use rustc::mir::BinOp::*;
26     match op {
27         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
28         Offset | Shl | Shr =>
29             true,
30         Eq | Ne | Lt | Le | Gt | Ge =>
31             false,
32     }
33 }
34 /// Classify whether an operator is "right-homogeneous", i.e. the RHS has the
35 /// same type as the LHS.
36 #[inline]
37 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
38     use rustc::mir::BinOp::*;
39     match op {
40         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
41         Eq | Ne | Lt | Le | Gt | Ge =>
42             true,
43         Offset | Shl | Shr =>
44             false,
45     }
46 }
47
48 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
49     pub fn run(&mut self) -> EvalResult<'tcx> {
50         while self.step()? {}
51         Ok(())
52     }
53
54     /// Returns true as long as there are more things to do.
55     fn step(&mut self) -> EvalResult<'tcx, bool> {
56         if self.stack.is_empty() {
57             return Ok(false);
58         }
59
60         let block = self.frame().block;
61         let stmt_id = self.frame().stmt;
62         let mir = self.mir();
63         let basic_block = &mir.basic_blocks()[block];
64
65         let old_frames = self.cur_frame();
66
67         if let Some(stmt) = basic_block.statements.get(stmt_id) {
68             assert_eq!(old_frames, self.cur_frame());
69             self.statement(stmt)?;
70             return Ok(true);
71         }
72
73         M::before_terminator(self)?;
74
75         let terminator = basic_block.terminator();
76         assert_eq!(old_frames, self.cur_frame());
77         self.terminator(terminator)?;
78         Ok(true)
79     }
80
81     fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
82         debug!("{:?}", stmt);
83
84         use rustc::mir::StatementKind::*;
85
86         // Some statements (e.g. box) push new stack frames.
87         // We have to record the stack frame number *before* executing the statement.
88         let frame_idx = self.cur_frame();
89         self.tcx.span = stmt.source_info.span;
90         self.memory.tcx.span = stmt.source_info.span;
91
92         match stmt.kind {
93             Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,
94
95             SetDiscriminant {
96                 ref place,
97                 variant_index,
98             } => {
99                 let dest = self.eval_place(place)?;
100                 self.write_discriminant_index(variant_index, dest)?;
101             }
102
103             // Mark locals as alive
104             StorageLive(local) => {
105                 let old_val = self.storage_live(local)?;
106                 self.deallocate_local(old_val)?;
107             }
108
109             // Mark locals as dead
110             StorageDead(local) => {
111                 let old_val = self.storage_dead(local);
112                 self.deallocate_local(old_val)?;
113             }
114
115             // No dynamic semantics attached to `FakeRead`; MIR
116             // interpreter is solely intended for borrowck'ed code.
117             FakeRead(..) => {}
118
119             // Validity checks.
120             Validate(op, ref places) => {
121                 for operand in places {
122                     M::validation_op(self, op, operand)?;
123                 }
124             }
125
126             EndRegion(..) => {}
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 { .. } => return err!(InlineAsm),
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     fn eval_rvalue_into_place(
145         &mut self,
146         rvalue: &mir::Rvalue<'tcx>,
147         place: &mir::Place<'tcx>,
148     ) -> EvalResult<'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 = if binop_left_homogeneous(bin_op) { Some(dest.layout) } else { None };
161                 let left = self.read_value(self.eval_operand(left, layout)?)?;
162                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
163                 let right = self.read_value(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_value(self.eval_operand(left, None)?)?;
175                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
176                 let right = self.read_value(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_value(self.eval_operand(operand, Some(dest.layout))?)?;
188                 let val = self.unary_op(un_op, val.to_scalar()?, dest.layout)?;
189                 self.write_scalar(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_index(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 as u64)?;
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 length > 0 {
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                         // copy the rest
228                         let (dest, dest_align) = first.to_scalar_ptr_align();
229                         let rest = dest.ptr_offset(first.layout.size, &self)?;
230                         self.memory.copy_repeatedly(
231                             dest, dest_align, rest, dest_align, first.layout.size, length - 1, true
232                         )?;
233                     }
234                 }
235             }
236
237             Len(ref place) => {
238                 // FIXME(CTFE): don't allow computing the length of arrays in const eval
239                 let src = self.eval_place(place)?;
240                 let mplace = self.force_allocation(src)?;
241                 let len = mplace.len(&self)?;
242                 let size = self.pointer_size();
243                 self.write_scalar(
244                     Scalar::from_uint(len, size),
245                     dest,
246                 )?;
247             }
248
249             Ref(_, _, ref place) => {
250                 let src = self.eval_place(place)?;
251                 let val = self.force_allocation(src)?.to_ref();
252                 self.write_value(val, dest)?;
253             }
254
255             NullaryOp(mir::NullOp::Box, _) => {
256                 M::box_alloc(self, dest)?;
257             }
258
259             NullaryOp(mir::NullOp::SizeOf, ty) => {
260                 let ty = self.monomorphize(ty, self.substs());
261                 let layout = self.layout_of(ty)?;
262                 assert!(!layout.is_unsized(),
263                         "SizeOf nullary MIR operator called for unsized type");
264                 let size = self.pointer_size();
265                 self.write_scalar(
266                     Scalar::from_uint(layout.size.bytes(), size),
267                     dest,
268                 )?;
269             }
270
271             Cast(kind, ref operand, cast_ty) => {
272                 debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest.layout.ty);
273                 let src = self.eval_operand(operand, None)?;
274                 self.cast(src, kind, dest)?;
275             }
276
277             Discriminant(ref place) => {
278                 let place = self.eval_place(place)?;
279                 let discr_val = self.read_discriminant(self.place_to_op(place)?)?.0;
280                 let size = dest.layout.size;
281                 self.write_scalar(Scalar::from_uint(discr_val, size), dest)?;
282             }
283         }
284
285         self.dump_place(*dest);
286
287         Ok(())
288     }
289
290     fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
291         debug!("{:?}", terminator.kind);
292         self.tcx.span = terminator.source_info.span;
293         self.memory.tcx.span = terminator.source_info.span;
294
295         let old_stack = self.cur_frame();
296         let old_bb = self.frame().block;
297         self.eval_terminator(terminator)?;
298         if !self.stack.is_empty() {
299             // This should change *something*
300             debug_assert!(self.cur_frame() != old_stack || self.frame().block != old_bb);
301             debug!("// {:?}", self.frame().block);
302         }
303         Ok(())
304     }
305 }