Skip to main content

rucc_ir/
flags.rs

1//! Instruction flags, atomic orderings, and the read-modify-write operations.
2//!
3//! Design: `spec/08-ir.md` section 8.4.
4//!
5//! Nearly every flag is a licence the frontend grants the optimizer, and each of those is tied to
6//! something the C standard leaves undefined. `-fwrapv` is implemented by not setting
7//! [`Flags::NSW`], and that is the whole of it.
8//!
9//! [`Flags::NOFREE`] and [`Flags::STATIC`] are the two that are not licences. Each is a fact worked
10//! out over the whole module and written onto the instruction it is about, because a pass is given
11//! one function and neither fact is in it: what a call reaches belongs to the callee, and how big a
12//! global is belongs to the module. The frontend does the same thing with a call that never comes
13//! back: it puts an `unreachable` after it rather than expecting every later pass to go and look
14//! the callee up.
15//!
16//! **There is no poison.** An `add nsw` that overflows does not produce a value that taints
17//! everything downstream. It produces an unspecified but stable value, meaning two reads of it
18//! agree, and `nsw` licenses only the specific rewrites the rule set proves sound under the
19//! assumption that the overflow does not happen. The cost is real, and it is that arithmetic
20//! cannot be speculated across control flow as aggressively. The benefit is that every rewrite
21//! is locally justifiable, which is what keeps the rule set verifiable, and that a wrong answer
22//! cannot travel from somewhere the user cannot see to somewhere they can.
23//!
24//! The fast-math flags sit on individual instructions rather than in a global mode, so
25//! `-ffast-math` is a decision the frontend makes per expression. That is what keeps link time
26//! optimization across a unit built with it and a unit built without it correct.
27
28use std::fmt;
29
30use crate::Opcode;
31
32/// The flags on one instruction.
33///
34/// A bitset rather than a struct of `bool`s, because it rides along in the instruction table
35/// and two bytes there is two bytes per instruction in every function in the program.
36#[derive(Clone, Copy, PartialEq, Eq, Default, Hash)]
37pub struct Flags(u16);
38
39impl Flags {
40    /// No flags, which is what `-O0` and `-fwrapv` and a plain unsigned addition all produce.
41    pub const NONE: Self = Self(0);
42
43    /// No signed wrap. Signed overflow is undefined, so the optimizer may assume it does not
44    /// happen. `-fwrapv` stops the frontend setting this and nothing else changes.
45    pub const NSW: Self = Self(1 << 0);
46    /// No unsigned wrap. Set only where the frontend knows it from the source, since C's
47    /// unsigned arithmetic wraps by definition and most unsigned arithmetic does not get this.
48    pub const NUW: Self = Self(1 << 1);
49    /// The shift or division is exact, so no bits are discarded and no remainder is dropped.
50    pub const EXACT: Self = Self(1 << 2);
51
52    /// No NaN operands or results.
53    pub const NNAN: Self = Self(1 << 3);
54    /// No infinite operands or results.
55    pub const NINF: Self = Self(1 << 4);
56    /// The sign of a zero does not matter.
57    pub const NSZ: Self = Self(1 << 5);
58    /// A division may become a multiplication by the reciprocal.
59    pub const ARCP: Self = Self(1 << 6);
60    /// A multiplication and an addition may be contracted into one rounding.
61    pub const CONTRACT: Self = Self(1 << 7);
62    /// The operation may be reassociated, which is the one that changes results the most.
63    pub const REASSOC: Self = Self(1 << 8);
64
65    /// The access is `volatile`, so it happens exactly once and is never moved or merged.
66    pub const VOLATILE: Self = Self(1 << 9);
67    /// The result does not alias anything else reachable, which is what `restrict` gives.
68    pub const NOALIAS: Self = Self(1 << 10);
69
70    /// Nothing this call reaches ends the lifetime of any storage.
71    ///
72    /// The `nofree` summary of `spec/safe-memory/07-check-elimination.md` section 7.5, written onto
73    /// the call site by a module-level analysis rather than by the frontend. A pass carrying what
74    /// an earlier safety check established keeps it across a call that has this and gives it up
75    /// across a call that does not.
76    pub const NOFREE: Self = Self(1 << 11);
77
78    /// The bytes this safety check is about lie inside one object of static storage duration
79    /// whose extent this module knows.
80    ///
81    /// Section 7.2 of `spec/safe-memory/07-check-elimination.md` puts the frontend first of the
82    /// four sources of a discharge, because most accesses in real C are to a local or a global at a
83    /// constant offset and how big either one is is not something anybody has to work out. The
84    /// local half is read straight off the `alloca` by the pass that removes the check. The global
85    /// half is this flag, because a global's size lives on the module and a pass is given one
86    /// function, so a module-level analysis works it out before the pipeline starts and writes it
87    /// onto the check.
88    ///
89    /// A fact rather than a licence, like [`Flags::NOFREE`] and unlike everything above it. It
90    /// says what is true of the bytes, and whether that is enough for the check to go is a rule.
91    pub const STATIC: Self = Self(1 << 12);
92
93    /// Every fast-math flag, which is what `-ffast-math` sets on an expression.
94    pub const FAST: Self = Self(
95        Self::NNAN.0
96            | Self::NINF.0
97            | Self::NSZ.0
98            | Self::ARCP.0
99            | Self::CONTRACT.0
100            | Self::REASSOC.0,
101    );
102
103    /// The underlying bits, for the printer and for hashing an instruction.
104    #[must_use]
105    pub const fn bits(self) -> u16 {
106        self.0
107    }
108
109    /// Whether nothing is set.
110    #[must_use]
111    pub const fn is_empty(self) -> bool {
112        self.0 == 0
113    }
114
115    /// Whether every flag in `other` is set here.
116    #[must_use]
117    pub const fn contains(self, other: Self) -> bool {
118        self.0 & other.0 == other.0
119    }
120
121    /// Both sets.
122    #[must_use]
123    pub const fn union(self, other: Self) -> Self {
124        Self(self.0 | other.0)
125    }
126
127    /// The flags in both sets.
128    ///
129    /// This is what a rewrite does when it replaces two instructions with one: a licence
130    /// granted on one of them and not the other is not a licence over the result.
131    #[must_use]
132    pub const fn intersection(self, other: Self) -> Self {
133        Self(self.0 & other.0)
134    }
135
136    /// This set without the flags in `other`.
137    #[must_use]
138    pub const fn without(self, other: Self) -> Self {
139        Self(self.0 & !other.0)
140    }
141
142    /// The flags that mean anything on that opcode.
143    ///
144    /// Anything outside this is a verifier failure rather than something ignored, because a
145    /// flag on an instruction that does not read it is a flag somebody meant to put somewhere
146    /// else.
147    #[must_use]
148    pub const fn legal_on(opcode: Opcode) -> Self {
149        match opcode {
150            Opcode::Add | Opcode::Sub | Opcode::Mul | Opcode::Shl => Self::NSW.union(Self::NUW),
151            Opcode::SDiv | Opcode::UDiv | Opcode::LShr | Opcode::AShr => Self::EXACT,
152            Opcode::FAdd
153            | Opcode::FSub
154            | Opcode::FMul
155            | Opcode::FDiv
156            | Opcode::FRem
157            | Opcode::FNeg
158            | Opcode::Fma
159            | Opcode::FCmp => Self::FAST,
160            Opcode::Load | Opcode::Store | Opcode::Memcpy | Opcode::Memmove | Opcode::Memset => {
161                Self::VOLATILE
162            }
163            Opcode::InlineAsm => Self::VOLATILE,
164            // On all three spellings of a call, including the indirect one. Nothing works out
165            // `nofree` for a call through an address today, and the flag is legal there because
166            // what it says is about the functions the call reaches rather than about how the call
167            // names them, so a later analysis that knows the targets has somewhere to write it.
168            Opcode::Call | Opcode::TailCall | Opcode::CallIndirect => Self::NOFREE,
169            // On the three checks `rucc-safety` emits and on nothing else. What it says is about
170            // the bytes a check names, so an instruction that names no bytes has no room for it.
171            Opcode::CheckBounds | Opcode::CheckLive | Opcode::CheckDeriv => Self::STATIC,
172            Opcode::Alloca | Opcode::PtrAdd => Self::NOALIAS,
173            _ => Self::NONE,
174        }
175    }
176
177    /// Every flag that is set, with its name, in the order the printer writes them.
178    pub fn iter(self) -> impl Iterator<Item = (Self, &'static str)> {
179        NAMED.iter().copied().filter(move |&(flag, _)| self.contains(flag))
180    }
181
182    /// The flag with that name, if there is one.
183    #[must_use]
184    pub fn from_name(name: &str) -> Option<Self> {
185        NAMED.iter().find(|&&(_, named)| named == name).map(|&(flag, _)| flag)
186    }
187}
188
189impl std::ops::BitOr for Flags {
190    type Output = Self;
191
192    fn bitor(self, other: Self) -> Self {
193        self.union(other)
194    }
195}
196
197impl std::ops::BitOrAssign for Flags {
198    fn bitor_assign(&mut self, other: Self) {
199        *self = self.union(other);
200    }
201}
202
203impl fmt::Display for Flags {
204    /// The suffix form the textual IR uses, `add.nsw`, with a leading dot on each flag and
205    /// nothing at all when the set is empty.
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        for (_, name) in self.iter() {
208            write!(f, ".{name}")?;
209        }
210        Ok(())
211    }
212}
213
214impl fmt::Debug for Flags {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        if self.is_empty() {
217            return f.write_str("Flags::NONE");
218        }
219        fmt::Display::fmt(self, f)
220    }
221}
222
223/// Each flag with its name, in printing order.
224static NAMED: &[(Flags, &str)] = &[
225    (Flags::NSW, "nsw"),
226    (Flags::NUW, "nuw"),
227    (Flags::EXACT, "exact"),
228    (Flags::NNAN, "nnan"),
229    (Flags::NINF, "ninf"),
230    (Flags::NSZ, "nsz"),
231    (Flags::ARCP, "arcp"),
232    (Flags::CONTRACT, "contract"),
233    (Flags::REASSOC, "reassoc"),
234    (Flags::VOLATILE, "volatile"),
235    (Flags::NOALIAS, "noalias"),
236    (Flags::NOFREE, "nofree"),
237    (Flags::STATIC, "static"),
238];
239
240/// How strongly an atomic operation is ordered against everything around it.
241///
242/// These are C11's, minus `consume`, which every compiler in existence widens to `acquire`
243/// because nobody can implement it as specified and the standard committee has said so.
244#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
245pub enum MemOrder {
246    /// Not atomic at all, which is what an ordinary load or store is.
247    #[default]
248    NotAtomic,
249    /// Atomic, with no ordering against anything else.
250    Relaxed,
251    /// Nothing after this in program order moves before it.
252    Acquire,
253    /// Nothing before this in program order moves after it.
254    Release,
255    /// Both, for a read-modify-write.
256    AcqRel,
257    /// Both, and a single total order over every sequentially consistent operation.
258    SeqCst,
259}
260
261impl MemOrder {
262    /// The textual form.
263    #[must_use]
264    pub const fn name(self) -> &'static str {
265        match self {
266            Self::NotAtomic => "not_atomic",
267            Self::Relaxed => "relaxed",
268            Self::Acquire => "acquire",
269            Self::Release => "release",
270            Self::AcqRel => "acq_rel",
271            Self::SeqCst => "seq_cst",
272        }
273    }
274
275    /// The ordering with that name, if there is one.
276    #[must_use]
277    pub fn from_name(name: &str) -> Option<Self> {
278        Self::all().find(|order| order.name() == name)
279    }
280
281    /// Every ordering, weakest first.
282    pub fn all() -> impl Iterator<Item = Self> {
283        [Self::NotAtomic, Self::Relaxed, Self::Acquire, Self::Release, Self::AcqRel, Self::SeqCst]
284            .into_iter()
285    }
286
287    /// Whether this ordering can be asked of a load.
288    ///
289    /// A load cannot release, because there is nothing it published.
290    #[must_use]
291    pub const fn is_valid_for_load(self) -> bool {
292        matches!(self, Self::Relaxed | Self::Acquire | Self::SeqCst)
293    }
294
295    /// Whether this ordering can be asked of a store.
296    ///
297    /// A store cannot acquire, because it read nothing to synchronise with.
298    #[must_use]
299    pub const fn is_valid_for_store(self) -> bool {
300        matches!(self, Self::Relaxed | Self::Release | Self::SeqCst)
301    }
302
303    /// Whether this ordering can be asked of a read-modify-write, which is any of them.
304    #[must_use]
305    pub const fn is_valid_for_rmw(self) -> bool {
306        !matches!(self, Self::NotAtomic)
307    }
308}
309
310impl fmt::Display for MemOrder {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.write_str(self.name())
313    }
314}
315
316/// Which operation an `atomic_rmw` performs.
317#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
318pub enum RmwOp {
319    /// Replace, returning the old value.
320    Xchg,
321    /// Integer addition.
322    Add,
323    /// Integer subtraction.
324    Sub,
325    /// Bitwise and.
326    And,
327    /// Bitwise and, then complement, which is the one hardware sometimes has natively.
328    Nand,
329    /// Bitwise or.
330    Or,
331    /// Bitwise exclusive or.
332    Xor,
333    /// Signed maximum.
334    SMax,
335    /// Signed minimum.
336    SMin,
337    /// Unsigned maximum.
338    UMax,
339    /// Unsigned minimum.
340    UMin,
341    /// Floating point addition.
342    FAdd,
343    /// Floating point subtraction.
344    FSub,
345}
346
347impl RmwOp {
348    /// The textual form.
349    #[must_use]
350    pub const fn name(self) -> &'static str {
351        match self {
352            Self::Xchg => "xchg",
353            Self::Add => "add",
354            Self::Sub => "sub",
355            Self::And => "and",
356            Self::Nand => "nand",
357            Self::Or => "or",
358            Self::Xor => "xor",
359            Self::SMax => "smax",
360            Self::SMin => "smin",
361            Self::UMax => "umax",
362            Self::UMin => "umin",
363            Self::FAdd => "fadd",
364            Self::FSub => "fsub",
365        }
366    }
367
368    /// The operation with that name, if there is one.
369    #[must_use]
370    pub fn from_name(name: &str) -> Option<Self> {
371        Self::all().find(|op| op.name() == name)
372    }
373
374    /// Every operation.
375    pub fn all() -> impl Iterator<Item = Self> {
376        [
377            Self::Xchg,
378            Self::Add,
379            Self::Sub,
380            Self::And,
381            Self::Nand,
382            Self::Or,
383            Self::Xor,
384            Self::SMax,
385            Self::SMin,
386            Self::UMax,
387            Self::UMin,
388            Self::FAdd,
389            Self::FSub,
390        ]
391        .into_iter()
392    }
393
394    /// Whether this operates on a floating point value rather than an integer.
395    #[must_use]
396    pub const fn is_float(self) -> bool {
397        matches!(self, Self::FAdd | Self::FSub)
398    }
399}
400
401impl fmt::Display for RmwOp {
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        f.write_str(self.name())
404    }
405}
406
407/// What kind of storage a memory safety instance is, which is `class` of
408/// `spec/safe-memory/04-safety-model.md` section 4.1.
409///
410/// It is on `meta_begin` because judgement J4 writes it when the instance is created, and the
411/// one place it is read afterwards is J6: `free` is permitted on an allocated instance and on
412/// no other kind, which is what makes freeing a stack address a report rather than a crash in
413/// the allocator.
414#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
415pub enum StorageClass {
416    /// A global or a static local, which lives as long as the program does.
417    Static,
418    /// A local, which lives as long as its block does.
419    Automatic,
420    /// Storage an allocator handed out, and the only kind `free` may be given.
421    Allocated,
422    /// A mapping, from `mmap` or its equivalent.
423    Mapped,
424    /// A device register window, where a read is not a read of anything the program wrote.
425    Mmio,
426    /// Storage a device owns, which is what a DMA buffer is while the transfer runs.
427    Device,
428    /// A function, which is what the address of one points at.
429    Function,
430    /// A string or compound literal, which the implementation may have merged with another.
431    Literal,
432}
433
434impl StorageClass {
435    /// The textual form.
436    #[must_use]
437    pub const fn name(self) -> &'static str {
438        match self {
439            Self::Static => "static",
440            Self::Automatic => "automatic",
441            Self::Allocated => "allocated",
442            Self::Mapped => "mapped",
443            Self::Mmio => "mmio",
444            Self::Device => "device",
445            Self::Function => "function",
446            Self::Literal => "literal",
447        }
448    }
449
450    /// The class with that name, if there is one.
451    #[must_use]
452    pub fn from_name(name: &str) -> Option<Self> {
453        Self::all().find(|class| class.name() == name)
454    }
455
456    /// Every class, in the order document 04 lists them.
457    pub fn all() -> impl Iterator<Item = Self> {
458        [
459            Self::Static,
460            Self::Automatic,
461            Self::Allocated,
462            Self::Mapped,
463            Self::Mmio,
464            Self::Device,
465            Self::Function,
466            Self::Literal,
467        ]
468        .into_iter()
469    }
470}
471
472impl fmt::Display for StorageClass {
473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474        f.write_str(self.name())
475    }
476}
477
478/// Who a range of memory belongs to while it is out of the monitor's authority.
479///
480/// Judgement J7 of `spec/safe-memory/04-safety-model.md`, which is the one that has no analogue
481/// in any existing tool. A range handed to a device is a range the program must not touch until
482/// it comes back, and saying which of the three it went to is what lets the report name what the
483/// program broke rather than only that it broke something.
484#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
485pub enum Owner {
486    /// A device, which is what the DMA ownership contract hands a buffer to.
487    Device,
488    /// Code compiled without the instrumentation, per document 10.
489    Uninstrumented,
490    /// The kernel, across a system call that writes into the range.
491    Kernel,
492}
493
494impl Owner {
495    /// The textual form.
496    #[must_use]
497    pub const fn name(self) -> &'static str {
498        match self {
499            Self::Device => "device",
500            Self::Uninstrumented => "uninstrumented",
501            Self::Kernel => "kernel",
502        }
503    }
504
505    /// The owner with that name, if there is one.
506    #[must_use]
507    pub fn from_name(name: &str) -> Option<Self> {
508        Self::all().find(|owner| owner.name() == name)
509    }
510
511    /// Every owner.
512    pub fn all() -> impl Iterator<Item = Self> {
513        [Self::Device, Self::Uninstrumented, Self::Kernel].into_iter()
514    }
515}
516
517impl fmt::Display for Owner {
518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519        f.write_str(self.name())
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    #[test]
528    fn a_flag_set_is_two_bytes() {
529        assert_eq!(size_of::<Flags>(), 2);
530    }
531
532    #[test]
533    fn every_flag_has_a_name_and_finds_it_again() {
534        for &(flag, name) in NAMED {
535            assert_eq!(Flags::from_name(name), Some(flag), "{name}");
536            assert_eq!(flag.to_string(), format!(".{name}"));
537        }
538        assert_eq!(Flags::from_name("poison"), None);
539        assert_eq!(Flags::from_name(""), None);
540    }
541
542    #[test]
543    fn no_two_flags_share_a_bit() {
544        let mut seen = 0u16;
545        for &(flag, name) in NAMED {
546            assert_eq!(flag.bits().count_ones(), 1, "{name} is not one bit");
547            assert_eq!(seen & flag.bits(), 0, "{name} shares a bit");
548            seen |= flag.bits();
549        }
550    }
551
552    #[test]
553    fn fast_is_exactly_the_six_fast_math_flags() {
554        let named: Vec<&str> = Flags::FAST.iter().map(|(_, name)| name).collect();
555        assert_eq!(named, ["nnan", "ninf", "nsz", "arcp", "contract", "reassoc"]);
556        assert!(!Flags::FAST.contains(Flags::NSW));
557        assert!(!Flags::FAST.contains(Flags::VOLATILE));
558    }
559
560    #[test]
561    fn the_empty_set_prints_as_nothing() {
562        assert!(Flags::NONE.is_empty());
563        assert_eq!(Flags::NONE.to_string(), "");
564        assert_eq!(Flags::NONE.iter().count(), 0);
565    }
566
567    #[test]
568    fn flags_print_as_the_suffix_the_textual_form_uses() {
569        assert_eq!((Flags::NSW | Flags::NUW).to_string(), ".nsw.nuw");
570        // Whatever order they were combined in, the printer writes them in one order, which
571        // is what a byte for byte round trip needs.
572        assert_eq!((Flags::NUW | Flags::NSW).to_string(), ".nsw.nuw");
573    }
574
575    #[test]
576    fn intersecting_is_what_a_rewrite_keeps() {
577        let one = Flags::NSW | Flags::NUW;
578        let other = Flags::NSW;
579        assert_eq!(one.intersection(other), Flags::NSW);
580        assert_eq!(one.without(Flags::NSW), Flags::NUW);
581        assert!(one.contains(Flags::NSW));
582        assert!(!other.contains(Flags::NUW));
583    }
584
585    #[test]
586    fn wrapping_flags_go_on_arithmetic_and_nowhere_else() {
587        assert!(Flags::legal_on(Opcode::Add).contains(Flags::NSW));
588        assert!(Flags::legal_on(Opcode::Shl).contains(Flags::NUW));
589        assert!(!Flags::legal_on(Opcode::Add).contains(Flags::EXACT));
590        assert!(!Flags::legal_on(Opcode::FAdd).contains(Flags::NSW));
591        assert!(!Flags::legal_on(Opcode::Load).contains(Flags::NSW));
592        assert!(Flags::legal_on(Opcode::SDiv).contains(Flags::EXACT));
593        assert!(Flags::legal_on(Opcode::FMul).contains(Flags::CONTRACT));
594        assert!(Flags::legal_on(Opcode::Store).contains(Flags::VOLATILE));
595        assert!(Flags::legal_on(Opcode::Jump).is_empty());
596    }
597
598    #[test]
599    fn nofree_goes_on_a_call_and_nowhere_else() {
600        for opcode in [Opcode::Call, Opcode::TailCall, Opcode::CallIndirect] {
601            assert!(Flags::legal_on(opcode).contains(Flags::NOFREE), "{opcode}");
602        }
603        for opcode in Opcode::all() {
604            let call = matches!(opcode, Opcode::Call | Opcode::TailCall | Opcode::CallIndirect);
605            assert_eq!(Flags::legal_on(opcode).contains(Flags::NOFREE), call, "{opcode}");
606        }
607        // It is a fact rather than a licence, so it is not part of what `-ffast-math` grants and
608        // it is not something a rewrite over arithmetic could carry onto a call.
609        assert!(!Flags::FAST.contains(Flags::NOFREE));
610    }
611
612    #[test]
613    fn static_goes_on_a_safety_check_and_nowhere_else() {
614        for opcode in [Opcode::CheckBounds, Opcode::CheckLive, Opcode::CheckDeriv] {
615            assert!(Flags::legal_on(opcode).contains(Flags::STATIC), "{opcode}");
616        }
617        for opcode in Opcode::all() {
618            let check =
619                matches!(opcode, Opcode::CheckBounds | Opcode::CheckLive | Opcode::CheckDeriv);
620            assert_eq!(Flags::legal_on(opcode).contains(Flags::STATIC), check, "{opcode}");
621        }
622        // The other fact, and they are legal on disjoint sets of opcodes, so an instruction that
623        // carries one can never be read as carrying the other.
624        assert!(!Flags::legal_on(Opcode::Call).contains(Flags::STATIC));
625        assert!(!Flags::legal_on(Opcode::CheckBounds).contains(Flags::NOFREE));
626    }
627
628    #[test]
629    fn every_flag_is_legal_on_something() {
630        for &(flag, name) in NAMED {
631            assert!(
632                Opcode::all().any(|op| Flags::legal_on(op).contains(flag)),
633                "{name} is legal nowhere, so nothing can ever set it"
634            );
635        }
636    }
637
638    #[test]
639    fn a_load_cannot_release_and_a_store_cannot_acquire() {
640        assert!(MemOrder::Acquire.is_valid_for_load());
641        assert!(!MemOrder::Release.is_valid_for_load());
642        assert!(!MemOrder::AcqRel.is_valid_for_load());
643        assert!(MemOrder::Release.is_valid_for_store());
644        assert!(!MemOrder::Acquire.is_valid_for_store());
645        assert!(MemOrder::SeqCst.is_valid_for_load());
646        assert!(MemOrder::SeqCst.is_valid_for_store());
647    }
648
649    #[test]
650    fn not_atomic_is_valid_for_no_atomic_operation() {
651        assert!(!MemOrder::NotAtomic.is_valid_for_load());
652        assert!(!MemOrder::NotAtomic.is_valid_for_store());
653        assert!(!MemOrder::NotAtomic.is_valid_for_rmw());
654        assert_eq!(MemOrder::default(), MemOrder::NotAtomic);
655    }
656
657    #[test]
658    fn every_ordering_and_operation_finds_its_name_again() {
659        for order in MemOrder::all() {
660            assert_eq!(MemOrder::from_name(order.name()), Some(order));
661        }
662        for op in RmwOp::all() {
663            assert_eq!(RmwOp::from_name(op.name()), Some(op));
664        }
665        assert_eq!(MemOrder::from_name("consume"), None);
666        assert_eq!(RmwOp::from_name("fmul"), None);
667    }
668
669    #[test]
670    fn the_floating_read_modify_writes_are_the_two_that_have_one() {
671        let floats: Vec<&str> = RmwOp::all().filter(|op| op.is_float()).map(RmwOp::name).collect();
672        assert_eq!(floats, ["fadd", "fsub"]);
673    }
674
675    #[test]
676    fn every_storage_class_and_owner_finds_its_name_again() {
677        for class in StorageClass::all() {
678            assert_eq!(StorageClass::from_name(class.name()), Some(class));
679        }
680        for owner in Owner::all() {
681            assert_eq!(Owner::from_name(owner.name()), Some(owner));
682        }
683        // The eight of document 04 and no more. `heap` is what a reader would guess and the
684        // model does not have it, since what the allocator hands out is `allocated`.
685        assert_eq!(StorageClass::all().count(), 8);
686        assert_eq!(StorageClass::from_name("heap"), None);
687        assert_eq!(Owner::from_name("hardware"), None);
688    }
689}