miri/concurrency/weak_memory.rs
1//! Implementation of C++11-consistent weak memory emulation using store buffers
2//! based on Dynamic Race Detection for C++ ("the paper"):
3//! <https://www.doc.ic.ac.uk/~afd/homepages/papers/pdfs/2017/POPL.pdf>
4//!
5//! This implementation will never generate weak memory behaviours forbidden by the C++11 model,
6//! but it is incapable of producing all possible weak behaviours allowed by the model. There are
7//! certain weak behaviours observable on real hardware but not while using this.
8//!
9//! Note that this implementation does not fully take into account of C++20's memory model revision to SC accesses
10//! and fences introduced by P0668 (<https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0668r5.html>).
11//! This implementation is not fully correct under the revised C++20 model and may generate behaviours C++20
12//! disallows (<https://github.com/rust-lang/miri/issues/2301>).
13//!
14//! Modifications are made to the paper's model to address C++20 changes:
15//! - If an SC load reads from an atomic store of any ordering, then a later SC load cannot read
16//! from an earlier store in the location's modification order. This is to prevent creating a
17//! backwards S edge from the second load to the first, as a result of C++20's coherence-ordered
18//! before rules. (This seems to rule out behaviors that were actually permitted by the RC11 model
19//! that C++20 intended to copy (<https://plv.mpi-sws.org/scfix/paper.pdf>); a change was
20//! introduced when translating the math to English. According to Viktor Vafeiadis, this
21//! difference is harmless. So we stick to what the standard says, and allow fewer behaviors.)
22//! - SC fences are treated like AcqRel RMWs to a global clock, to ensure they induce enough
23//! synchronization with the surrounding accesses. This rules out legal behavior, but it is really
24//! hard to be more precise here.
25//!
26//! Rust follows the C++20 memory model (except for the Consume ordering and some operations not performable through C++'s
27//! `std::atomic<T>` API). It is therefore possible for this implementation to generate behaviours never observable when the
28//! same program is compiled and run natively. Unfortunately, no literature exists at the time of writing which proposes
29//! an implementable and C++20-compatible relaxed memory model that supports all atomic operation existing in Rust. The closest one is
30//! A Promising Semantics for Relaxed-Memory Concurrency by Jeehoon Kang et al. (<https://www.cs.tau.ac.il/~orilahav/papers/popl17.pdf>)
31//! However, this model lacks SC accesses and is therefore unusable by Miri (SC accesses are everywhere in library code).
32//!
33//! If you find anything that proposes a relaxed memory model that is C++20-consistent, supports all orderings Rust's atomic accesses
34//! and fences accept, and is implementable (with operational semantics), please open a GitHub issue!
35//!
36//! One characteristic of this implementation, in contrast to some other notable operational models such as ones proposed in
37//! Taming Release-Acquire Consistency by Ori Lahav et al. (<https://plv.mpi-sws.org/sra/paper.pdf>) or Promising Semantics noted above,
38//! is that this implementation does not require each thread to hold an isolated view of the entire memory. Here, store buffers are per-location
39//! and shared across all threads. This is more memory efficient but does require store elements (representing writes to a location) to record
40//! information about reads, whereas in the other two models it is the other way round: reads points to the write it got its value from.
41//! Additionally, writes in our implementation do not have globally unique timestamps attached. In the other two models this timestamp is
42//! used to make sure a value in a thread's view is not overwritten by a write that occurred earlier than the one in the existing view.
43//! In our implementation, this is detected using read information attached to store elements, as there is no data structure representing reads.
44//!
45//! The C++ memory model is built around the notion of an 'atomic object', so it would be natural
46//! to attach store buffers to atomic objects. However, Rust follows LLVM in that it only has
47//! 'atomic accesses'. Therefore Miri cannot know when and where atomic 'objects' are being
48//! created or destroyed, to manage its store buffers. Instead, we hence lazily create an
49//! atomic object on the first atomic write to a given region, and we destroy that object
50//! on the next non-atomic or imperfectly overlapping atomic write to that region.
51//! These lazy (de)allocations happen in memory_accessed() on non-atomic accesses, and
52//! get_or_create_store_buffer_mut() on atomic writes.
53//!
54//! One consequence of this difference is that safe/sound Rust allows for more operations on atomic locations
55//! than the C++20 atomic API was intended to allow, such as non-atomically accessing
56//! a previously atomically accessed location, or accessing previously atomically accessed locations with a differently sized operation
57//! (such as accessing the top 16 bits of an AtomicU32). These scenarios are generally undiscussed in formalizations of C++ memory model.
58//! In Rust, these operations can only be done through a `&mut AtomicFoo` reference or one derived from it, therefore these operations
59//! can only happen after all previous accesses on the same locations. This implementation is adapted to allow these operations.
60//! A mixed atomicity read that races with writes, or a write that races with reads or writes will still cause UBs to be thrown.
61//! Mixed size atomic accesses must not race with any other atomic access, whether read or write, or a UB will be thrown.
62//! You can refer to test cases in weak_memory/extra_cpp.rs and weak_memory/extra_cpp_unsafe.rs for examples of these operations.
63
64// Our and the author's own implementation (tsan11) of the paper have some deviations from the provided operational semantics in §5.3:
65// 1. In the operational semantics, loads acquire the vector clock of the atomic location
66// irrespective of which store buffer element is loaded. That's incorrect; the synchronization clock
67// needs to be tracked per-store-buffer-element. (The paper has a field "clocks" for that purpose,
68// but it is not actuallt used.) tsan11 does this correctly
69// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L305).
70//
71// 2. In the operational semantics, each store element keeps the timestamp of a thread when it loads from the store.
72// If the same thread loads from the same store element multiple times, then the timestamps at all loads are saved in a list of load elements.
73// This is not necessary as later loads by the same thread will always have greater timestamp values, so we only need to record the timestamp of the first
74// load by each thread. This optimisation is done in tsan11
75// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.h#L35-L37)
76// and here.
77//
78// 3. §4.5 of the paper wants an SC store to mark all existing stores in the buffer that happens before it
79// as SC. This is not done in the operational semantics but implemented correctly in tsan11
80// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L160-L167)
81// and here.
82//
83// 4. W_SC ; R_SC case requires the SC load to ignore all but last store marked SC (stores not marked SC are not
84// affected). But this rule is applied to all loads in ReadsFromSet from the paper (last two lines of code), not just SC load.
85// This is implemented correctly in tsan11
86// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L295)
87// and here.
88
89use std::cell::{Ref, RefCell};
90use std::collections::VecDeque;
91
92use rustc_data_structures::fx::FxHashMap;
93
94use super::AllocDataRaceHandler;
95use super::data_race::{GlobalState as DataRaceState, ThreadClockSet};
96use super::vector_clock::{VClock, VTimestamp, VectorIdx};
97use crate::concurrency::GlobalDataRaceHandler;
98use crate::data_structures::range_object_map::{AccessType, RangeObjectMap};
99use crate::*;
100
101pub type AllocState = StoreBufferAlloc;
102
103// Each store buffer must be bounded otherwise it will grow indefinitely.
104// However, bounding the store buffer means restricting the amount of weak
105// behaviours observable. The author picked 128 as a good tradeoff
106// so we follow them here.
107const STORE_BUFFER_LIMIT: usize = 128;
108
109#[derive(Debug, Clone)]
110pub struct StoreBufferAlloc {
111 /// Store buffer of each atomic object in this allocation
112 // Behind a RefCell because we need to allocate/remove on read access
113 store_buffers: RefCell<RangeObjectMap<StoreBuffer>>,
114}
115
116impl VisitProvenance for StoreBufferAlloc {
117 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
118 let Self { store_buffers } = self;
119 for val in store_buffers
120 .borrow()
121 .iter()
122 .flat_map(|buf| buf.buffer.iter().map(|element| &element.val))
123 {
124 val.visit_provenance(visit);
125 }
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub(super) struct StoreBuffer {
131 // Stores to this location in modification order
132 buffer: VecDeque<StoreElement>,
133}
134
135/// Whether a load returned the latest value or not.
136#[derive(PartialEq, Eq)]
137enum LoadRecency {
138 Latest,
139 Outdated,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
143struct StoreElement {
144 /// The thread that performed the store.
145 store_thread: VectorIdx,
146 /// The timestamp of the storing thread when it performed the store
147 store_timestamp: VTimestamp,
148
149 /// The vector clock that can be acquired by loading this store.
150 sync_clock: VClock,
151
152 /// Whether this store is SC.
153 is_seqcst: bool,
154
155 /// The value of this store. `None` means uninitialized.
156 // FIXME: Currently, we cannot represent partial initialization.
157 val: Option<Scalar>,
158
159 /// Metadata about loads from this store element,
160 /// behind a RefCell to keep load op take &self
161 load_info: RefCell<LoadInfo>,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Default)]
165struct LoadInfo {
166 /// Timestamp of first loads from this store element by each thread.
167 timestamps: FxHashMap<VectorIdx, VTimestamp>,
168 /// Whether this store element has been read by an SC load.
169 /// This is crucial to ensure we respect coherence-ordered-before. Concretely we use
170 /// this to ensure that if a store element is seen by an SC load, then all later SC loads
171 /// cannot see `mo`-earlier store elements.
172 sc_loaded: bool,
173}
174
175impl StoreBufferAlloc {
176 pub fn new_allocation() -> Self {
177 Self { store_buffers: RefCell::new(RangeObjectMap::new()) }
178 }
179
180 /// When a non-atomic write happens on a location that has been atomically accessed
181 /// before without data race, we can determine that the non-atomic write fully happens
182 /// after all the prior atomic writes so the location no longer needs to exhibit
183 /// any weak memory behaviours until further atomic writes.
184 pub fn non_atomic_write(&self, range: AllocRange, global: &DataRaceState) {
185 if !global.ongoing_action_data_race_free() {
186 let mut buffers = self.store_buffers.borrow_mut();
187 let access_type = buffers.access_type(range);
188 match access_type {
189 AccessType::PerfectlyOverlapping(pos) => {
190 buffers.remove_from_pos(pos);
191 }
192 AccessType::ImperfectlyOverlapping(pos_range) => {
193 // We rely on the data-race check making sure this is synchronized.
194 // Therefore we can forget about the old data here.
195 buffers.remove_pos_range(pos_range);
196 }
197 AccessType::Empty(_) => {
198 // The range had no weak behaviours attached, do nothing
199 }
200 }
201 }
202 }
203
204 /// Gets a store buffer associated with an atomic object in this allocation.
205 /// Returns `None` if there is no store buffer.
206 fn get_store_buffer<'tcx>(
207 &self,
208 range: AllocRange,
209 ) -> InterpResult<'tcx, Option<Ref<'_, StoreBuffer>>> {
210 let access_type = self.store_buffers.borrow().access_type(range);
211 let AccessType::PerfectlyOverlapping(pos) = access_type else {
212 // If there is nothing here yet, that means there wasn't an atomic write yet so
213 // we can't return anything outdated.
214 return interp_ok(None);
215 };
216 let store_buffer = Ref::map(self.store_buffers.borrow(), |buffer| &buffer[pos]);
217 interp_ok(Some(store_buffer))
218 }
219
220 /// Gets a mutable store buffer associated with an atomic object in this allocation,
221 /// or creates one with the specified initial value if no atomic object exists yet.
222 fn get_or_create_store_buffer_mut<'tcx>(
223 &mut self,
224 range: AllocRange,
225 init: Result<Option<Scalar>, ()>,
226 ) -> InterpResult<'tcx, &mut StoreBuffer> {
227 let buffers = self.store_buffers.get_mut();
228 let access_type = buffers.access_type(range);
229 let pos = match access_type {
230 AccessType::PerfectlyOverlapping(pos) => pos,
231 AccessType::Empty(pos) => {
232 let init =
233 init.expect("cannot have empty store buffer when previous write was atomic");
234 buffers.insert_at_pos(pos, range, StoreBuffer::new(init));
235 pos
236 }
237 AccessType::ImperfectlyOverlapping(pos_range) => {
238 // Once we reach here we would've already checked that this access is not racy.
239 let init = init.expect(
240 "cannot have partially overlapping store buffer when previous write was atomic",
241 );
242 buffers.remove_pos_range(pos_range.clone());
243 buffers.insert_at_pos(pos_range.start, range, StoreBuffer::new(init));
244 pos_range.start
245 }
246 };
247 interp_ok(&mut buffers[pos])
248 }
249}
250
251impl<'tcx> StoreBuffer {
252 fn new(init: Option<Scalar>) -> Self {
253 let mut buffer = VecDeque::new();
254 let store_elem = StoreElement {
255 // The thread index and timestamp of the initialisation write
256 // are never meaningfully used, so it's fine to leave them as 0
257 store_thread: VectorIdx::from(0),
258 store_timestamp: VTimestamp::ZERO,
259 // The initialization write is non-atomic so nothing can be acquired.
260 sync_clock: VClock::default(),
261 val: init,
262 is_seqcst: false,
263 load_info: RefCell::new(LoadInfo::default()),
264 };
265 buffer.push_back(store_elem);
266 Self { buffer }
267 }
268
269 /// Reads from the last store in modification order, if any.
270 fn read_from_last_store(
271 &self,
272 global: &DataRaceState,
273 thread_mgr: &ThreadManager<'_>,
274 is_seqcst: bool,
275 ) {
276 let store_elem = self.buffer.back();
277 if let Some(store_elem) = store_elem {
278 let (index, clocks) = global.active_thread_state(thread_mgr);
279 store_elem.load_impl(index, &clocks, is_seqcst);
280 }
281 }
282
283 fn buffered_read(
284 &self,
285 global: &DataRaceState,
286 thread_mgr: &ThreadManager<'_>,
287 is_seqcst: bool,
288 rng: &mut (impl rand::Rng + ?Sized),
289 validate: impl FnOnce(Option<&VClock>) -> InterpResult<'tcx>,
290 ) -> InterpResult<'tcx, (Option<Scalar>, LoadRecency)> {
291 // Having a live borrow to store_buffer while calling validate_atomic_load is fine
292 // because the race detector doesn't touch store_buffer
293
294 let (store_elem, recency) = {
295 // The `clocks` we got here must be dropped before calling validate_atomic_load
296 // as the race detector will update it
297 let (.., clocks) = global.active_thread_state(thread_mgr);
298 // Load from a valid entry in the store buffer
299 self.fetch_store(is_seqcst, &clocks, &mut *rng)
300 };
301
302 // Unlike in buffered_atomic_write, thread clock updates have to be done
303 // after we've picked a store element from the store buffer, as presented
304 // in ATOMIC LOAD rule of the paper. This is because fetch_store
305 // requires access to ThreadClockSet.clock, which is updated by the race detector
306 validate(Some(&store_elem.sync_clock))?;
307
308 let (index, clocks) = global.active_thread_state(thread_mgr);
309 let loaded = store_elem.load_impl(index, &clocks, is_seqcst);
310 interp_ok((loaded, recency))
311 }
312
313 fn buffered_write(
314 &mut self,
315 val: Scalar,
316 global: &DataRaceState,
317 thread_mgr: &ThreadManager<'_>,
318 is_seqcst: bool,
319 sync_clock: VClock,
320 ) -> InterpResult<'tcx> {
321 let (index, clocks) = global.active_thread_state(thread_mgr);
322
323 self.store_impl(val, index, &clocks.clock, is_seqcst, sync_clock);
324 interp_ok(())
325 }
326
327 /// Selects a valid store element in the buffer.
328 fn fetch_store<R: rand::Rng + ?Sized>(
329 &self,
330 is_seqcst: bool,
331 clocks: &ThreadClockSet,
332 rng: &mut R,
333 ) -> (&StoreElement, LoadRecency) {
334 use rand::seq::IteratorRandom;
335 let mut found_sc = false;
336 // FIXME: we want an inclusive take_while (stops after a false predicate, but
337 // includes the element that gave the false), but such function doesn't yet
338 // exist in the standard library https://github.com/rust-lang/rust/issues/62208
339 // so we have to hack around it with keep_searching
340 let mut keep_searching = true;
341 let candidates = self
342 .buffer
343 .iter()
344 .rev()
345 .take_while(move |&store_elem| {
346 if !keep_searching {
347 return false;
348 }
349
350 keep_searching = if store_elem.store_timestamp
351 <= clocks.clock[store_elem.store_thread]
352 {
353 // CoWR: if a store happens-before the current load,
354 // then we can't read-from anything earlier in modification order.
355 // C++20 §6.9.2.2 [intro.races] paragraph 18
356 false
357 } else if store_elem.load_info.borrow().timestamps.iter().any(
358 |(&load_index, &load_timestamp)| load_timestamp <= clocks.clock[load_index],
359 ) {
360 // CoRR: if there was a load from this store which happened-before the current load,
361 // then we cannot read-from anything earlier in modification order.
362 // C++20 §6.9.2.2 [intro.races] paragraph 16
363 false
364 } else if store_elem.store_timestamp <= clocks.write_seqcst[store_elem.store_thread]
365 && store_elem.is_seqcst
366 {
367 // The current non-SC load, which may be sequenced-after an SC fence,
368 // cannot read-before the last SC store executed before the fence.
369 // C++17 §32.4 [atomics.order] paragraph 4
370 false
371 } else if is_seqcst
372 && store_elem.store_timestamp <= clocks.read_seqcst[store_elem.store_thread]
373 {
374 // The current SC load cannot read-before the last store sequenced-before
375 // the last SC fence.
376 // C++17 §32.4 [atomics.order] paragraph 5
377 false
378 } else if is_seqcst && store_elem.load_info.borrow().sc_loaded {
379 // The current SC load cannot read-before a store that an earlier SC load has observed.
380 // See https://github.com/rust-lang/miri/issues/2301#issuecomment-1222720427.
381 // Consequences of C++20 §31.4 [atomics.order] paragraph 3.1, 3.3 (coherence-ordered before)
382 // and 4.1 (coherence-ordered before between SC makes global total order S).
383 false
384 } else {
385 true
386 };
387
388 true
389 })
390 .filter(|&store_elem| {
391 if is_seqcst && store_elem.is_seqcst {
392 // An SC load needs to ignore all but last store maked SC (stores not marked SC are not
393 // affected)
394 let include = !found_sc;
395 found_sc = true;
396 include
397 } else {
398 true
399 }
400 });
401
402 let chosen = candidates.choose(rng).expect("store buffer cannot be empty");
403 if std::ptr::eq(chosen, self.buffer.back().expect("store buffer cannot be empty")) {
404 (chosen, LoadRecency::Latest)
405 } else {
406 (chosen, LoadRecency::Outdated)
407 }
408 }
409
410 /// ATOMIC STORE IMPL in the paper
411 fn store_impl(
412 &mut self,
413 val: Scalar,
414 index: VectorIdx,
415 thread_clock: &VClock,
416 is_seqcst: bool,
417 sync_clock: VClock,
418 ) {
419 let store_elem = StoreElement {
420 store_thread: index,
421 store_timestamp: thread_clock[index],
422 sync_clock,
423 // In the language provided in the paper, an atomic store takes the value from a
424 // non-atomic memory location.
425 // But we already have the immediate value here so we don't need to do the memory
426 // access.
427 val: Some(val),
428 is_seqcst,
429 load_info: RefCell::new(LoadInfo::default()),
430 };
431 if self.buffer.len() >= STORE_BUFFER_LIMIT {
432 self.buffer.pop_front();
433 }
434 self.buffer.push_back(store_elem);
435 if is_seqcst {
436 // Every store that happens before this needs to be marked as SC
437 // so that in a later SC load, only the last SC store (i.e. this one) or stores that
438 // aren't ordered by hb with the last SC is picked.
439 self.buffer.iter_mut().rev().for_each(|elem| {
440 if elem.store_timestamp <= thread_clock[elem.store_thread] {
441 elem.is_seqcst = true;
442 }
443 })
444 }
445 }
446}
447
448impl StoreElement {
449 /// ATOMIC LOAD IMPL in the paper
450 /// Unlike the operational semantics in the paper, we don't need to keep track
451 /// of the thread timestamp for every single load. Keeping track of the first (smallest)
452 /// timestamp of each thread that has loaded from a store is sufficient: if the earliest
453 /// load of another thread happens before the current one, then we must stop searching the store
454 /// buffer regardless of subsequent loads by the same thread; if the earliest load of another
455 /// thread doesn't happen before the current one, then no subsequent load by the other thread
456 /// can happen before the current one.
457 fn load_impl(
458 &self,
459 index: VectorIdx,
460 clocks: &ThreadClockSet,
461 is_seqcst: bool,
462 ) -> Option<Scalar> {
463 let mut load_info = self.load_info.borrow_mut();
464 load_info.sc_loaded |= is_seqcst;
465 let _ = load_info.timestamps.try_insert(index, clocks.clock[index]);
466 self.val
467 }
468}
469
470impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
471pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
472 fn buffered_atomic_rmw(
473 &mut self,
474 new_val: Scalar,
475 place: &MPlaceTy<'tcx>,
476 atomic: AtomicRwOrd,
477 init: Scalar,
478 ) -> InterpResult<'tcx> {
479 let this = self.eval_context_mut();
480 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
481 if let (
482 crate::AllocExtra {
483 data_race: AllocDataRaceHandler::Vclocks(data_race_clocks, Some(alloc_buffers)),
484 ..
485 },
486 crate::MiriMachine {
487 data_race: GlobalDataRaceHandler::Vclocks(global), threads, ..
488 },
489 ) = this.get_alloc_extra_mut(alloc_id)?
490 {
491 if atomic == AtomicRwOrd::SeqCst {
492 global.sc_read(threads);
493 global.sc_write(threads);
494 }
495 let range = alloc_range(base_offset, place.layout.size);
496 let sync_clock = data_race_clocks.sync_clock(range);
497 let buffer = alloc_buffers.get_or_create_store_buffer_mut(range, Ok(Some(init)))?;
498 // The RMW always reads from the most recent store.
499 buffer.read_from_last_store(global, threads, atomic == AtomicRwOrd::SeqCst);
500 buffer.buffered_write(
501 new_val,
502 global,
503 threads,
504 atomic == AtomicRwOrd::SeqCst,
505 sync_clock,
506 )?;
507 }
508 interp_ok(())
509 }
510
511 /// The argument to `validate` is the synchronization clock of the memory that is being read,
512 /// if we are reading from a store buffer element.
513 fn buffered_atomic_read(
514 &self,
515 place: &MPlaceTy<'tcx>,
516 atomic: AtomicReadOrd,
517 latest_in_mo: Scalar,
518 validate: impl FnOnce(Option<&VClock>) -> InterpResult<'tcx>,
519 ) -> InterpResult<'tcx, Option<Scalar>> {
520 let this = self.eval_context_ref();
521 'fallback: {
522 if let Some(global) = this.machine.data_race.as_vclocks_ref() {
523 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
524 if let Some(alloc_buffers) =
525 this.get_alloc_extra(alloc_id)?.data_race.as_weak_memory_ref()
526 {
527 if atomic == AtomicReadOrd::SeqCst {
528 global.sc_read(&this.machine.threads);
529 }
530 let mut rng = this.machine.rng.borrow_mut();
531 let Some(buffer) = alloc_buffers
532 .get_store_buffer(alloc_range(base_offset, place.layout.size))?
533 else {
534 // No old writes available, fall back to base case.
535 break 'fallback;
536 };
537 let (loaded, recency) = buffer.buffered_read(
538 global,
539 &this.machine.threads,
540 atomic == AtomicReadOrd::SeqCst,
541 &mut *rng,
542 validate,
543 )?;
544 if global.track_outdated_loads && recency == LoadRecency::Outdated {
545 this.emit_diagnostic(NonHaltingDiagnostic::WeakMemoryOutdatedLoad {
546 ptr: place.ptr(),
547 });
548 }
549
550 return interp_ok(loaded);
551 }
552 }
553 }
554
555 // Race detector or weak memory disabled, simply read the latest value
556 validate(None)?;
557 interp_ok(Some(latest_in_mo))
558 }
559
560 /// Add the given write to the store buffer. (Does not change machine memory.)
561 ///
562 /// `init` says with which value to initialize the store buffer in case there wasn't a store
563 /// buffer for this memory range before. `Err(())` means the value is not available;
564 /// `Ok(None)` means the memory does not contain a valid scalar.
565 ///
566 /// Must be called *after* `validate_atomic_store` to ensure that `sync_clock` is up-to-date.
567 fn buffered_atomic_write(
568 &mut self,
569 val: Scalar,
570 dest: &MPlaceTy<'tcx>,
571 atomic: AtomicWriteOrd,
572 init: Result<Option<Scalar>, ()>,
573 ) -> InterpResult<'tcx> {
574 let this = self.eval_context_mut();
575 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(dest.ptr(), 0)?;
576 if let (
577 crate::AllocExtra {
578 data_race: AllocDataRaceHandler::Vclocks(data_race_clocks, Some(alloc_buffers)),
579 ..
580 },
581 crate::MiriMachine {
582 data_race: GlobalDataRaceHandler::Vclocks(global), threads, ..
583 },
584 ) = this.get_alloc_extra_mut(alloc_id)?
585 {
586 if atomic == AtomicWriteOrd::SeqCst {
587 global.sc_write(threads);
588 }
589
590 let range = alloc_range(base_offset, dest.layout.size);
591 // It's a bit annoying that we have to go back to the data race part to get the clock...
592 // but it does make things a lot simpler.
593 let sync_clock = data_race_clocks.sync_clock(range);
594 let buffer = alloc_buffers.get_or_create_store_buffer_mut(range, init)?;
595 buffer.buffered_write(
596 val,
597 global,
598 threads,
599 atomic == AtomicWriteOrd::SeqCst,
600 sync_clock,
601 )?;
602 }
603
604 // Caller should've written to dest with the vanilla scalar write, we do nothing here
605 interp_ok(())
606 }
607
608 /// Caller should never need to consult the store buffer for the latest value.
609 /// This function is used exclusively for failed atomic_compare_exchange_scalar
610 /// to perform load_impl on the latest store element
611 fn perform_read_on_buffered_latest(
612 &self,
613 place: &MPlaceTy<'tcx>,
614 atomic: AtomicReadOrd,
615 ) -> InterpResult<'tcx> {
616 let this = self.eval_context_ref();
617
618 if let Some(global) = this.machine.data_race.as_vclocks_ref() {
619 if atomic == AtomicReadOrd::SeqCst {
620 global.sc_read(&this.machine.threads);
621 }
622 let size = place.layout.size;
623 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
624 if let Some(alloc_buffers) =
625 this.get_alloc_extra(alloc_id)?.data_race.as_weak_memory_ref()
626 {
627 let Some(buffer) =
628 alloc_buffers.get_store_buffer(alloc_range(base_offset, size))?
629 else {
630 // No store buffer, nothing to do.
631 return interp_ok(());
632 };
633 buffer.read_from_last_store(
634 global,
635 &this.machine.threads,
636 atomic == AtomicReadOrd::SeqCst,
637 );
638 }
639 }
640 interp_ok(())
641 }
642}