]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
Merge branch 'master' into debug
[rust.git] / src / stacked_borrows.rs
1 use std::cell::RefCell;
2 use std::collections::{HashMap, HashSet};
3 use std::rc::Rc;
4 use std::fmt;
5 use std::num::NonZeroU64;
6
7 use rustc::ty::{self, layout::Size};
8 use rustc::hir::{MutMutable, MutImmutable};
9 use rustc::mir::RetagKind;
10
11 use crate::{
12     EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
13     MemoryKind, MiriMemoryKind, RangeMap, Allocation, AllocationExtra, AllocId, CheckInAllocMsg,
14     Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
15 };
16
17 pub type PtrId = NonZeroU64;
18 pub type CallId = NonZeroU64;
19
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
22 pub enum Tag {
23     Tagged(PtrId),
24     Untagged,
25 }
26
27 impl fmt::Debug for Tag {
28     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29         match self {
30             Tag::Tagged(id) => write!(f, "<{}>", id),
31             Tag::Untagged => write!(f, "<untagged>"),
32         }
33     }
34 }
35
36 /// Indicates which permission is granted (by this item to some pointers)
37 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
38 pub enum Permission {
39     /// Grants unique mutable access.
40     Unique,
41     /// Grants shared mutable access.
42     SharedReadWrite,
43     /// Grants shared read-only access.
44     SharedReadOnly,
45     /// Grants no access, but separates two groups of SharedReadWrite so they are not
46     /// all considered mutually compatible.
47     Disabled,
48 }
49
50 /// An item in the per-location borrow stack.
51 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
52 pub struct Item {
53     /// The permission this item grants.
54     perm: Permission,
55     /// The pointers the permission is granted to.
56     tag: Tag,
57     /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
58     protector: Option<CallId>,
59 }
60
61 impl fmt::Debug for Item {
62     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63         write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
64         if let Some(call) = self.protector {
65             write!(f, " (call {})", call)?;
66         }
67         write!(f, "]")?;
68         Ok(())
69     }
70 }
71
72 /// Extra per-location state.
73 #[derive(Clone, Debug, PartialEq, Eq)]
74 pub struct Stack {
75     /// Used *mostly* as a stack; never empty.
76     /// Invariants:
77     /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
78     /// * Except for `Untagged`, no tag occurs in the stack more than once.
79     borrows: Vec<Item>,
80 }
81
82
83 /// Extra per-allocation state.
84 #[derive(Clone, Debug)]
85 pub struct Stacks {
86     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
87     stacks: RefCell<RangeMap<Stack>>,
88     // Pointer to global state
89     global: MemoryState,
90 }
91
92 /// Extra global state, available to the memory access hooks.
93 #[derive(Debug)]
94 pub struct GlobalState {
95     /// Next unused pointer ID (tag).
96     next_ptr_id: PtrId,
97     /// Table storing the "base" tag for each allocation.
98     /// The base tag is the one used for the initial pointer.
99     /// We need this in a separate table to handle cyclic statics.
100     base_ptr_ids: HashMap<AllocId, Tag>,
101     /// Next unused call ID (for protectors).
102     next_call_id: CallId,
103     /// Those call IDs corresponding to functions that are still running.
104     active_calls: HashSet<CallId>,
105 }
106 /// Memory extra state gives us interior mutable access to the global state.
107 pub type MemoryState = Rc<RefCell<GlobalState>>;
108
109 /// Indicates which kind of access is being performed.
110 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
111 pub enum AccessKind {
112     Read,
113     Write,
114 }
115
116 impl fmt::Display for AccessKind {
117     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118         match self {
119             AccessKind::Read => write!(f, "read access"),
120             AccessKind::Write => write!(f, "write access"),
121         }
122     }
123 }
124
125 /// Indicates which kind of reference is being created.
126 /// Used by high-level `reborrow` to compute which permissions to grant to the
127 /// new pointer.
128 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
129 pub enum RefKind {
130     /// `&mut` and `Box`.
131     Unique { two_phase: bool },
132     /// `&` with or without interior mutability.
133     Shared,
134     /// `*mut`/`*const` (raw pointers).
135     Raw { mutable: bool },
136 }
137
138 impl fmt::Display for RefKind {
139     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140         match self {
141             RefKind::Unique { two_phase: false } => write!(f, "unique"),
142             RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
143             RefKind::Shared => write!(f, "shared"),
144             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
145             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
146         }
147     }
148 }
149
150 /// Utilities for initialization and ID generation
151 impl Default for GlobalState {
152     fn default() -> Self {
153         GlobalState {
154             next_ptr_id: NonZeroU64::new(1).unwrap(),
155             base_ptr_ids: HashMap::default(),
156             next_call_id: NonZeroU64::new(1).unwrap(),
157             active_calls: HashSet::default(),
158         }
159     }
160 }
161
162 impl GlobalState {
163     fn new_ptr(&mut self) -> PtrId {
164         let id = self.next_ptr_id;
165         self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
166         id
167     }
168
169     pub fn new_call(&mut self) -> CallId {
170         let id = self.next_call_id;
171         trace!("new_call: Assigning ID {}", id);
172         self.active_calls.insert(id);
173         self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
174         id
175     }
176
177     pub fn end_call(&mut self, id: CallId) {
178         assert!(self.active_calls.remove(&id));
179     }
180
181     fn is_active(&self, id: CallId) -> bool {
182         self.active_calls.contains(&id)
183     }
184
185     pub fn static_base_ptr(&mut self, id: AllocId) -> Tag {
186         self.base_ptr_ids.get(&id).copied().unwrap_or_else(|| {
187             let tag = Tag::Tagged(self.new_ptr());
188             trace!("New allocation {:?} has base tag {:?}", id, tag);
189             self.base_ptr_ids.insert(id, tag);
190             tag
191         })
192     }
193 }
194
195 // # Stacked Borrows Core Begin
196
197 /// We need to make at least the following things true:
198 ///
199 /// U1: After creating a `Uniq`, it is at the top.
200 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
201 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
202 ///
203 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
204 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
205 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
206 ///          gets popped.
207 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
208 /// F3: If an access happens with an `&` outside `UnsafeCell`,
209 ///     it requires the `SharedReadOnly` to still be in the stack.
210
211 /// Core relation on `Permission` to define which accesses are allowed
212 impl Permission {
213     /// This defines for a given permission, whether it permits the given kind of access.
214     fn grants(self, access: AccessKind) -> bool {
215         // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
216         self != Permission::Disabled && (access == AccessKind::Read || self != Permission::SharedReadOnly)
217     }
218 }
219
220 /// Core per-location operations: access, dealloc, reborrow.
221 impl<'tcx> Stack {
222     /// Find the item granting the given kind of access to the given tag, and return where
223     /// it is on the stack.
224     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
225         self.borrows.iter()
226             .enumerate() // we also need to know *where* in the stack
227             .rev() // search top-to-bottom
228             // Return permission of first item that grants access.
229             // We require a permission with the right tag, ensuring U3 and F3.
230             .find_map(|(idx, item)|
231                 if tag == item.tag && item.perm.grants(access) {
232                     Some(idx)
233                 } else {
234                     None
235                 }
236             )
237     }
238
239     /// Find the first write-incompatible item above the given one --
240     /// i.e, find the height to which the stack will be truncated when writing to `granting`.
241     fn find_first_write_incompaible(&self, granting: usize) -> usize {
242         let perm = self.borrows[granting].perm;
243         match perm {
244             Permission::SharedReadOnly =>
245                 bug!("Cannot use SharedReadOnly for writing"),
246             Permission::Disabled =>
247                 bug!("Cannot use Disabled for anything"),
248             Permission::Unique =>
249                 // On a write, everything above us is incompatible.
250                 granting + 1,
251             Permission::SharedReadWrite => {
252                 // The SharedReadWrite *just* above us are compatible, to skip those.
253                 let mut idx = granting + 1;
254                 while let Some(item) = self.borrows.get(idx) {
255                     if item.perm == Permission::SharedReadWrite {
256                         // Go on.
257                         idx += 1;
258                     } else {
259                         // Found first incompatible!
260                         break;
261                     }
262                 }
263                 idx
264             }
265         }
266     }
267
268     /// Check if the given item is protected.
269     fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> EvalResult<'tcx> {
270         if let Some(call) = item.protector {
271             if global.is_active(call) {
272                 if let Some(tag) = tag {
273                     return err!(MachineError(format!(
274                         "not granting access to tag {:?} because incompatible item is protected: {:?}",
275                         tag, item
276                     )));
277                 } else {
278                     return err!(MachineError(format!(
279                         "deallocating while item is protected: {:?}", item
280                     )));
281                 }
282             }
283         }
284         Ok(())
285     }
286
287     /// Test if a memory `access` using pointer tagged `tag` is granted.
288     /// If yes, return the index of the item that granted it.
289     fn access(
290         &mut self,
291         access: AccessKind,
292         tag: Tag,
293         global: &GlobalState,
294     ) -> EvalResult<'tcx> {
295         // Two main steps: Find granting item, remove incompatible items above.
296
297         // Step 1: Find granting item.
298         let granting_idx = self.find_granting(access, tag)
299             .ok_or_else(|| InterpError::MachineError(format!(
300                 "no item granting {} to tag {:?} found in borrow stack",
301                 access, tag,
302             )))?;
303
304         // Step 2: Remove incompatible items above them.  Make sure we do not remove protected
305         // items.  Behavior differs for reads and writes.
306         if access == AccessKind::Write {
307             // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
308             // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
309             let first_incompatible_idx = self.find_first_write_incompaible(granting_idx);
310             for item in self.borrows.drain(first_incompatible_idx..).rev() {
311                 trace!("access: popping item {:?}", item);
312                 Stack::check_protector(&item, Some(tag), global)?;
313             }
314         } else {
315             // On a read, *disable* all `Unique` above the granting item.  This ensures U2 for read accesses.
316             // The reason this is not following the stack discipline (by removing the first Unique and
317             // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
318             // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
319             // `SharedReadWrite` for `raw`.
320             // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
321             // reference and use that.
322             // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
323             for idx in (granting_idx+1 .. self.borrows.len()).rev() {
324                 let item = &mut self.borrows[idx];
325                 if item.perm == Permission::Unique {
326                     trace!("access: disabling item {:?}", item);
327                     Stack::check_protector(item, Some(tag), global)?;
328                     item.perm = Permission::Disabled;
329                 }
330             }
331         }
332
333         // Done.
334         Ok(())
335     }
336
337     /// Deallocate a location: Like a write access, but also there must be no
338     /// active protectors at all because we will remove all items.
339     fn dealloc(
340         &mut self,
341         tag: Tag,
342         global: &GlobalState,
343     ) -> EvalResult<'tcx> {
344         // Step 1: Find granting item.
345         self.find_granting(AccessKind::Write, tag)
346             .ok_or_else(|| InterpError::MachineError(format!(
347                 "no item granting write access for deallocation to tag {:?} found in borrow stack",
348                 tag,
349             )))?;
350
351         // Step 2: Remove all items.  Also checks for protectors.
352         for item in self.borrows.drain(..).rev() {
353             Stack::check_protector(&item, None, global)?;
354         }
355
356         Ok(())
357     }
358
359     /// Derived a new pointer from one with the given tag.
360     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
361     /// an access, and they add the new item directly on top of the one it is derived
362     /// from instead of all the way at the top of the stack.
363     fn grant(
364         &mut self,
365         derived_from: Tag,
366         new: Item,
367         global: &GlobalState,
368     ) -> EvalResult<'tcx> {
369         // Figure out which access `perm` corresponds to.
370         let access = if new.perm.grants(AccessKind::Write) {
371             AccessKind::Write
372         } else {
373             AccessKind::Read
374         };
375         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
376         // We use that to determine where to put the new item.
377         let granting_idx = self.find_granting(access, derived_from)
378             .ok_or_else(|| InterpError::MachineError(format!(
379                 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack", new.perm, derived_from,
380             )))?;
381
382         // Compute where to put the new item.
383         // Either way, we ensure that we insert the new item in a way such that between
384         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
385         let new_idx = if new.perm == Permission::SharedReadWrite {
386             assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
387             // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
388             // access.  Instead of popping the stack, we insert the item at the place the stack would
389             // be popped to (i.e., we insert it above all the write-compatible items).
390             // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
391             self.find_first_write_incompaible(granting_idx)
392         } else {
393             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
394             // Here, creating a reference actually counts as an access.
395             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
396             self.access(access, derived_from, global)?;
397
398             // We insert "as far up as possible": We know only compatible items are remaining
399             // on top of `derived_from`, and we want the new item at the top so that we
400             // get the strongest possible guarantees.
401             // This ensures U1 and F1.
402             self.borrows.len()
403         };
404
405         // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
406         if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
407             // Optimization applies, done.
408             trace!("reborrow: avoiding adding redundant item {:?}", new);
409         } else {
410             trace!("reborrow: adding item {:?}", new);
411             self.borrows.insert(new_idx, new);
412         }
413
414         Ok(())
415     }
416 }
417 // # Stacked Borrows Core End
418
419 /// Map per-stack operations to higher-level per-location-range operations.
420 impl<'tcx> Stacks {
421     /// Creates new stack with initial tag.
422     fn new(
423         size: Size,
424         perm: Permission,
425         tag: Tag,
426         extra: MemoryState,
427     ) -> Self {
428         let item = Item { perm, tag, protector: None };
429         let stack = Stack {
430             borrows: vec![item],
431         };
432         Stacks {
433             stacks: RefCell::new(RangeMap::new(size, stack)),
434             global: extra,
435         }
436     }
437
438     /// Call `f` on every stack in the range.
439     fn for_each(
440         &self,
441         ptr: Pointer<Tag>,
442         size: Size,
443         f: impl Fn(&mut Stack, &GlobalState) -> EvalResult<'tcx>,
444     ) -> EvalResult<'tcx> {
445         let global = self.global.borrow();
446         let mut stacks = self.stacks.borrow_mut();
447         for stack in stacks.iter_mut(ptr.offset, size) {
448             f(stack, &*global)?;
449         }
450         Ok(())
451     }
452 }
453
454 /// Glue code to connect with Miri Machine Hooks
455 impl Stacks {
456     pub fn new_allocation(
457         id: AllocId,
458         size: Size,
459         extra: MemoryState,
460         kind: MemoryKind<MiriMemoryKind>,
461     ) -> (Self, Tag) {
462         let (tag, perm) = match kind {
463             MemoryKind::Stack =>
464                 // New unique borrow. This tag is not accessible by the program,
465                 // so it will only ever be used when using the local directly (i.e.,
466                 // not through a pointer). That is, whenever we directly write to a local, this will pop
467                 // everything else off the stack, invalidating all previous pointers,
468                 // and in particular, *all* raw pointers.
469                 (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
470             MemoryKind::Machine(MiriMemoryKind::Static) =>
471                 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
472             _ =>
473                 (Tag::Untagged, Permission::SharedReadWrite),
474         };
475         let stack = Stacks::new(size, perm, tag, extra);
476         (stack, tag)
477     }
478 }
479
480 impl AllocationExtra<Tag> for Stacks {
481     #[inline(always)]
482     fn memory_read<'tcx>(
483         alloc: &Allocation<Tag, Stacks>,
484         ptr: Pointer<Tag>,
485         size: Size,
486     ) -> EvalResult<'tcx> {
487         trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
488         alloc.extra.for_each(ptr, size, |stack, global| {
489             stack.access(AccessKind::Read, ptr.tag, global)?;
490             Ok(())
491         })
492     }
493
494     #[inline(always)]
495     fn memory_written<'tcx>(
496         alloc: &mut Allocation<Tag, Stacks>,
497         ptr: Pointer<Tag>,
498         size: Size,
499     ) -> EvalResult<'tcx> {
500         trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
501         alloc.extra.for_each(ptr, size, |stack, global| {
502             stack.access(AccessKind::Write, ptr.tag, global)?;
503             Ok(())
504         })
505     }
506
507     #[inline(always)]
508     fn memory_deallocated<'tcx>(
509         alloc: &mut Allocation<Tag, Stacks>,
510         ptr: Pointer<Tag>,
511         size: Size,
512     ) -> EvalResult<'tcx> {
513         trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
514         alloc.extra.for_each(ptr, size, |stack, global| {
515             stack.dealloc(ptr.tag, global)
516         })
517     }
518 }
519
520 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
521 /// to grant for which references, and when to add protectors.
522 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
523 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
524     fn reborrow(
525         &mut self,
526         place: MPlaceTy<'tcx, Tag>,
527         size: Size,
528         kind: RefKind,
529         new_tag: Tag,
530         protect: bool,
531     ) -> EvalResult<'tcx> {
532         let this = self.eval_context_mut();
533         let protector = if protect { Some(this.frame().extra) } else { None };
534         let ptr = place.ptr.to_ptr()?;
535         trace!("reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
536             kind, new_tag, ptr.tag, place.layout.ty, ptr.erase_tag(), size.bytes());
537
538         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
539         let alloc = this.memory().get(ptr.alloc_id)?;
540         alloc.check_bounds(this, ptr, size, CheckInAllocMsg::InboundsTest)?;
541         // Update the stacks.
542         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
543         // There could be existing unique pointers reborrowed from them that should remain valid!
544         let perm = match kind {
545             RefKind::Unique { two_phase: false } => Permission::Unique,
546             RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
547             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
548             RefKind::Shared | RefKind::Raw { mutable: false } => {
549                 // Shared references and *const are a whole different kind of game, the
550                 // permission is not uniform across the entire range!
551                 // We need a frozen-sensitive reborrow.
552                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
553                     // We are only ever `SharedReadOnly` inside the frozen bits.
554                     let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
555                     let item = Item { perm, tag: new_tag, protector };
556                     alloc.extra.for_each(cur_ptr, size, |stack, global| {
557                         stack.grant(cur_ptr.tag, item, global)
558                     })
559                 });
560             }
561         };
562         let item = Item { perm, tag: new_tag, protector };
563         alloc.extra.for_each(ptr, size, |stack, global| {
564             stack.grant(ptr.tag, item, global)
565         })
566     }
567
568     /// Retags an indidual pointer, returning the retagged version.
569     /// `mutbl` can be `None` to make this a raw pointer.
570     fn retag_reference(
571         &mut self,
572         val: ImmTy<'tcx, Tag>,
573         kind: RefKind,
574         protect: bool,
575     ) -> EvalResult<'tcx, Immediate<Tag>> {
576         let this = self.eval_context_mut();
577         // We want a place for where the ptr *points to*, so we get one.
578         let place = this.ref_to_mplace(val)?;
579         let size = this.size_and_align_of_mplace(place)?
580             .map(|(size, _)| size)
581             .unwrap_or_else(|| place.layout.size);
582         if size == Size::ZERO {
583             // Nothing to do for ZSTs.
584             return Ok(*val);
585         }
586
587         // Compute new borrow.
588         let new_tag = match kind {
589             RefKind::Raw { .. } => Tag::Untagged,
590             _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
591         };
592
593         // Reborrow.
594         this.reborrow(place, size, kind, new_tag, protect)?;
595         let new_place = place.replace_tag(new_tag);
596
597         // Return new pointer.
598         Ok(new_place.to_ref())
599     }
600 }
601
602 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
603 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
604     fn retag(
605         &mut self,
606         kind: RetagKind,
607         place: PlaceTy<'tcx, Tag>
608     ) -> EvalResult<'tcx> {
609         let this = self.eval_context_mut();
610         // Determine mutability and whether to add a protector.
611         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
612         // making it useless.
613         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
614             match ty.sty {
615                 // References are simple.
616                 ty::Ref(_, _, MutMutable) =>
617                     Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
618                 ty::Ref(_, _, MutImmutable) =>
619                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
620                 // Raw pointers need to be enabled.
621                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
622                     Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
623                 // Boxes do not get a protector: protectors reflect that references outlive the call
624                 // they were passed in to; that's just not the case for boxes.
625                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
626                 _ => None,
627             }
628         }
629
630         // We need a visitor to visit all references. However, that requires
631         // a `MemPlace`, so we have a fast path for reference types that
632         // avoids allocating.
633         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
634             // Fast path.
635             let val = this.read_immediate(this.place_to_op(place)?)?;
636             let val = this.retag_reference(val, mutbl, protector)?;
637             this.write_immediate(val, place)?;
638             return Ok(());
639         }
640         let place = this.force_allocation(place)?;
641
642         let mut visitor = RetagVisitor { ecx: this, kind };
643         visitor.visit_value(place)?;
644
645         // The actual visitor.
646         struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
647             ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
648             kind: RetagKind,
649         }
650         impl<'ecx, 'a, 'mir, 'tcx>
651             MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
652         for
653             RetagVisitor<'ecx, 'a, 'mir, 'tcx>
654         {
655             type V = MPlaceTy<'tcx, Tag>;
656
657             #[inline(always)]
658             fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
659                 &mut self.ecx
660             }
661
662             // Primitives of reference type, that is the one thing we are interested in.
663             fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
664             {
665                 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
666                 // making it useless.
667                 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
668                     let val = self.ecx.read_immediate(place.into())?;
669                     let val = self.ecx.retag_reference(
670                         val,
671                         mutbl,
672                         protector
673                     )?;
674                     self.ecx.write_immediate(val, place.into())?;
675                 }
676                 Ok(())
677             }
678         }
679
680         Ok(())
681     }
682 }