]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/terminator.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_mir / interpret / terminator.rs
1 use std::borrow::Cow;
2
3 use rustc::ty::layout::{self, LayoutOf, TyLayout};
4 use rustc::ty::Instance;
5 use rustc::{mir, ty};
6 use rustc_span::source_map::Span;
7 use rustc_target::spec::abi::Abi;
8
9 use super::{
10     FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup,
11 };
12
13 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
14     pub(super) fn eval_terminator(
15         &mut self,
16         terminator: &mir::Terminator<'tcx>,
17     ) -> InterpResult<'tcx> {
18         use rustc::mir::TerminatorKind::*;
19         match terminator.kind {
20             Return => {
21                 self.frame().return_place.map(|r| self.dump_place(*r));
22                 self.pop_stack_frame(/* unwinding */ false)?
23             }
24
25             Goto { target } => self.go_to_block(target),
26
27             SwitchInt { ref discr, ref values, ref targets, .. } => {
28                 let discr = self.read_immediate(self.eval_operand(discr, None)?)?;
29                 trace!("SwitchInt({:?})", *discr);
30
31                 // Branch to the `otherwise` case by default, if no match is found.
32                 let mut target_block = targets[targets.len() - 1];
33
34                 for (index, &const_int) in values.iter().enumerate() {
35                     // Compare using binary_op, to also support pointer values
36                     let res = self
37                         .overflowing_binary_op(
38                             mir::BinOp::Eq,
39                             discr,
40                             ImmTy::from_uint(const_int, discr.layout),
41                         )?
42                         .0;
43                     if res.to_bool()? {
44                         target_block = targets[index];
45                         break;
46                     }
47                 }
48
49                 self.go_to_block(target_block);
50             }
51
52             Call { ref func, ref args, ref destination, ref cleanup, .. } => {
53                 let func = self.eval_operand(func, None)?;
54                 let (fn_val, abi) = match func.layout.ty.kind {
55                     ty::FnPtr(sig) => {
56                         let caller_abi = sig.abi();
57                         let fn_ptr = self.read_scalar(func)?.not_undef()?;
58                         let fn_val = self.memory.get_fn(fn_ptr)?;
59                         (fn_val, caller_abi)
60                     }
61                     ty::FnDef(def_id, substs) => {
62                         let sig = func.layout.ty.fn_sig(*self.tcx);
63                         (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi())
64                     }
65                     _ => bug!("invalid callee of type {:?}", func.layout.ty),
66                 };
67                 let args = self.eval_operands(args)?;
68                 let ret = match destination {
69                     Some((dest, ret)) => Some((self.eval_place(dest)?, *ret)),
70                     None => None,
71                 };
72                 self.eval_fn_call(
73                     fn_val,
74                     terminator.source_info.span,
75                     abi,
76                     &args[..],
77                     ret,
78                     *cleanup,
79                 )?;
80             }
81
82             Drop { ref location, target, unwind } => {
83                 // FIXME(CTFE): forbid drop in const eval
84                 let place = self.eval_place(location)?;
85                 let ty = place.layout.ty;
86                 trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
87
88                 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
89                 self.drop_in_place(place, instance, terminator.source_info.span, target, unwind)?;
90             }
91
92             Assert { ref cond, expected, ref msg, target, cleanup } => {
93                 let cond_val =
94                     self.read_immediate(self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
95                 if expected == cond_val {
96                     self.go_to_block(target);
97                 } else {
98                     M::assert_panic(self, msg, cleanup)?;
99                 }
100             }
101
102             Abort => {
103                 M::abort(self)?;
104             }
105
106             // When we encounter Resume, we've finished unwinding
107             // cleanup for the current stack frame. We pop it in order
108             // to continue unwinding the next frame
109             Resume => {
110                 trace!("unwinding: resuming from cleanup");
111                 // By definition, a Resume terminator means
112                 // that we're unwinding
113                 self.pop_stack_frame(/* unwinding */ true)?;
114                 return Ok(());
115             }
116
117             // It is UB to ever encounter this.
118             Unreachable => throw_ub!(Unreachable),
119
120             // These should never occur for MIR we actually run.
121             DropAndReplace { .. }
122             | FalseEdges { .. }
123             | FalseUnwind { .. }
124             | Yield { .. }
125             | GeneratorDrop => {
126                 bug!("{:#?} should have been eliminated by MIR pass", terminator.kind)
127             }
128         }
129
130         Ok(())
131     }
132
133     fn check_argument_compat(
134         rust_abi: bool,
135         caller: TyLayout<'tcx>,
136         callee: TyLayout<'tcx>,
137     ) -> bool {
138         if caller.ty == callee.ty {
139             // No question
140             return true;
141         }
142         if !rust_abi {
143             // Don't risk anything
144             return false;
145         }
146         // Compare layout
147         match (&caller.abi, &callee.abi) {
148             // Different valid ranges are okay (once we enforce validity,
149             // that will take care to make it UB to leave the range, just
150             // like for transmute).
151             (layout::Abi::Scalar(ref caller), layout::Abi::Scalar(ref callee)) => {
152                 caller.value == callee.value
153             }
154             (
155                 layout::Abi::ScalarPair(ref caller1, ref caller2),
156                 layout::Abi::ScalarPair(ref callee1, ref callee2),
157             ) => caller1.value == callee1.value && caller2.value == callee2.value,
158             // Be conservative
159             _ => false,
160         }
161     }
162
163     /// Pass a single argument, checking the types for compatibility.
164     fn pass_argument(
165         &mut self,
166         rust_abi: bool,
167         caller_arg: &mut impl Iterator<Item = OpTy<'tcx, M::PointerTag>>,
168         callee_arg: PlaceTy<'tcx, M::PointerTag>,
169     ) -> InterpResult<'tcx> {
170         if rust_abi && callee_arg.layout.is_zst() {
171             // Nothing to do.
172             trace!("Skipping callee ZST");
173             return Ok(());
174         }
175         let caller_arg = caller_arg.next().ok_or_else(|| {
176             err_ub_format!("calling a function with fewer arguments than it requires")
177         })?;
178         if rust_abi {
179             assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
180         }
181         // Now, check
182         if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
183             throw_ub_format!(
184                 "calling a function with argument of type {:?} passing data of type {:?}",
185                 callee_arg.layout.ty,
186                 caller_arg.layout.ty
187             )
188         }
189         // We allow some transmutes here
190         self.copy_op_transmute(caller_arg, callee_arg)
191     }
192
193     /// Call this function -- pushing the stack frame and initializing the arguments.
194     fn eval_fn_call(
195         &mut self,
196         fn_val: FnVal<'tcx, M::ExtraFnVal>,
197         span: Span,
198         caller_abi: Abi,
199         args: &[OpTy<'tcx, M::PointerTag>],
200         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
201         unwind: Option<mir::BasicBlock>,
202     ) -> InterpResult<'tcx> {
203         trace!("eval_fn_call: {:#?}", fn_val);
204
205         let instance = match fn_val {
206             FnVal::Instance(instance) => instance,
207             FnVal::Other(extra) => {
208                 return M::call_extra_fn(self, extra, args, ret, unwind);
209             }
210         };
211
212         // ABI check
213         {
214             let callee_abi = {
215                 let instance_ty = instance.ty_env(*self.tcx, self.param_env);
216                 match instance_ty.kind {
217                     ty::FnDef(..) => instance_ty.fn_sig(*self.tcx).abi(),
218                     ty::Closure(..) => Abi::RustCall,
219                     ty::Generator(..) => Abi::Rust,
220                     _ => bug!("unexpected callee ty: {:?}", instance_ty),
221                 }
222             };
223             let normalize_abi = |abi| match abi {
224                 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
225                 // These are all the same ABI, really.
226                 {
227                     Abi::Rust
228                 }
229                 abi => abi,
230             };
231             if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
232                 throw_ub_format!(
233                     "calling a function with ABI {:?} using caller ABI {:?}",
234                     callee_abi,
235                     caller_abi
236                 )
237             }
238         }
239
240         match instance.def {
241             ty::InstanceDef::Intrinsic(..) => {
242                 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
243                 return M::call_intrinsic(self, span, instance, args, ret, unwind);
244             }
245             ty::InstanceDef::VtableShim(..)
246             | ty::InstanceDef::ReifyShim(..)
247             | ty::InstanceDef::ClosureOnceShim { .. }
248             | ty::InstanceDef::FnPtrShim(..)
249             | ty::InstanceDef::DropGlue(..)
250             | ty::InstanceDef::CloneShim(..)
251             | ty::InstanceDef::Item(_) => {
252                 // We need MIR for this fn
253                 let body = match M::find_mir_or_eval_fn(self, span, instance, args, ret, unwind)? {
254                     Some(body) => body,
255                     None => return Ok(()),
256                 };
257
258                 self.push_stack_frame(
259                     instance,
260                     span,
261                     body,
262                     ret.map(|p| p.0),
263                     StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
264                 )?;
265
266                 // If an error is raised here, pop the frame again to get an accurate backtrace.
267                 // To this end, we wrap it all in a `try` block.
268                 let res: InterpResult<'tcx> = try {
269                     trace!(
270                         "caller ABI: {:?}, args: {:#?}",
271                         caller_abi,
272                         args.iter()
273                             .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
274                             .collect::<Vec<_>>()
275                     );
276                     trace!(
277                         "spread_arg: {:?}, locals: {:#?}",
278                         body.spread_arg,
279                         body.args_iter()
280                             .map(|local| (
281                                 local,
282                                 self.layout_of_local(self.frame(), local, None).unwrap().ty
283                             ))
284                             .collect::<Vec<_>>()
285                     );
286
287                     // Figure out how to pass which arguments.
288                     // The Rust ABI is special: ZST get skipped.
289                     let rust_abi = match caller_abi {
290                         Abi::Rust | Abi::RustCall => true,
291                         _ => false,
292                     };
293                     // We have two iterators: Where the arguments come from,
294                     // and where they go to.
295
296                     // For where they come from: If the ABI is RustCall, we untuple the
297                     // last incoming argument.  These two iterators do not have the same type,
298                     // so to keep the code paths uniform we accept an allocation
299                     // (for RustCall ABI only).
300                     let caller_args: Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
301                         if caller_abi == Abi::RustCall && !args.is_empty() {
302                             // Untuple
303                             let (&untuple_arg, args) = args.split_last().unwrap();
304                             trace!("eval_fn_call: Will pass last argument by untupling");
305                             Cow::from(
306                                 args.iter()
307                                     .map(|&a| Ok(a))
308                                     .chain(
309                                         (0..untuple_arg.layout.fields.count())
310                                             .map(|i| self.operand_field(untuple_arg, i as u64)),
311                                     )
312                                     .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
313                                     )?,
314                             )
315                         } else {
316                             // Plain arg passing
317                             Cow::from(args)
318                         };
319                     // Skip ZSTs
320                     let mut caller_iter =
321                         caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
322
323                     // Now we have to spread them out across the callee's locals,
324                     // taking into account the `spread_arg`.  If we could write
325                     // this is a single iterator (that handles `spread_arg`), then
326                     // `pass_argument` would be the loop body. It takes care to
327                     // not advance `caller_iter` for ZSTs.
328                     for local in body.args_iter() {
329                         let dest = self.eval_place(&mir::Place::from(local))?;
330                         if Some(local) == body.spread_arg {
331                             // Must be a tuple
332                             for i in 0..dest.layout.fields.count() {
333                                 let dest = self.place_field(dest, i as u64)?;
334                                 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
335                             }
336                         } else {
337                             // Normal argument
338                             self.pass_argument(rust_abi, &mut caller_iter, dest)?;
339                         }
340                     }
341                     // Now we should have no more caller args
342                     if caller_iter.next().is_some() {
343                         throw_ub_format!("calling a function with more arguments than it expected")
344                     }
345                     // Don't forget to check the return type!
346                     if let Some((caller_ret, _)) = ret {
347                         let callee_ret = self.eval_place(&mir::Place::return_place())?;
348                         if !Self::check_argument_compat(
349                             rust_abi,
350                             caller_ret.layout,
351                             callee_ret.layout,
352                         ) {
353                             throw_ub_format!(
354                                 "calling a function with return type {:?} passing \
355                                      return place of type {:?}",
356                                 callee_ret.layout.ty,
357                                 caller_ret.layout.ty
358                             )
359                         }
360                     } else {
361                         let local = mir::RETURN_PLACE;
362                         let callee_layout = self.layout_of_local(self.frame(), local, None)?;
363                         if !callee_layout.abi.is_uninhabited() {
364                             throw_ub_format!("calling a returning function without a return place")
365                         }
366                     }
367                 };
368                 match res {
369                     Err(err) => {
370                         self.stack.pop();
371                         Err(err)
372                     }
373                     Ok(v) => Ok(v),
374                 }
375             }
376             // cannot use the shim here, because that will only result in infinite recursion
377             ty::InstanceDef::Virtual(_, idx) => {
378                 let mut args = args.to_vec();
379                 // We have to implement all "object safe receivers".  Currently we
380                 // support built-in pointers (&, &mut, Box) as well as unsized-self.  We do
381                 // not yet support custom self types.
382                 // Also see librustc_codegen_llvm/abi.rs and librustc_codegen_llvm/mir/block.rs.
383                 let receiver_place = match args[0].layout.ty.builtin_deref(true) {
384                     Some(_) => {
385                         // Built-in pointer.
386                         self.deref_operand(args[0])?
387                     }
388                     None => {
389                         // Unsized self.
390                         args[0].assert_mem_place(self)
391                     }
392                 };
393                 // Find and consult vtable
394                 let vtable = receiver_place.vtable();
395                 let drop_fn = self.get_vtable_slot(vtable, idx)?;
396
397                 // `*mut receiver_place.layout.ty` is almost the layout that we
398                 // want for args[0]: We have to project to field 0 because we want
399                 // a thin pointer.
400                 assert!(receiver_place.layout.is_unsized());
401                 let receiver_ptr_ty = self.tcx.mk_mut_ptr(receiver_place.layout.ty);
402                 let this_receiver_ptr = self.layout_of(receiver_ptr_ty)?.field(self, 0)?;
403                 // Adjust receiver argument.
404                 args[0] =
405                     OpTy::from(ImmTy { layout: this_receiver_ptr, imm: receiver_place.ptr.into() });
406                 trace!("Patched self operand to {:#?}", args[0]);
407                 // recurse with concrete function
408                 self.eval_fn_call(drop_fn, span, caller_abi, &args, ret, unwind)
409             }
410         }
411     }
412
413     fn drop_in_place(
414         &mut self,
415         place: PlaceTy<'tcx, M::PointerTag>,
416         instance: ty::Instance<'tcx>,
417         span: Span,
418         target: mir::BasicBlock,
419         unwind: Option<mir::BasicBlock>,
420     ) -> InterpResult<'tcx> {
421         trace!("drop_in_place: {:?},\n  {:?}, {:?}", *place, place.layout.ty, instance);
422         // We take the address of the object.  This may well be unaligned, which is fine
423         // for us here.  However, unaligned accesses will probably make the actual drop
424         // implementation fail -- a problem shared by rustc.
425         let place = self.force_allocation(place)?;
426
427         let (instance, place) = match place.layout.ty.kind {
428             ty::Dynamic(..) => {
429                 // Dropping a trait object.
430                 self.unpack_dyn_trait(place)?
431             }
432             _ => (instance, place),
433         };
434
435         let arg = ImmTy {
436             imm: place.to_ref(),
437             layout: self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
438         };
439
440         let ty = self.tcx.mk_unit(); // return type is ()
441         let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
442
443         self.eval_fn_call(
444             FnVal::Instance(instance),
445             span,
446             Abi::Rust,
447             &[arg.into()],
448             Some((dest.into(), target)),
449             unwind,
450         )
451     }
452 }