/
step.rs
348 lines (322 loc) · 12.5 KB
/
step.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//! This module contains the `EvalContext` methods for executing a single step of the interpreter.
//!
//! The main entry point is the `step` method.
use hir;
use mir::visit::{Visitor, PlaceContext};
use mir;
use ty::{self, Instance};
use ty::layout::LayoutOf;
use middle::const_val::ConstVal;
use super::{EvalResult, EvalContext, StackPopCleanup, PtrAndAlign, GlobalId, Place,
Machine, EvalErrorKind};
use syntax::codemap::Span;
use syntax::ast::Mutability;
impl<'a, 'tcx, M: Machine<'tcx>> EvalContext<'a, 'tcx, M> {
pub fn inc_step_counter_and_check_limit(&mut self, n: u64) -> EvalResult<'tcx> {
self.steps_remaining = self.steps_remaining.saturating_sub(n);
if self.steps_remaining > 0 {
Ok(())
} else {
err!(ExecutionTimeLimitReached)
}
}
/// Returns true as long as there are more things to do.
pub fn step(&mut self) -> EvalResult<'tcx, bool> {
self.inc_step_counter_and_check_limit(1)?;
if self.stack.is_empty() {
return Ok(false);
}
let block = self.frame().block;
let stmt_id = self.frame().stmt;
let mir = self.mir();
let basic_block = &mir.basic_blocks()[block];
let old_frames = self.cur_frame();
if let Some(stmt) = basic_block.statements.get(stmt_id) {
let mut new = Ok(false);
ConstantExtractor {
span: stmt.source_info.span,
instance: self.frame().instance,
ecx: self,
mir,
new_constant: &mut new,
}.visit_statement(
block,
stmt,
mir::Location {
block,
statement_index: stmt_id,
},
);
// if ConstantExtractor added a new frame, we don't execute anything here
// but await the next call to step
if !new? {
assert_eq!(old_frames, self.cur_frame());
self.statement(stmt)?;
}
return Ok(true);
}
let terminator = basic_block.terminator();
let mut new = Ok(false);
ConstantExtractor {
span: terminator.source_info.span,
instance: self.frame().instance,
ecx: self,
mir,
new_constant: &mut new,
}.visit_terminator(
block,
terminator,
mir::Location {
block,
statement_index: stmt_id,
},
);
// if ConstantExtractor added a new frame, we don't execute anything here
// but await the next call to step
if !new? {
assert_eq!(old_frames, self.cur_frame());
self.terminator(terminator)?;
}
Ok(true)
}
fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
trace!("{:?}", stmt);
use mir::StatementKind::*;
// Some statements (e.g. box) push new stack frames. We have to record the stack frame number
// *before* executing the statement.
let frame_idx = self.cur_frame();
match stmt.kind {
Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,
SetDiscriminant {
ref place,
variant_index,
} => {
let dest = self.eval_place(place)?;
let dest_ty = self.place_ty(place);
self.write_discriminant_value(dest_ty, dest, variant_index)?;
}
// Mark locals as alive
StorageLive(local) => {
let old_val = self.frame_mut().storage_live(local)?;
self.deallocate_local(old_val)?;
}
// Mark locals as dead
StorageDead(local) => {
let old_val = self.frame_mut().storage_dead(local)?;
self.deallocate_local(old_val)?;
}
// Validity checks.
Validate(op, ref places) => {
for operand in places {
self.validation_op(op, operand)?;
}
}
EndRegion(ce) => {
self.end_region(Some(ce))?;
}
// Defined to do nothing. These are added by optimization passes, to avoid changing the
// size of MIR constantly.
Nop => {}
InlineAsm { .. } => return err!(InlineAsm),
}
self.stack[frame_idx].stmt += 1;
Ok(())
}
fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
trace!("{:?}", terminator.kind);
self.eval_terminator(terminator)?;
if !self.stack.is_empty() {
trace!("// {:?}", self.frame().block);
}
Ok(())
}
/// returns `true` if a stackframe was pushed
fn global_item(
&mut self,
instance: Instance<'tcx>,
span: Span,
mutability: Mutability,
) -> EvalResult<'tcx, bool> {
debug!("global_item: {:?}", instance);
let cid = GlobalId {
instance,
promoted: None,
};
if self.tcx.interpret_interner.borrow().get_cached(cid).is_some() {
return Ok(false);
}
if self.tcx.has_attr(instance.def_id(), "linkage") {
M::global_item_with_linkage(self, cid.instance, mutability)?;
return Ok(false);
}
// FIXME(eddyb) use `Instance::ty` when it becomes available.
let instance_ty =
self.monomorphize(instance.def.def_ty(self.tcx), instance.substs);
let layout = self.layout_of(instance_ty)?;
assert!(!layout.is_unsized());
let ptr = self.memory.allocate(
layout.size.bytes(),
layout.align.abi(),
None,
)?;
self.tcx.interpret_interner.borrow_mut().cache(
cid,
PtrAndAlign {
ptr: ptr.into(),
aligned: !layout.is_packed(),
},
);
let internally_mutable = !layout.ty.is_freeze(self.tcx, self.param_env, span);
let mutability = if mutability == Mutability::Mutable || internally_mutable {
Mutability::Mutable
} else {
Mutability::Immutable
};
let cleanup = StackPopCleanup::MarkStatic(mutability);
let name = ty::tls::with(|tcx| tcx.item_path_str(instance.def_id()));
trace!("pushing stack frame for global: {}", name);
let mir = self.load_mir(instance.def)?;
self.push_stack_frame(
instance,
span,
mir,
Place::from_ptr(ptr),
cleanup,
)?;
Ok(true)
}
}
struct ConstantExtractor<'a, 'b: 'a, 'tcx: 'b, M: Machine<'tcx> + 'a> {
span: Span,
ecx: &'a mut EvalContext<'b, 'tcx, M>,
mir: &'tcx mir::Mir<'tcx>,
instance: ty::Instance<'tcx>,
// Whether a stackframe for a new constant has been pushed
new_constant: &'a mut EvalResult<'tcx, bool>,
}
impl<'a, 'b, 'tcx, M: Machine<'tcx>> ConstantExtractor<'a, 'b, 'tcx, M> {
fn try<F: FnOnce(&mut Self) -> EvalResult<'tcx, bool>>(&mut self, f: F) {
match *self.new_constant {
// already computed a constant, don't do more than one per iteration
Ok(true) => {},
// no constants computed yet
Ok(false) => *self.new_constant = f(self),
// error happened, abort the visitor traversing
Err(_) => {},
}
}
}
impl<'a, 'b, 'tcx, M: Machine<'tcx>> Visitor<'tcx> for ConstantExtractor<'a, 'b, 'tcx, M> {
fn visit_constant(&mut self, constant: &mir::Constant<'tcx>, location: mir::Location) {
self.super_constant(constant, location);
self.try(|this| {
match constant.literal {
// already computed by rustc
mir::Literal::Value { value: &ty::Const { val: ConstVal::Unevaluated(def_id, substs), .. } } => {
debug!("global_item: {:?}, {:#?}", def_id, substs);
let substs = this.ecx.tcx.trans_apply_param_substs(this.instance.substs, &substs);
debug!("global_item_new_substs: {:#?}", substs);
debug!("global_item_param_env: {:#?}", this.ecx.param_env);
let instance = Instance::resolve(
this.ecx.tcx,
this.ecx.param_env,
def_id,
substs,
).ok_or(EvalErrorKind::TypeckError)?; // turn error prop into a panic to expose associated type in const issue
this.ecx.global_item(
instance,
constant.span,
Mutability::Immutable,
)
}
mir::Literal::Value { .. } => Ok(false),
mir::Literal::Promoted { index } => {
let cid = GlobalId {
instance: this.instance,
promoted: Some(index),
};
if this.ecx.tcx.interpret_interner.borrow().get_cached(cid).is_some() {
return Ok(false);
}
let mir = &this.mir.promoted[index];
let ty = this.ecx.monomorphize(mir.return_ty(), this.instance.substs);
let layout = this.ecx.layout_of(ty)?;
assert!(!layout.is_unsized());
let ptr = this.ecx.memory.allocate(
layout.size.bytes(),
layout.align.abi(),
None,
)?;
this.ecx.tcx.interpret_interner.borrow_mut().cache(
cid,
PtrAndAlign {
ptr: ptr.into(),
aligned: !layout.is_packed(),
},
);
trace!("pushing stack frame for {:?}", index);
this.ecx.push_stack_frame(
this.instance,
constant.span,
mir,
Place::from_ptr(ptr),
StackPopCleanup::MarkStatic(Mutability::Immutable),
)?;
Ok(true)
}
}
});
}
fn visit_place(
&mut self,
place: &mir::Place<'tcx>,
context: PlaceContext<'tcx>,
location: mir::Location,
) {
self.super_place(place, context, location);
self.try(|this| {
if let mir::Place::Static(ref static_) = *place {
let def_id = static_.def_id;
let span = this.span;
if let Some(node_item) = this.ecx.tcx.hir.get_if_local(def_id) {
if let hir::map::Node::NodeItem(&hir::Item { ref node, .. }) = node_item {
if let hir::ItemStatic(_, m, _) = *node {
let instance = Instance::mono(this.ecx.tcx, def_id);
this.ecx.global_item(
instance,
span,
if m == hir::MutMutable {
Mutability::Mutable
} else {
Mutability::Immutable
},
)
} else {
bug!("static def id doesn't point to static");
}
} else {
bug!("static def id doesn't point to item");
}
} else {
let def = this.ecx.tcx.describe_def(def_id).expect("static not found");
if let hir::def::Def::Static(_, mutable) = def {
let instance = Instance::mono(this.ecx.tcx, def_id);
this.ecx.global_item(
instance,
span,
if mutable {
Mutability::Mutable
} else {
Mutability::Immutable
},
)
} else {
bug!("static found but isn't a static: {:?}", def);
}
}
} else {
Ok(false)
}
});
}
}