]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
rewrite Stacked Borrows Core. this passes stacked-borrows.rs!
[rust.git] / src / stacked_borrows.rs
1 use std::cell::RefCell;
2 use std::collections::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::{Mutability, MutMutable, MutImmutable};
9 use rustc::mir::RetagKind;
10
11 use crate::{
12     EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
13     MemoryKind, MiriMemoryKind, RangeMap, Allocation, AllocationExtra,
14     Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
15 };
16
17 pub type PtrId = NonZeroU64;
18 pub type CallId = u64;
19
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22 pub enum Tag {
23     Tagged(PtrId),
24     Untagged,
25 }
26
27 impl fmt::Display 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     /// Greants shared read-only access.
44     SharedReadOnly,
45 }
46
47 /// An item in the per-location borrow stack.
48 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
49 pub enum Item {
50     /// Grants the given permission for pointers with this tag.
51     Permission(Permission, Tag),
52     /// A barrier, tracking the function it belongs to by its index on the call stack.
53     FnBarrier(CallId),
54 }
55
56 impl fmt::Display for Item {
57     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58         match self {
59             Item::Permission(perm, tag) => write!(f, "[{:?} for {}]", perm, tag),
60             Item::FnBarrier(call) => write!(f, "[barrier {}]", call),
61         }
62     }
63 }
64
65 /// Extra per-location state.
66 #[derive(Clone, Debug, PartialEq, Eq)]
67 pub struct Stack {
68     /// Used *mostly* as a stack; never empty.
69     /// We sometimes push into the middle but never remove from the middle.
70     /// The same tag may occur multiple times, e.g. from a two-phase borrow.
71     /// Invariants:
72     /// * Above a `SharedReadOnly` there can only be barriers and more `SharedReadOnly`.
73     borrows: Vec<Item>,
74 }
75
76
77 /// Extra per-allocation state.
78 #[derive(Clone, Debug)]
79 pub struct Stacks {
80     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
81     stacks: RefCell<RangeMap<Stack>>,
82     // Pointer to global state
83     global: MemoryState,
84 }
85
86 /// Extra global state, available to the memory access hooks.
87 #[derive(Debug)]
88 pub struct GlobalState {
89     next_ptr_id: PtrId,
90     next_call_id: CallId,
91     active_calls: HashSet<CallId>,
92 }
93 pub type MemoryState = Rc<RefCell<GlobalState>>;
94
95 /// Indicates which kind of access is being performed.
96 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
97 pub enum AccessKind {
98     Read,
99     Write { dealloc: bool },
100 }
101
102 // "Fake" constructors
103 impl AccessKind {
104     fn write() -> AccessKind {
105         AccessKind::Write { dealloc: false }
106     }
107
108     fn dealloc() -> AccessKind {
109         AccessKind::Write { dealloc: true }
110     }
111 }
112
113 impl fmt::Display for AccessKind {
114     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115         match self {
116             AccessKind::Read => write!(f, "read"),
117             AccessKind::Write { dealloc: false } => write!(f, "write"),
118             AccessKind::Write { dealloc: true } => write!(f, "deallocation"),
119         }
120     }
121 }
122
123 /// Indicates which kind of reference is being created.
124 /// Used by `reborrow` to compute which permissions to grant to the
125 /// new pointer.
126 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
127 pub enum RefKind {
128     /// `&mut`.
129     Mutable,
130     /// `&` with or without interior mutability.
131     Shared { frozen: bool },
132     /// `*` (raw pointer).
133     Raw,
134 }
135
136 impl fmt::Display for RefKind {
137     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138         match self {
139             RefKind::Mutable => write!(f, "mutable"),
140             RefKind::Shared { frozen: true } => write!(f, "shared (frozen)"),
141             RefKind::Shared { frozen: false } => write!(f, "shared (mutable)"),
142             RefKind::Raw => write!(f, "raw"),
143         }
144     }
145 }
146
147 /// Utilities for initialization and ID generation
148 impl Default for GlobalState {
149     fn default() -> Self {
150         GlobalState {
151             next_ptr_id: NonZeroU64::new(1).unwrap(),
152             next_call_id: 0,
153             active_calls: HashSet::default(),
154         }
155     }
156 }
157
158 impl GlobalState {
159     pub fn new_ptr(&mut self) -> PtrId {
160         let id = self.next_ptr_id;
161         self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
162         id
163     }
164
165     pub fn new_call(&mut self) -> CallId {
166         let id = self.next_call_id;
167         trace!("new_call: Assigning ID {}", id);
168         self.active_calls.insert(id);
169         self.next_call_id = id+1;
170         id
171     }
172
173     pub fn end_call(&mut self, id: CallId) {
174         assert!(self.active_calls.remove(&id));
175     }
176
177     fn is_active(&self, id: CallId) -> bool {
178         self.active_calls.contains(&id)
179     }
180 }
181
182 // # Stacked Borrows Core Begin
183
184 /// We need to make at least the following things true:
185 ///
186 /// U1: After creating a `Uniq`, it is at the top (and unfrozen).
187 /// U2: If the top is `Uniq` (and unfrozen), accesses must be through that `Uniq` or pop it.
188 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
189 ///
190 /// F1: After creating a `&`, the parts outside `UnsafeCell` are frozen.
191 /// F2: If a write access happens, it unfreezes.
192 /// F3: If an access happens with an `&` outside `UnsafeCell`,
193 ///     it requires the location to still be frozen.
194
195 impl Default for Tag {
196     #[inline(always)]
197     fn default() -> Tag {
198         Tag::Untagged
199     }
200 }
201
202 /// Core relations on `Permission` define which accesses are allowed:
203 /// On every access, we try to find a *granting* item, and then we remove all
204 /// *incompatible* items above it.
205 impl Permission {
206     /// This defines for a given permission, whether it permits the given kind of access.
207     fn grants(self, access: AccessKind) -> bool {
208         match (self, access) {
209             // Unique and SharedReadWrite allow any kind of access.
210             (Permission::Unique, _) |
211             (Permission::SharedReadWrite, _) =>
212                 true,
213             // SharedReadOnly only permits read access.
214             (Permission::SharedReadOnly, AccessKind::Read) =>
215                 true,
216             (Permission::SharedReadOnly, AccessKind::Write { .. }) =>
217                 false,
218         }
219     }
220
221     /// This defines for a given permission, which other items it can tolerate "above" itself
222     /// for which kinds of accesses.
223     /// If true, then `other` is allowed to remain on top of `self` when `access` happens.
224     fn compatible_with(self, access: AccessKind, other: Item) -> bool {
225         use self::Permission::*;
226
227         let other = match other {
228             Item::Permission(perm, _) => perm,
229             Item::FnBarrier(_) => return false, // Remove all barriers -- if they are active, cause UB.
230         };
231
232         match (self, access, other) {
233             // Some cases are impossible.
234             (SharedReadOnly, _, SharedReadWrite) |
235             (SharedReadOnly, _, Unique) =>
236                 bug!("There can never be a SharedReadWrite or a Unique on top of a SharedReadOnly"),
237             // When `other` is `SharedReadOnly`, that is NEVER compatible with
238             // write accesses.
239             // This makes sure read-only pointers become invalid on write accesses.
240             (_, AccessKind::Write { .. }, SharedReadOnly) =>
241                 false,
242             // When `other` is `Unique`, that is compatible with nothing.
243             // This makes sure unique pointers become invalid on incompatible accesses (ensures U2).
244             (_, _, Unique) =>
245                 false,
246             // When we are unique and this is a write/dealloc, we tolerate nothing.
247             // This makes sure we re-assert uniqueness on write accesses.
248             // (This is particularily important such that when a new mutable ref gets created, it gets
249             // pushed into the right item -- this behaves like a write and we assert uniqueness of the
250             // pointer from which this comes, *if* it was a unique pointer.)
251             (Unique, AccessKind::Write { .. }, _) =>
252                 false,
253             // `SharedReadWrite` items can tolerate any other akin items for any kind of access.
254             (SharedReadWrite, _, SharedReadWrite) =>
255                 true,
256             // Any item can tolerate read accesses for shared items.
257             // This includes unique items!  Reads from unique pointers do not invalidate
258             // other pointers.
259             (_, AccessKind::Read, SharedReadWrite) |
260             (_, AccessKind::Read, SharedReadOnly) =>
261                 true,
262             // That's it.
263         }
264     }
265 }
266
267 impl<'tcx> RefKind {
268     /// Defines which kind of access the "parent" must grant to create this reference.
269     fn access(self) -> AccessKind {
270         match self {
271             RefKind::Mutable | RefKind::Shared { frozen: false } => AccessKind::write(),
272             RefKind::Raw | RefKind::Shared { frozen: true } => AccessKind::Read,
273             // FIXME: Just requiring read-only access for raw means that a raw ptr might not be writeable
274             // even when we think it should be!  Think about this some more.
275         }
276     }
277
278     /// This defines the new permission used when a pointer gets created: For raw pointers, whether these are read-only
279     /// or read-write depends on the permission from which they derive.
280     fn new_perm(self, derived_from: Permission) -> EvalResult<'tcx, Permission> {
281         Ok(match (self, derived_from) {
282             // Do not derive writable safe pointer from read-only pointer!
283             (RefKind::Mutable, Permission::SharedReadOnly) =>
284                 return err!(MachineError(format!(
285                     "deriving mutable reference from read-only pointer"
286                 ))),
287             (RefKind::Shared { frozen: false }, Permission::SharedReadOnly) =>
288                 return err!(MachineError(format!(
289                     "deriving shared reference with interior mutability from read-only pointer"
290                 ))),
291             // Safe pointer cases.
292             (RefKind::Mutable, _) => Permission::Unique,
293             (RefKind::Shared { frozen: true }, _) => Permission::SharedReadOnly,
294             (RefKind::Shared { frozen: false }, _) => Permission::SharedReadWrite,
295             // Raw pointer cases.
296             (RefKind::Raw, Permission::SharedReadOnly) => Permission::SharedReadOnly,
297             (RefKind::Raw, _) => Permission::SharedReadWrite,
298         })
299     }
300 }
301
302 /// Core per-location operations: access, create.
303 impl<'tcx> Stack {
304     /// Find the item granting the given kind of access to the given tag, and where that item is in the stack.
305     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<(usize, Permission)> {
306         self.borrows.iter()
307             .enumerate() // we also need to know *where* in the stack
308             .rev() // search top-to-bottom
309             // Return permission of first item that grants access.
310             .filter_map(|(idx, item)| match item {
311                 &Item::Permission(perm, item_tag) if perm.grants(access) && tag == item_tag =>
312                     Some((idx, perm)),
313                 _ => None,
314             })
315             .next()
316     }
317
318     /// Test if a memory `access` using pointer tagged `tag` is granted.
319     /// If yes, return the index of the item that granted it.
320     fn access(
321         &mut self,
322         access: AccessKind,
323         tag: Tag,
324         global: &GlobalState,
325     ) -> EvalResult<'tcx, usize> {
326         // Two main steps: Find granting item, remove all incompatible items above.
327         // Afterwards we just do some post-processing for deallocation accesses.
328
329         // Step 1: Find granting item.
330         let (granting_idx, granting_perm) = self.find_granting(access, tag)
331             .ok_or_else(|| InterpError::MachineError(format!(
332                     "no item granting {} access to tag {} found in borrow stack",
333                     access, tag,
334             )))?;
335         
336         // Step 2: Remove everything incompatible above them.
337         // Implemented with indices because there does not seem to be a nice iterator and range-based
338         // API for this.
339         {
340             let mut cur = granting_idx + 1;
341             while let Some(item) = self.borrows.get(cur) {
342                 if granting_perm.compatible_with(access, *item) {
343                     // Keep this, check next.
344                     cur += 1;
345                 } else {
346                     // Aha! This is a bad one, remove it, and if it is an *active* barrier
347                     // we have a problem.
348                     match self.borrows.remove(cur) {
349                         Item::FnBarrier(call) if global.is_active(call) => {
350                             return err!(MachineError(format!(
351                                 "not granting access because of barrier ({})", call
352                             )));
353                         }
354                         _ => {}
355                     }
356                 }
357             }
358         }
359
360         // Post-processing.
361         // If we got here, we found a matching item. Congratulations!
362         // However, we are not done yet: If this access is deallocating, we must make sure
363         // there are no active barriers remaining on the stack.
364         if access == AccessKind::dealloc() {
365             for &itm in self.borrows.iter().rev() {
366                 match itm {
367                     Item::FnBarrier(call) if global.is_active(call) => {
368                         return err!(MachineError(format!(
369                             "deallocating with active barrier ({})", call
370                         )))
371                     }
372                     _ => {},
373                 }
374             }
375         }
376
377         // Done.
378         return Ok(granting_idx);
379     }
380
381     /// `reborrow` helper function.
382     /// Grant `permisson` to new pointer tagged `tag`, added at `position` in the stack.
383     fn grant(&mut self, perm: Permission, tag: Tag, position: usize) {
384         // Simply add it to the "stack" -- this might add in the middle.
385         // As an optimization, do nothing if the new item is identical to one of its neighbors.
386         let item = Item::Permission(perm, tag);
387         if self.borrows[position-1] == item || self.borrows.get(position) == Some(&item) {
388             // Optimization applies, done.
389             trace!("reborrow: avoiding redundant item {}", item);
390             return;
391         }
392         trace!("reborrow: pushing item {}", item);
393         self.borrows.insert(position, item);
394     }
395
396     /// `reborrow` helper function.
397     /// Adds a barrier.
398     fn barrier(&mut self, call: CallId) {
399         let itm = Item::FnBarrier(call);
400         if *self.borrows.last().unwrap() == itm {
401             // This is just an optimization, no functional change: Avoid stacking
402             // multiple identical barriers on top of each other.
403             // This can happen when a function receives several shared references
404             // that overlap.
405             trace!("reborrow: avoiding redundant extra barrier");
406         } else {
407             trace!("reborrow: pushing barrier for call {}", call);
408             self.borrows.push(itm);
409         }
410     }
411
412     /// `reborrow` helper function: test that the stack invariants are still maintained.
413     fn test_invariants(&self) {
414         let mut saw_shared_read_only = false;
415         for item in self.borrows.iter() {
416             match item {
417                 Item::Permission(Permission::SharedReadOnly, _) => {
418                     saw_shared_read_only = true;
419                 }
420                 Item::Permission(perm, _) if saw_shared_read_only => {
421                     panic!("Found {:?} on top of a SharedReadOnly!", perm);
422                 }
423                 _ => {}
424             }
425         }
426     }
427
428     /// Derived a new pointer from one with the given tag .
429     fn reborrow(
430         &mut self,
431         derived_from: Tag,
432         barrier: Option<CallId>,
433         new_kind: RefKind,
434         new_tag: Tag,
435         global: &GlobalState,
436     ) -> EvalResult<'tcx> {
437         // Find the permission "from which we derive".  To this end we first have to decide
438         // if we derive from a permission that grants writes or just reads.
439         let access = new_kind.access();
440         let (derived_from_idx, derived_from_perm) = self.find_granting(access, derived_from)
441             .ok_or_else(|| InterpError::MachineError(format!(
442                     "no item to reborrow as {} from tag {} found in borrow stack", new_kind, derived_from,
443             )))?;
444         // With this we can compute the permission for the new pointer.
445         let new_perm = new_kind.new_perm(derived_from_perm)?;
446
447         // We behave very differently for the "unsafe" case of a shared-read-write pointer
448         // ("unsafe" because this also applies to shared references with interior mutability).
449         // This is because such pointers may be reborrowed to unique pointers that actually
450         // remain valid when their "parents" get further reborrows!
451         if new_perm == Permission::SharedReadWrite {
452             // A very liberal reborrow because the new pointer does not expect any kind of aliasing guarantee.
453             // Just insert new permission as child of old permission, and maintain everything else.
454             // This inserts "as far down as possible", which is good because it makes this pointer as
455             // long-lived as possible *and* we want all the items that are incompatible with this
456             // to actually get removed from the stack.  If we pushed a `SharedReadWrite` on top of
457             // a `SharedReadOnly`, we'd violate the invariant that `SaredReadOnly` are at the top
458             // and we'd allow write access without invalidating frozen shared references!
459             self.grant(new_perm, new_tag, derived_from_idx+1);
460
461             // No barrier. They can rightfully alias with `&mut`.
462             // FIXME: This means that the `dereferencable` attribute on non-frozen shared references
463             // is incorrect! They are dereferencable when the function is called, but might become
464             // non-dereferencable during the course of execution.
465             // Also see [1], [2].
466             //
467             // [1]: <https://internals.rust-lang.org/t/
468             //       is-it-possible-to-be-memory-safe-with-deallocated-self/8457/8>,
469             // [2]: <https://lists.llvm.org/pipermail/llvm-dev/2018-July/124555.html>
470         } else {
471             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
472             // Here, creating a reference actually counts as an access, and pops incompatible
473             // stuff off the stack.
474             let check_idx = self.access(access, derived_from, global)?;
475             assert_eq!(check_idx, derived_from_idx, "somehow we saw different items??");
476
477             // Now is a good time to add the barrier.
478             if let Some(call) = barrier {
479                 self.barrier(call);
480             }
481
482             // We insert "as far up as possible": We know only compatible items are remaining
483             // on top of `derived_from`, and we want the new item at the top so that we
484             // get the strongest possible guarantees.
485             self.grant(new_perm, new_tag, self.borrows.len());
486         }
487
488         // Make sure that after all this, the stack's invariant is still maintained.
489         if cfg!(debug_assertions) {
490             self.test_invariants();
491         }
492
493         Ok(())
494     }
495 }
496
497 /// Higher-level per-location operations: deref, access, reborrow.
498 impl<'tcx> Stacks {
499     /// Creates new stack with initial tag.
500     pub(crate) fn new(
501         size: Size,
502         tag: Tag,
503         extra: MemoryState,
504     ) -> Self {
505         let item = Item::Permission(Permission::Unique, tag);
506         let stack = Stack {
507             borrows: vec![item],
508         };
509         Stacks {
510             stacks: RefCell::new(RangeMap::new(size, stack)),
511             global: extra,
512         }
513     }
514
515     /// `ptr` got used, reflect that in the stack.
516     fn access(
517         &self,
518         ptr: Pointer<Tag>,
519         size: Size,
520         kind: AccessKind,
521     ) -> EvalResult<'tcx> {
522         trace!("{} access of tag {}: {:?}, size {}", kind, ptr.tag, ptr, size.bytes());
523         // Even reads can have a side-effect, by invalidating other references.
524         // This is fundamentally necessary since `&mut` asserts that there
525         // are no accesses through other references, not even reads.
526         let global = self.global.borrow();
527         let mut stacks = self.stacks.borrow_mut();
528         for stack in stacks.iter_mut(ptr.offset, size) {
529             stack.access(kind, ptr.tag, &*global)?;
530         }
531         Ok(())
532     }
533
534     /// Reborrow the given pointer to the new tag for the given kind of reference.
535     /// This works on `&self` because we might encounter references to constant memory.
536     fn reborrow(
537         &self,
538         ptr: Pointer<Tag>,
539         size: Size,
540         barrier: Option<CallId>,
541         new_kind: RefKind,
542         new_tag: Tag,
543     ) -> EvalResult<'tcx> {
544         trace!(
545             "{} reborrow for tag {} to {}: {:?}, size {}",
546             new_kind, ptr.tag, new_tag, ptr, size.bytes(),
547         );
548         let global = self.global.borrow();
549         let mut stacks = self.stacks.borrow_mut();
550         for stack in stacks.iter_mut(ptr.offset, size) {
551             stack.reborrow(ptr.tag, barrier, new_kind, new_tag, &*global)?;
552         }
553         Ok(())
554     }
555 }
556
557 // # Stacked Borrows Core End
558
559 // Glue code to connect with Miri Machine Hooks
560
561 impl Stacks {
562     pub fn new_allocation(
563         size: Size,
564         extra: &MemoryState,
565         kind: MemoryKind<MiriMemoryKind>,
566     ) -> (Self, Tag) {
567         let tag = match kind {
568             MemoryKind::Stack => {
569                 // New unique borrow. This `Uniq` is not accessible by the program,
570                 // so it will only ever be used when using the local directly (i.e.,
571                 // not through a pointer). That is, whenever we directly use a local, this will pop
572                 // everything else off the stack, invalidating all previous pointers,
573                 // and in particular, *all* raw pointers. This subsumes the explicit
574                 // `reset` which the blog post [1] says to perform when accessing a local.
575                 //
576                 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
577                 Tag::Tagged(extra.borrow_mut().new_ptr())
578             }
579             _ => {
580                 Tag::Untagged
581             }
582         };
583         let stack = Stacks::new(size, tag, Rc::clone(extra));
584         (stack, tag)
585     }
586 }
587
588 impl AllocationExtra<Tag> for Stacks {
589     #[inline(always)]
590     fn memory_read<'tcx>(
591         alloc: &Allocation<Tag, Stacks>,
592         ptr: Pointer<Tag>,
593         size: Size,
594     ) -> EvalResult<'tcx> {
595         alloc.extra.access(ptr, size, AccessKind::Read)
596     }
597
598     #[inline(always)]
599     fn memory_written<'tcx>(
600         alloc: &mut Allocation<Tag, Stacks>,
601         ptr: Pointer<Tag>,
602         size: Size,
603     ) -> EvalResult<'tcx> {
604         alloc.extra.access(ptr, size, AccessKind::write())
605     }
606
607     #[inline(always)]
608     fn memory_deallocated<'tcx>(
609         alloc: &mut Allocation<Tag, Stacks>,
610         ptr: Pointer<Tag>,
611         size: Size,
612     ) -> EvalResult<'tcx> {
613         alloc.extra.access(ptr, size, AccessKind::dealloc())
614     }
615 }
616
617 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
618 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
619     fn reborrow(
620         &mut self,
621         place: MPlaceTy<'tcx, Tag>,
622         size: Size,
623         mutbl: Option<Mutability>,
624         new_tag: Tag,
625         fn_barrier: bool,
626     ) -> EvalResult<'tcx> {
627         let this = self.eval_context_mut();
628         let barrier = if fn_barrier { Some(this.frame().extra) } else { None };
629         let ptr = place.ptr.to_ptr()?;
630         trace!("reborrow: creating new reference for {:?} (pointee {}): {:?}",
631             ptr, place.layout.ty, new_tag);
632
633         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
634         let alloc = this.memory().get(ptr.alloc_id)?;
635         alloc.check_bounds(this, ptr, size)?;
636         // Update the stacks.
637         if mutbl == Some(MutImmutable) {
638             // Reference that cares about freezing. We need a frozen-sensitive reborrow.
639             this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
640                 let new_kind = RefKind::Shared { frozen };
641                 alloc.extra.reborrow(cur_ptr, size, barrier, new_kind, new_tag)
642             })?;
643         } else {
644             // Just treat this as one big chunk.
645             let new_kind = if mutbl == Some(MutMutable) { RefKind::Mutable } else { RefKind::Raw };
646             alloc.extra.reborrow(ptr, size, barrier, new_kind, new_tag)?;
647         }
648         Ok(())
649     }
650
651     /// Retags an indidual pointer, returning the retagged version.
652     /// `mutbl` can be `None` to make this a raw pointer.
653     fn retag_reference(
654         &mut self,
655         val: ImmTy<'tcx, Tag>,
656         mutbl: Option<Mutability>,
657         fn_barrier: bool,
658         two_phase: bool,
659     ) -> EvalResult<'tcx, Immediate<Tag>> {
660         let this = self.eval_context_mut();
661         // We want a place for where the ptr *points to*, so we get one.
662         let place = this.ref_to_mplace(val)?;
663         let size = this.size_and_align_of_mplace(place)?
664             .map(|(size, _)| size)
665             .unwrap_or_else(|| place.layout.size);
666         if size == Size::ZERO {
667             // Nothing to do for ZSTs.
668             return Ok(*val);
669         }
670
671         // Compute new borrow.
672         let new_tag = match mutbl {
673             Some(_) => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
674             None => Tag::Untagged,
675         };
676
677         // Reborrow.
678         this.reborrow(place, size, mutbl, new_tag, fn_barrier)?;
679         let new_place = place.replace_tag(new_tag);
680         // Handle two-phase borrows.
681         if two_phase {
682             assert!(mutbl == Some(MutMutable), "two-phase shared borrows make no sense");
683             // Grant read access *to the parent pointer* with the old tag.  This means the same pointer
684             // has multiple items in the stack now!
685             // FIXME: Think about this some more, in particular about the interaction with cast-to-raw.
686             // Maybe find a better way to express 2-phase, now that we have a "more expressive language"
687             // in the stack.
688             let old_tag = place.ptr.to_ptr().unwrap().tag;
689             this.reborrow(new_place, size, Some(MutImmutable), old_tag, /* fn_barrier: */ false)?;
690         }
691
692         // Return new pointer.
693         Ok(new_place.to_ref())
694     }
695 }
696
697 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
698 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
699     fn retag(
700         &mut self,
701         kind: RetagKind,
702         place: PlaceTy<'tcx, Tag>
703     ) -> EvalResult<'tcx> {
704         let this = self.eval_context_mut();
705         // Determine mutability and whether to add a barrier.
706         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
707         // making it useless.
708         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(Option<Mutability>, bool)> {
709             match ty.sty {
710                 // References are simple.
711                 ty::Ref(_, _, mutbl) => Some((Some(mutbl), kind == RetagKind::FnEntry)),
712                 // Raw pointers need to be enabled.
713                 ty::RawPtr(..) if kind == RetagKind::Raw => Some((None, false)),
714                 // Boxes do not get a barrier: barriers reflect that references outlive the call
715                 // they were passed in to; that's just not the case for boxes.
716                 ty::Adt(..) if ty.is_box() => Some((Some(MutMutable), false)),
717                 _ => None,
718             }
719         }
720
721         // We need a visitor to visit all references. However, that requires
722         // a `MemPlace`, so we have a fast path for reference types that
723         // avoids allocating.
724         if let Some((mutbl, barrier)) = qualify(place.layout.ty, kind) {
725             // Fast path.
726             let val = this.read_immediate(this.place_to_op(place)?)?;
727             let val = this.retag_reference(val, mutbl, barrier, kind == RetagKind::TwoPhase)?;
728             this.write_immediate(val, place)?;
729             return Ok(());
730         }
731         let place = this.force_allocation(place)?;
732
733         let mut visitor = RetagVisitor { ecx: this, kind };
734         visitor.visit_value(place)?;
735
736         // The actual visitor.
737         struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
738             ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
739             kind: RetagKind,
740         }
741         impl<'ecx, 'a, 'mir, 'tcx>
742             MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
743         for
744             RetagVisitor<'ecx, 'a, 'mir, 'tcx>
745         {
746             type V = MPlaceTy<'tcx, Tag>;
747
748             #[inline(always)]
749             fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
750                 &mut self.ecx
751             }
752
753             // Primitives of reference type, that is the one thing we are interested in.
754             fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
755             {
756                 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
757                 // making it useless.
758                 if let Some((mutbl, barrier)) = qualify(place.layout.ty, self.kind) {
759                     let val = self.ecx.read_immediate(place.into())?;
760                     let val = self.ecx.retag_reference(
761                         val,
762                         mutbl,
763                         barrier,
764                         self.kind == RetagKind::TwoPhase
765                     )?;
766                     self.ecx.write_immediate(val, place.into())?;
767                 }
768                 Ok(())
769             }
770         }
771
772         Ok(())
773     }
774 }