rucc_ir/opcode.rs
1//! The instruction set.
2//!
3//! Design: `spec/08-ir.md` section 8.3.
4//!
5//! The set is small enough to enumerate and it is closed. Adding an opcode is a spec change,
6//! because the verifier, the printer, the parser, the rewrite rules and the lowering all have
7//! to learn it, and an opcode that only half of them know about is a silent miscompilation
8//! waiting for the right input.
9//!
10//! Two things are deliberately absent. There is no `getelementptr`: pointer arithmetic is
11//! [`Opcode::PtrAdd`] over a byte offset the frontend computed, because C never needs the
12//! multi-index form and its absence removes a well known source of complexity. And there is no
13//! `phi`: values arriving at a block are the block's parameters, passed by the branch, so
14//! there is no operand list positionally tied to a predecessor list kept somewhere else.
15
16use std::fmt;
17
18/// One instruction of the IR.
19///
20/// The names are the textual form exactly, so [`Opcode::name`] and [`Opcode::from_name`] are
21/// what the printer and the parser use, and neither carries a table of its own that could
22/// drift from this one.
23///
24/// The enum is not `non_exhaustive`, deliberately. The set is closed, so a pass that matches
25/// on every opcode should stop compiling when one is added rather than fall into a wildcard
26/// arm that quietly does the wrong thing.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub enum Opcode {
29 // Constants. A constant is an instruction rather than an operand kind, so that every
30 // operand is a value and every value has one definition, which is what makes the
31 // dominance check in the verifier a single rule rather than a rule with exceptions.
32 /// An integer constant, `iconst.i32 7`.
33 IConst,
34 /// A floating point constant, `fconst.f64 0x1.8p+1`.
35 FConst,
36 /// A vector constant with every lane the same, `splat.i8x16 0`.
37 Splat,
38 /// The address of a global or a function, `global_addr @counter`.
39 GlobalAddr,
40 /// The address of a block in this function, `block_addr block3`.
41 ///
42 /// The one instruction that names a block without being a branch, which is what GNU's
43 /// `&&label` is. Where it goes is [`Opcode::IndirectBr`], and the two are only useful
44 /// together: an address on its own is a number that nothing can do anything with.
45 BlockAddr,
46
47 // Arithmetic.
48 /// Integer addition.
49 Add,
50 /// Integer subtraction.
51 Sub,
52 /// Integer multiplication.
53 Mul,
54 /// Signed division.
55 SDiv,
56 /// Unsigned division.
57 UDiv,
58 /// Signed remainder, with the sign of the dividend.
59 SRem,
60 /// Unsigned remainder.
61 URem,
62 /// Bitwise and.
63 And,
64 /// Bitwise or.
65 Or,
66 /// Bitwise exclusive or.
67 Xor,
68 /// Shift left.
69 Shl,
70 /// Logical shift right, shifting in zeroes.
71 LShr,
72 /// Arithmetic shift right, shifting in the sign bit.
73 AShr,
74 /// Floating point addition.
75 FAdd,
76 /// Floating point subtraction.
77 FSub,
78 /// Floating point multiplication.
79 FMul,
80 /// Floating point division.
81 FDiv,
82 /// Floating point remainder.
83 FRem,
84 /// Floating point negation, which flips the sign bit and is not `0 - x`.
85 FNeg,
86 /// Fused multiply-add, rounded once.
87 Fma,
88
89 // Comparison.
90 /// Integer comparison, producing `i1` or a vector of `i1`.
91 ICmp,
92 /// Floating point comparison, producing `i1` or a vector of `i1`.
93 FCmp,
94
95 // Selection.
96 /// One of two values, chosen by a bit. `select c, a, b` is `a` when `c` is one.
97 ///
98 /// This is what control flow becomes when it stops being control flow.
99 /// `spec/optimizer/22-phiopt-and-if-conversion.md` section 22.2 makes it the lowering target
100 /// for a diamond whose two arms compute a value, and the reason it is an opcode rather than a
101 /// pattern is that it is the form the rule set is written against: `select(c, a, a) -> a` and
102 /// `select(c, 1, 0) -> zext(c)` are ordinary rules once the shape has a name.
103 ///
104 /// Both arms are evaluated, which is the whole point and also the whole danger. Whatever
105 /// produces one of these owes the argument that evaluating the arm that is not chosen is
106 /// harmless, and section 22.6 is the list of ways that argument goes wrong.
107 Select,
108
109 // Conversion.
110 /// Narrows an integer, discarding the high bits.
111 Trunc,
112 /// Widens an integer, copying the sign bit.
113 SExt,
114 /// Widens an integer, filling with zeroes.
115 ZExt,
116 /// Narrows a floating point value.
117 FPTrunc,
118 /// Widens a floating point value.
119 FPExt,
120 /// Floating point to signed integer.
121 FPToSI,
122 /// Floating point to unsigned integer.
123 FPToUI,
124 /// Signed integer to floating point.
125 SIToFP,
126 /// Unsigned integer to floating point.
127 UIToFP,
128 /// An address to an integer of the same width.
129 PtrToInt,
130 /// An integer to an address.
131 IntToPtr,
132 /// A reinterpretation of the same bits at the same width.
133 Bitcast,
134
135 // Memory.
136 /// Memory as the function found it, which is where a memory SSA chain starts.
137 ///
138 /// It produces one `mem` and takes nothing, and it belongs at the top of the entry block.
139 /// GCC calls the same thing the default definition of `.MEM` and LLVM calls it
140 /// `liveOnEntry`. It exists as an instruction rather than as a parameter of the entry block
141 /// because the entry block's parameters are the function's parameters and the verifier
142 /// checks them against the signature, and memory is not an argument anybody passed.
143 MemEntry,
144 /// A stack slot. In the entry block, or marked dynamic for a variable length array.
145 Alloca,
146 /// A read.
147 Load,
148 /// A write, producing no value.
149 Store,
150 /// Address arithmetic: an address and a byte offset.
151 PtrAdd,
152 /// A copy of a known size between addresses that do not overlap.
153 Memcpy,
154 /// A copy of a known size between addresses that may overlap.
155 Memmove,
156 /// A fill of a known size with one byte.
157 Memset,
158 /// An atomic read.
159 AtomicLoad,
160 /// An atomic write.
161 AtomicStore,
162 /// An atomic read-modify-write, carrying which operation in [`RmwOp`](crate::RmwOp).
163 AtomicRmw,
164 /// An atomic compare and exchange, producing the old value and whether it succeeded.
165 Cmpxchg,
166 /// A memory barrier.
167 Fence,
168
169 // Memory safety. Design: `spec/safe-memory/06-instrumentation.md` section 6.2.2. None of
170 // these is emitted unless `-fsafety` asked for it, and a function compiled without it
171 // contains not one of them.
172 /// The capability of a pointer value, taken from the pointer's provenance.
173 CapOf,
174 /// The capability in the auxiliary slot beside a stored pointer, read back.
175 ///
176 /// A pointer written to memory and read again has to bring its capability with it, and where
177 /// the capability lives is document 05's question rather than this one's. What this says is
178 /// that a capability comes back from an address, which is enough for every pass above.
179 CapLoad,
180 /// The other half of [`Opcode::CapLoad`], writing one into the slot beside a pointer.
181 CapStore,
182 /// The capability that permits nothing, which is what a null pointer has.
183 CapNull,
184 /// A capability narrowed to a sub-object of what it covered.
185 ///
186 /// Only under `-fsafety-subobject`. Narrowing is what catches an overflow from one member of
187 /// a struct into the next, and it is separate because C code that walks off the end of a
188 /// member on purpose exists and a project has to be able to say so.
189 CapNarrow,
190 /// The capability for an address that arrived from outside, recovered from the planes.
191 CapRecover,
192 /// An access is within its capability's bounds, aligned, and permitted.
193 ///
194 /// The size and the alignment are the access's, and they are in the memory payload rather
195 /// than in operands because they are what the front end knew and not what the program
196 /// computed.
197 ///
198 /// A third operand overrides how many bytes are asked about, and it exists for the one check
199 /// the front end did not write. `spec/safe-memory/07-check-elimination.md` section 7.4 replaces
200 /// the checks in a loop that runs `n` times with one check over `n * sizeof(T)` bytes, and that
201 /// is a length the program computes rather than one anybody knew when the access was parsed. The
202 /// payload still holds the alignment and the type information of the access the check came from,
203 /// and its size becomes the size of one of them rather than the size of the question.
204 CheckBounds,
205 /// The capability's provenance is still live.
206 CheckLive,
207 /// The access agrees with the type plane, which is the effective type rule of C 6.5.
208 CheckType,
209 /// The bytes the access reads have been written.
210 CheckInit,
211 /// A pointer derived from another stays inside the capability the first one had.
212 ///
213 /// Three operands, because the answer is about the new pointer and the question is about
214 /// the old one's capability.
215 CheckDeriv,
216 /// The metadata this access is about to consult has not been changed under it.
217 CheckRace,
218 /// A storage instance begins here, over a range, with a class.
219 ///
220 /// Judgement J4. This is the `alloca` for an automatic instance and the allocator's report
221 /// for an allocated one, and the range is a pointer and a length in registers rather than a
222 /// payload, because the length of a variable length array is not known when the instruction
223 /// is written down.
224 MetaBegin,
225 /// A storage instance ends here, which is judgement J5.
226 ///
227 /// Every capability for it fails from this point on and keeps failing after the address is
228 /// handed out again, which is what makes the check a use after free check rather than a use
229 /// after reallocation one.
230 MetaEnd,
231 /// The effective type of a range is now this one.
232 MetaType,
233 /// The bytes of a range are now initialized.
234 MetaInit,
235 /// A range leaves the monitor's authority, or comes back, which is judgement J7.
236 MetaTransfer,
237 /// A declared exemption starts here, with the reason it was declared.
238 ///
239 /// Not an optimization hint. Everything between this and its `safe_region_end` is code the
240 /// monitor is told not to judge, so the reason it carries is a trust set entry, and
241 /// `spec/safe-memory/10-boundaries.md` section 10.2 counts them per build precisely so that
242 /// a reviewer can read what a binary's guarantee rests on.
243 SafeRegionBegin,
244 /// The end of the region the last `safe_region_begin` opened.
245 SafeRegionEnd,
246
247 // Control. Every one of these is a terminator.
248 /// An unconditional branch, `jump block1(%a, %b)`.
249 Jump,
250 /// A two-way branch on an `i1`.
251 BrIf,
252 /// A multi-way branch on an integer, with a default.
253 Switch,
254 /// A branch to an address, `indirect_br %0, block1, block2`.
255 ///
256 /// The targets are every block control can arrive at, which is what makes the edges of a
257 /// computed `goto` ordinary edges: nothing else in the compiler has to know that the
258 /// address decides which one it is. A target that is not listed is a branch that does not
259 /// happen, so a frontend that leaves one out has made a promise on the program's behalf.
260 IndirectBr,
261 /// A return, with the values the signature says.
262 Return,
263 /// A place control cannot reach, which the frontend emits after a `noreturn` call.
264 Unreachable,
265
266 // Calls.
267 /// A call to a named function.
268 Call,
269 /// A call through an address, carrying the signature it is called with.
270 CallIndirect,
271 /// A call in tail position that reuses the frame, which is a terminator.
272 TailCall,
273
274 // Intrinsics, which is the closed part. The open part is `TargetIntrinsic`.
275 /// Count leading zeroes.
276 Ctlz,
277 /// Count trailing zeroes.
278 Cttz,
279 /// Count set bits.
280 Ctpop,
281 /// Reverse the bytes.
282 Bswap,
283 /// Reverse the bits.
284 Bitreverse,
285 /// Signed addition, producing the result and whether it overflowed.
286 SAddOverflow,
287 /// Unsigned addition, producing the result and whether it overflowed.
288 UAddOverflow,
289 /// Signed subtraction, producing the result and whether it overflowed.
290 SSubOverflow,
291 /// Unsigned subtraction, producing the result and whether it overflowed.
292 USubOverflow,
293 /// Signed multiplication, producing the result and whether it overflowed.
294 SMulOverflow,
295 /// Unsigned multiplication, producing the result and whether it overflowed.
296 UMulOverflow,
297 /// `__builtin_expect`, which is the value with a hint attached.
298 Expect,
299 /// `__builtin_unreachable` as a hint on a path, distinct from the terminator.
300 UnreachableHint,
301 /// `__builtin_prefetch`.
302 Prefetch,
303 /// `__builtin_frame_address`.
304 FrameAddress,
305 /// `__builtin_return_address`.
306 ReturnAddress,
307 /// The start of a variable argument list.
308 VaStart,
309 /// One argument off a variable argument list, which moves the list on as it reads it. Two
310 /// of these on one list are two arguments and never one argument read twice, so whatever
311 /// decides which instructions may be folded together has to leave these alone.
312 VaArg,
313 /// One argument off a variable argument list, when that argument is an object rather than a
314 /// value, which is what a `struct` or a `union` read out of one is.
315 ///
316 /// It answers the address of the object rather than the object, because an aggregate is not
317 /// a value and there is nothing for one result to be. Where the object arrives in registers
318 /// there is no address until something makes one, so what this asks of a target is a place
319 /// to put the registers and the address of that place, which is the copy every psABI's own
320 /// description of the algorithm makes. It moves the list on for the reason [`Opcode::VaArg`]
321 /// does.
322 VaObject,
323 /// The end of a variable argument list.
324 VaEnd,
325 /// A copy of a variable argument list.
326 VaCopy,
327 /// The stack pointer, saved before a variable length array.
328 StackSave,
329 /// The stack pointer, restored after one.
330 StackRestore,
331 /// The marker a `setjmp` leaves, which pins everything live across it.
332 SetjmpMarker,
333 /// The marker a `longjmp` leaves.
334 LongjmpMarker,
335 /// A target-specific intrinsic, named rather than enumerated, for the vector builtins.
336 TargetIntrinsic,
337
338 /// Inline assembly. A terminator when it has labels, which is `asm goto`.
339 InlineAsm,
340}
341
342impl Opcode {
343 /// The textual form, which is also what the parser reads.
344 #[must_use]
345 pub const fn name(self) -> &'static str {
346 match self {
347 Self::IConst => "iconst",
348 Self::FConst => "fconst",
349 Self::Splat => "splat",
350 Self::GlobalAddr => "global_addr",
351 Self::BlockAddr => "block_addr",
352 Self::Add => "add",
353 Self::Sub => "sub",
354 Self::Mul => "mul",
355 Self::SDiv => "sdiv",
356 Self::UDiv => "udiv",
357 Self::SRem => "srem",
358 Self::URem => "urem",
359 Self::And => "and",
360 Self::Or => "or",
361 Self::Xor => "xor",
362 Self::Shl => "shl",
363 Self::LShr => "lshr",
364 Self::AShr => "ashr",
365 Self::FAdd => "fadd",
366 Self::FSub => "fsub",
367 Self::FMul => "fmul",
368 Self::FDiv => "fdiv",
369 Self::FRem => "frem",
370 Self::FNeg => "fneg",
371 Self::Fma => "fma",
372 Self::ICmp => "icmp",
373 Self::FCmp => "fcmp",
374 Self::Select => "select",
375 Self::Trunc => "trunc",
376 Self::SExt => "sext",
377 Self::ZExt => "zext",
378 Self::FPTrunc => "fptrunc",
379 Self::FPExt => "fpext",
380 Self::FPToSI => "fptosi",
381 Self::FPToUI => "fptoui",
382 Self::SIToFP => "sitofp",
383 Self::UIToFP => "uitofp",
384 Self::PtrToInt => "ptrtoint",
385 Self::IntToPtr => "inttoptr",
386 Self::Bitcast => "bitcast",
387 Self::MemEntry => "mem_entry",
388 Self::Alloca => "alloca",
389 Self::Load => "load",
390 Self::Store => "store",
391 Self::PtrAdd => "ptr_add",
392 Self::Memcpy => "memcpy",
393 Self::Memmove => "memmove",
394 Self::Memset => "memset",
395 Self::AtomicLoad => "atomic_load",
396 Self::AtomicStore => "atomic_store",
397 Self::AtomicRmw => "atomic_rmw",
398 Self::Cmpxchg => "cmpxchg",
399 Self::Fence => "fence",
400 Self::CapOf => "cap_of",
401 Self::CapLoad => "cap_load",
402 Self::CapStore => "cap_store",
403 Self::CapNull => "cap_null",
404 Self::CapNarrow => "cap_narrow",
405 Self::CapRecover => "cap_recover",
406 Self::CheckBounds => "check_bounds",
407 Self::CheckLive => "check_live",
408 Self::CheckType => "check_type",
409 Self::CheckInit => "check_init",
410 Self::CheckDeriv => "check_deriv",
411 Self::CheckRace => "check_race",
412 Self::MetaBegin => "meta_begin",
413 Self::MetaEnd => "meta_end",
414 Self::MetaType => "meta_type",
415 Self::MetaInit => "meta_init",
416 Self::MetaTransfer => "meta_transfer",
417 Self::SafeRegionBegin => "safe_region_begin",
418 Self::SafeRegionEnd => "safe_region_end",
419 Self::Jump => "jump",
420 Self::BrIf => "br_if",
421 Self::Switch => "switch",
422 Self::IndirectBr => "indirect_br",
423 Self::Return => "return",
424 Self::Unreachable => "unreachable",
425 Self::Call => "call",
426 Self::CallIndirect => "call_indirect",
427 Self::TailCall => "tail_call",
428 Self::Ctlz => "ctlz",
429 Self::Cttz => "cttz",
430 Self::Ctpop => "ctpop",
431 Self::Bswap => "bswap",
432 Self::Bitreverse => "bitreverse",
433 Self::SAddOverflow => "sadd_overflow",
434 Self::UAddOverflow => "uadd_overflow",
435 Self::SSubOverflow => "ssub_overflow",
436 Self::USubOverflow => "usub_overflow",
437 Self::SMulOverflow => "smul_overflow",
438 Self::UMulOverflow => "umul_overflow",
439 Self::Expect => "expect",
440 Self::UnreachableHint => "unreachable_hint",
441 Self::Prefetch => "prefetch",
442 Self::FrameAddress => "frame_address",
443 Self::ReturnAddress => "return_address",
444 Self::VaStart => "va_start",
445 Self::VaArg => "va_arg",
446 Self::VaObject => "va_object",
447 Self::VaEnd => "va_end",
448 Self::VaCopy => "va_copy",
449 Self::StackSave => "stacksave",
450 Self::StackRestore => "stackrestore",
451 Self::SetjmpMarker => "setjmp_marker",
452 Self::LongjmpMarker => "longjmp_marker",
453 Self::TargetIntrinsic => "target_intrinsic",
454 Self::InlineAsm => "inline_asm",
455 }
456 }
457
458 /// Every opcode, in the order they are declared.
459 ///
460 /// The parser walks this rather than holding a second table, because a second table is a
461 /// table that can disagree with the first one.
462 pub fn all() -> impl Iterator<Item = Self> {
463 ALL.iter().copied()
464 }
465
466 /// The opcode with that name, if there is one.
467 #[must_use]
468 pub fn from_name(name: &str) -> Option<Self> {
469 ALL.iter().copied().find(|op| op.name() == name)
470 }
471
472 /// Whether this ends a block.
473 ///
474 /// [`Opcode::InlineAsm`] is not here and is the one instruction whose answer depends on
475 /// the instruction rather than on the opcode: `asm goto` has successors and everything
476 /// else does not. Ask the instruction, not the opcode.
477 #[must_use]
478 pub const fn is_terminator(self) -> bool {
479 matches!(
480 self,
481 Self::Jump
482 | Self::BrIf
483 | Self::Switch
484 | Self::IndirectBr
485 | Self::Return
486 | Self::Unreachable
487 | Self::TailCall
488 )
489 }
490
491 /// Whether the operands can be swapped without changing the result.
492 ///
493 /// The floating point cases are commutative even under the strictest rounding, because
494 /// swapping the operands of an addition does not change which of them is a NaN, and the
495 /// sign of a NaN result is not something we promise anything about either way.
496 #[must_use]
497 pub const fn is_commutative(self) -> bool {
498 matches!(
499 self,
500 Self::Add
501 | Self::Mul
502 | Self::And
503 | Self::Or
504 | Self::Xor
505 | Self::FAdd
506 | Self::FMul
507 | Self::SAddOverflow
508 | Self::UAddOverflow
509 | Self::SMulOverflow
510 | Self::UMulOverflow
511 )
512 }
513
514 /// Whether this reads or writes memory, or has an effect the optimizer has to preserve.
515 ///
516 /// An instruction that answers no can be deleted when nothing uses its result, moved
517 /// across a call, and merged with another one computing the same thing. Everything else
518 /// has to be argued about individually, so the conservative answer is the true one here
519 /// and the list of exceptions is the part that is checked.
520 #[must_use]
521 pub const fn has_effects(self) -> bool {
522 !matches!(
523 self,
524 Self::IConst
525 | Self::FConst
526 | Self::Splat
527 | Self::GlobalAddr
528 | Self::BlockAddr
529 | Self::Add
530 | Self::Sub
531 | Self::Mul
532 | Self::SDiv
533 | Self::UDiv
534 | Self::SRem
535 | Self::URem
536 | Self::And
537 | Self::Or
538 | Self::Xor
539 | Self::Shl
540 | Self::LShr
541 | Self::AShr
542 | Self::FAdd
543 | Self::FSub
544 | Self::FMul
545 | Self::FDiv
546 | Self::FRem
547 | Self::FNeg
548 | Self::Fma
549 | Self::ICmp
550 | Self::FCmp
551 | Self::Select
552 | Self::Trunc
553 | Self::SExt
554 | Self::ZExt
555 | Self::FPTrunc
556 | Self::FPExt
557 | Self::FPToSI
558 | Self::FPToUI
559 | Self::SIToFP
560 | Self::UIToFP
561 | Self::PtrToInt
562 | Self::IntToPtr
563 | Self::Bitcast
564 | Self::PtrAdd
565 | Self::Ctlz
566 | Self::Cttz
567 | Self::Ctpop
568 | Self::Bswap
569 | Self::Bitreverse
570 | Self::SAddOverflow
571 | Self::UAddOverflow
572 | Self::SSubOverflow
573 | Self::USubOverflow
574 | Self::SMulOverflow
575 | Self::UMulOverflow
576 | Self::Expect
577 | Self::FrameAddress
578 | Self::ReturnAddress
579 | Self::MemEntry
580 // Three of the capability instructions are arithmetic on a pointer's
581 // provenance and touch nothing. The other three do: `cap_load` and
582 // `cap_store` are an access, and `cap_recover` reads the planes.
583 | Self::CapOf
584 | Self::CapNull
585 | Self::CapNarrow
586 )
587 }
588
589 /// Whether an instruction with this opcode touches memory.
590 ///
591 /// This is what decides whether it takes a memory operand once memory SSA is built, per
592 /// document 09 of `spec/optimizer`. It is written as the exceptions to touching memory
593 /// rather than as a list of what does, for the reason document 08.6 gives about the escape
594 /// analysis: an opcode added later has to end up on the conservative side by default, and a
595 /// list of what touches memory would silently leave a new one out.
596 ///
597 /// `mem_entry` answers no. It produces memory rather than touching it, which is the whole
598 /// of what it is for.
599 #[must_use]
600 pub const fn touches_memory(self) -> bool {
601 if !self.has_effects() {
602 return false;
603 }
604 !matches!(
605 self,
606 // Fresh storage nothing could have been reading, and the pointer that names it.
607 Self::Alloca
608 // The stack pointer, which is a register and not memory. Putting it back is a
609 // different matter and is below, because it takes storage away.
610 | Self::StackSave
611 // Control, which goes somewhere rather than touching anything. A tail call is
612 // not here, because it is a call.
613 | Self::Jump
614 | Self::BrIf
615 | Self::Switch
616 | Self::IndirectBr
617 | Self::Return
618 | Self::Unreachable
619 | Self::UnreachableHint
620 )
621 }
622
623 /// Whether an instruction with this opcode writes memory, and so produces a new version of
624 /// it rather than only reading the version it was given.
625 ///
626 /// Everything that touches memory writes it except the ones that plainly do not. A `fence`
627 /// writes nothing and is still a write here, because document 09.5 says an atomic or a
628 /// barrier is a definition nothing walks past, and giving it one is how that is expressed
629 /// in a representation whose only ordering is the memory chain.
630 ///
631 /// The checks read the planes and change nothing, which
632 /// `spec/safe-memory/06-instrumentation.md` section 6.2.4 states as the word `readonly`. A
633 /// check that trapped is a program that stopped and there is no version of memory after it
634 /// for anything to observe, so the trap costs nothing here. What it does cost is that a
635 /// check may not be moved across a plane write, and that is the memory chain saying so
636 /// rather than this.
637 #[must_use]
638 pub const fn writes_memory(self) -> bool {
639 self.touches_memory()
640 && !matches!(
641 self,
642 Self::Load
643 | Self::AtomicLoad
644 | Self::Prefetch
645 | Self::CapLoad
646 | Self::CapRecover
647 | Self::CheckBounds
648 | Self::CheckLive
649 | Self::CheckType
650 | Self::CheckInit
651 | Self::CheckDeriv
652 | Self::CheckRace
653 )
654 }
655
656 /// How many values this produces, for the opcodes where the count is fixed.
657 ///
658 /// `None` means the count comes from somewhere else: a call takes it from its signature,
659 /// and inline assembly takes it from its output constraints. A tail call is not one of
660 /// them, because whatever it returns goes straight out of the function and there is no
661 /// instruction after it to use anything.
662 #[must_use]
663 pub const fn results(self) -> Option<u8> {
664 match self {
665 Self::Call | Self::CallIndirect | Self::InlineAsm => None,
666 Self::Cmpxchg
667 | Self::SAddOverflow
668 | Self::UAddOverflow
669 | Self::SSubOverflow
670 | Self::USubOverflow
671 | Self::SMulOverflow
672 | Self::UMulOverflow => Some(2),
673 Self::Store
674 | Self::Memcpy
675 | Self::Memmove
676 | Self::Memset
677 | Self::AtomicStore
678 | Self::Fence
679 | Self::Prefetch
680 | Self::VaStart
681 | Self::VaEnd
682 | Self::VaCopy
683 | Self::StackRestore
684 | Self::UnreachableHint
685 | Self::SetjmpMarker
686 | Self::LongjmpMarker
687 | Self::CapStore
688 | Self::CheckBounds
689 | Self::CheckLive
690 | Self::CheckType
691 | Self::CheckInit
692 | Self::CheckDeriv
693 | Self::CheckRace
694 | Self::MetaBegin
695 | Self::MetaEnd
696 | Self::MetaType
697 | Self::MetaInit
698 | Self::MetaTransfer
699 | Self::SafeRegionBegin
700 | Self::SafeRegionEnd => Some(0),
701 _ if self.is_terminator() => Some(0),
702 _ => Some(1),
703 }
704 }
705
706 /// Whether an instruction with this opcode produces a capability.
707 ///
708 /// Five of the six `cap` instructions, `cap_store` being the one that consumes one instead.
709 /// The reason this is a question about the opcode rather than about the
710 /// result type is that the verifier asks it the other way round: it walks the results looking
711 /// for a `cap` and needs to know whether the instruction under it was entitled to make one.
712 #[must_use]
713 pub const fn makes_capability(self) -> bool {
714 matches!(
715 self,
716 Self::CapOf | Self::CapLoad | Self::CapNull | Self::CapNarrow | Self::CapRecover
717 )
718 }
719
720 /// Which payload an instruction with this opcode carries.
721 ///
722 /// The printer reads the payload it finds and does not need this. The parser has only the
723 /// opcode when it reaches the operands, so this is where the two of them agree on what
724 /// comes after them. An instruction carrying a payload of some other kind prints as text
725 /// the parser cannot read back, which is why the verifier checks it against
726 /// [`Extra::kind`](crate::Extra::kind) rather than leaving it to be found later.
727 #[must_use]
728 pub const fn extra_kind(self) -> ExtraKind {
729 match self {
730 Self::IConst | Self::FConst | Self::Splat => ExtraKind::Imm,
731 Self::GlobalAddr | Self::TargetIntrinsic => ExtraKind::Symbol,
732 Self::ICmp => ExtraKind::IntPred,
733 Self::FCmp => ExtraKind::FloatPred,
734 Self::Alloca
735 | Self::Load
736 | Self::Store
737 | Self::Memcpy
738 | Self::Memmove
739 | Self::Memset
740 | Self::AtomicLoad
741 | Self::AtomicStore
742 | Self::Cmpxchg
743 // Three of the checks are about a run of bytes and the payload is where the size
744 // of that run is, along with the alignment `check_bounds` wants and the aliasing
745 // node `check_type` compares against. The other three ask a question about a
746 // pointer and not about a range, so they carry nothing.
747 | Self::CheckBounds
748 | Self::CheckType
749 | Self::CheckInit => ExtraKind::Mem,
750 // The plane writes. What each one needs beyond the range is different, and the range
751 // itself is operands, since the length of a variable length array is a value.
752 Self::MetaBegin => ExtraKind::Class,
753 Self::MetaTransfer => ExtraKind::Owner,
754 Self::MetaType => ExtraKind::Node,
755 Self::SafeRegionBegin => ExtraKind::Reason,
756 Self::VaObject => ExtraKind::VaObject,
757 Self::AtomicRmw => ExtraKind::Rmw,
758 Self::Fence => ExtraKind::Order,
759 Self::Jump | Self::BrIf | Self::BlockAddr | Self::IndirectBr => ExtraKind::Targets,
760 Self::Switch => ExtraKind::Switch,
761 Self::Call | Self::CallIndirect | Self::TailCall => ExtraKind::Call,
762 Self::InlineAsm => ExtraKind::Asm,
763 _ => ExtraKind::None,
764 }
765 }
766}
767
768/// Which of [`Extra`](crate::Extra)'s shapes an instruction carries.
769///
770/// The same list of names, without any of the payloads, so that a question about an opcode can
771/// be answered without an instruction to look at.
772#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
773pub enum ExtraKind {
774 /// Nothing.
775 None,
776 /// A constant.
777 Imm,
778 /// A name.
779 Symbol,
780 /// An integer comparison predicate.
781 IntPred,
782 /// A floating point comparison predicate.
783 FloatPred,
784 /// An access.
785 Mem,
786 /// An atomic read-modify-write.
787 Rmw,
788 /// A barrier's ordering.
789 Order,
790 /// Branch targets.
791 Targets,
792 /// A call.
793 Call,
794 /// A `switch`.
795 Switch,
796 /// Inline assembly.
797 Asm,
798 /// An object read off a variable argument list.
799 VaObject,
800 /// What kind of storage an instance is.
801 Class,
802 /// Who a range of memory went to.
803 Owner,
804 /// A metadata node.
805 Node,
806 /// Why a declared exemption is there.
807 Reason,
808}
809
810impl ExtraKind {
811 /// What it is, in words, for a message that names two of them and has to read as English.
812 #[must_use]
813 pub const fn name(self) -> &'static str {
814 match self {
815 Self::None => "nothing",
816 Self::Imm => "a constant",
817 Self::Symbol => "a name",
818 Self::IntPred => "an integer comparison",
819 Self::FloatPred => "a floating point comparison",
820 Self::Mem => "an access",
821 Self::Rmw => "a read-modify-write",
822 Self::Order => "an ordering",
823 Self::Targets => "branch targets",
824 Self::Call => "a call",
825 Self::Switch => "a switch",
826 Self::Asm => "inline assembly",
827 Self::VaObject => "an object off a variable argument list",
828 Self::Class => "a storage class",
829 Self::Owner => "an owner",
830 Self::Node => "a metadata node",
831 Self::Reason => "a reason",
832 }
833 }
834}
835
836impl fmt::Display for Opcode {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 f.write_str(self.name())
839 }
840}
841
842/// Every opcode, which is what [`Opcode::all`] hands out.
843///
844/// This is written out rather than derived, and the test below is what keeps it complete: it
845/// checks the count against [`Opcode::InlineAsm`], the last variant, so a new opcode that is
846/// not added here fails the build rather than going quietly missing from the parser.
847static ALL: &[Opcode] = &[
848 Opcode::IConst,
849 Opcode::FConst,
850 Opcode::Splat,
851 Opcode::GlobalAddr,
852 Opcode::BlockAddr,
853 Opcode::Add,
854 Opcode::Sub,
855 Opcode::Mul,
856 Opcode::SDiv,
857 Opcode::UDiv,
858 Opcode::SRem,
859 Opcode::URem,
860 Opcode::And,
861 Opcode::Or,
862 Opcode::Xor,
863 Opcode::Shl,
864 Opcode::LShr,
865 Opcode::AShr,
866 Opcode::FAdd,
867 Opcode::FSub,
868 Opcode::FMul,
869 Opcode::FDiv,
870 Opcode::FRem,
871 Opcode::FNeg,
872 Opcode::Fma,
873 Opcode::ICmp,
874 Opcode::FCmp,
875 Opcode::Select,
876 Opcode::Trunc,
877 Opcode::SExt,
878 Opcode::ZExt,
879 Opcode::FPTrunc,
880 Opcode::FPExt,
881 Opcode::FPToSI,
882 Opcode::FPToUI,
883 Opcode::SIToFP,
884 Opcode::UIToFP,
885 Opcode::PtrToInt,
886 Opcode::IntToPtr,
887 Opcode::Bitcast,
888 Opcode::MemEntry,
889 Opcode::Alloca,
890 Opcode::Load,
891 Opcode::Store,
892 Opcode::PtrAdd,
893 Opcode::Memcpy,
894 Opcode::Memmove,
895 Opcode::Memset,
896 Opcode::AtomicLoad,
897 Opcode::AtomicStore,
898 Opcode::AtomicRmw,
899 Opcode::Cmpxchg,
900 Opcode::Fence,
901 Opcode::CapOf,
902 Opcode::CapLoad,
903 Opcode::CapStore,
904 Opcode::CapNull,
905 Opcode::CapNarrow,
906 Opcode::CapRecover,
907 Opcode::CheckBounds,
908 Opcode::CheckLive,
909 Opcode::CheckType,
910 Opcode::CheckInit,
911 Opcode::CheckDeriv,
912 Opcode::CheckRace,
913 Opcode::MetaBegin,
914 Opcode::MetaEnd,
915 Opcode::MetaType,
916 Opcode::MetaInit,
917 Opcode::MetaTransfer,
918 Opcode::SafeRegionBegin,
919 Opcode::SafeRegionEnd,
920 Opcode::Jump,
921 Opcode::BrIf,
922 Opcode::Switch,
923 Opcode::IndirectBr,
924 Opcode::Return,
925 Opcode::Unreachable,
926 Opcode::Call,
927 Opcode::CallIndirect,
928 Opcode::TailCall,
929 Opcode::Ctlz,
930 Opcode::Cttz,
931 Opcode::Ctpop,
932 Opcode::Bswap,
933 Opcode::Bitreverse,
934 Opcode::SAddOverflow,
935 Opcode::UAddOverflow,
936 Opcode::SSubOverflow,
937 Opcode::USubOverflow,
938 Opcode::SMulOverflow,
939 Opcode::UMulOverflow,
940 Opcode::Expect,
941 Opcode::UnreachableHint,
942 Opcode::Prefetch,
943 Opcode::FrameAddress,
944 Opcode::ReturnAddress,
945 Opcode::VaStart,
946 Opcode::VaArg,
947 Opcode::VaObject,
948 Opcode::VaEnd,
949 Opcode::VaCopy,
950 Opcode::StackSave,
951 Opcode::StackRestore,
952 Opcode::SetjmpMarker,
953 Opcode::LongjmpMarker,
954 Opcode::TargetIntrinsic,
955 Opcode::InlineAsm,
956];
957
958/// The ten integer comparisons.
959///
960/// Signedness is on the predicate rather than on the type, for the same reason it is on
961/// `sdiv` and `udiv`: the type space is halved and the operation says what it means.
962#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
963pub enum IntPred {
964 /// Equal.
965 Eq,
966 /// Not equal.
967 Ne,
968 /// Signed less than.
969 Slt,
970 /// Signed less than or equal.
971 Sle,
972 /// Signed greater than.
973 Sgt,
974 /// Signed greater than or equal.
975 Sge,
976 /// Unsigned less than.
977 Ult,
978 /// Unsigned less than or equal.
979 Ule,
980 /// Unsigned greater than.
981 Ugt,
982 /// Unsigned greater than or equal.
983 Uge,
984}
985
986impl IntPred {
987 /// The textual form.
988 #[must_use]
989 pub const fn name(self) -> &'static str {
990 match self {
991 Self::Eq => "eq",
992 Self::Ne => "ne",
993 Self::Slt => "slt",
994 Self::Sle => "sle",
995 Self::Sgt => "sgt",
996 Self::Sge => "sge",
997 Self::Ult => "ult",
998 Self::Ule => "ule",
999 Self::Ugt => "ugt",
1000 Self::Uge => "uge",
1001 }
1002 }
1003
1004 /// The predicate with that name, if there is one.
1005 #[must_use]
1006 pub fn from_name(name: &str) -> Option<Self> {
1007 Self::all().find(|pred| pred.name() == name)
1008 }
1009
1010 /// Every predicate.
1011 pub fn all() -> impl Iterator<Item = Self> {
1012 [
1013 Self::Eq,
1014 Self::Ne,
1015 Self::Slt,
1016 Self::Sle,
1017 Self::Sgt,
1018 Self::Sge,
1019 Self::Ult,
1020 Self::Ule,
1021 Self::Ugt,
1022 Self::Uge,
1023 ]
1024 .into_iter()
1025 }
1026
1027 /// The predicate that holds exactly when this one does not.
1028 #[must_use]
1029 pub const fn inverse(self) -> Self {
1030 match self {
1031 Self::Eq => Self::Ne,
1032 Self::Ne => Self::Eq,
1033 Self::Slt => Self::Sge,
1034 Self::Sge => Self::Slt,
1035 Self::Sle => Self::Sgt,
1036 Self::Sgt => Self::Sle,
1037 Self::Ult => Self::Uge,
1038 Self::Uge => Self::Ult,
1039 Self::Ule => Self::Ugt,
1040 Self::Ugt => Self::Ule,
1041 }
1042 }
1043
1044 /// The predicate that holds when the operands are given the other way round.
1045 #[must_use]
1046 pub const fn swapped(self) -> Self {
1047 match self {
1048 Self::Eq => Self::Eq,
1049 Self::Ne => Self::Ne,
1050 Self::Slt => Self::Sgt,
1051 Self::Sgt => Self::Slt,
1052 Self::Sle => Self::Sge,
1053 Self::Sge => Self::Sle,
1054 Self::Ult => Self::Ugt,
1055 Self::Ugt => Self::Ult,
1056 Self::Ule => Self::Uge,
1057 Self::Uge => Self::Ule,
1058 }
1059 }
1060
1061 /// Whether this reads its operands as signed. Equality reads them as neither.
1062 #[must_use]
1063 pub const fn is_signed(self) -> bool {
1064 matches!(self, Self::Slt | Self::Sle | Self::Sgt | Self::Sge)
1065 }
1066}
1067
1068impl fmt::Display for IntPred {
1069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1070 f.write_str(self.name())
1071 }
1072}
1073
1074/// The floating point comparisons, ordered and unordered.
1075///
1076/// An ordered predicate is false if either operand is a NaN, and an unordered one is true. C's
1077/// `<` is `olt` and C's `!=` is `une`, which is the whole of why both families are here.
1078#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1079pub enum FloatPred {
1080 /// Always false.
1081 False,
1082 /// Ordered and equal.
1083 Oeq,
1084 /// Ordered and greater than.
1085 Ogt,
1086 /// Ordered and greater than or equal.
1087 Oge,
1088 /// Ordered and less than.
1089 Olt,
1090 /// Ordered and less than or equal.
1091 Ole,
1092 /// Ordered and not equal.
1093 One,
1094 /// Ordered, which is to say neither operand is a NaN.
1095 Ord,
1096 /// Unordered, which is to say one of them is.
1097 Uno,
1098 /// Unordered or equal.
1099 Ueq,
1100 /// Unordered or greater than.
1101 Ugt,
1102 /// Unordered or greater than or equal.
1103 Uge,
1104 /// Unordered or less than.
1105 Ult,
1106 /// Unordered or less than or equal.
1107 Ule,
1108 /// Unordered or not equal.
1109 Une,
1110 /// Always true.
1111 True,
1112}
1113
1114impl FloatPred {
1115 /// The textual form.
1116 #[must_use]
1117 pub const fn name(self) -> &'static str {
1118 match self {
1119 Self::False => "false",
1120 Self::Oeq => "oeq",
1121 Self::Ogt => "ogt",
1122 Self::Oge => "oge",
1123 Self::Olt => "olt",
1124 Self::Ole => "ole",
1125 Self::One => "one",
1126 Self::Ord => "ord",
1127 Self::Uno => "uno",
1128 Self::Ueq => "ueq",
1129 Self::Ugt => "ugt",
1130 Self::Uge => "uge",
1131 Self::Ult => "ult",
1132 Self::Ule => "ule",
1133 Self::Une => "une",
1134 Self::True => "true",
1135 }
1136 }
1137
1138 /// The predicate with that name, if there is one.
1139 #[must_use]
1140 pub fn from_name(name: &str) -> Option<Self> {
1141 Self::all().find(|pred| pred.name() == name)
1142 }
1143
1144 /// Every predicate.
1145 pub fn all() -> impl Iterator<Item = Self> {
1146 [
1147 Self::False,
1148 Self::Oeq,
1149 Self::Ogt,
1150 Self::Oge,
1151 Self::Olt,
1152 Self::Ole,
1153 Self::One,
1154 Self::Ord,
1155 Self::Uno,
1156 Self::Ueq,
1157 Self::Ugt,
1158 Self::Uge,
1159 Self::Ult,
1160 Self::Ule,
1161 Self::Une,
1162 Self::True,
1163 ]
1164 .into_iter()
1165 }
1166
1167 /// The predicate that holds exactly when this one does not.
1168 #[must_use]
1169 pub const fn inverse(self) -> Self {
1170 match self {
1171 Self::False => Self::True,
1172 Self::Oeq => Self::Une,
1173 Self::Ogt => Self::Ule,
1174 Self::Oge => Self::Ult,
1175 Self::Olt => Self::Uge,
1176 Self::Ole => Self::Ugt,
1177 Self::One => Self::Ueq,
1178 Self::Ord => Self::Uno,
1179 Self::Uno => Self::Ord,
1180 Self::Ueq => Self::One,
1181 Self::Ugt => Self::Ole,
1182 Self::Uge => Self::Olt,
1183 Self::Ult => Self::Oge,
1184 Self::Ule => Self::Ogt,
1185 Self::Une => Self::Oeq,
1186 Self::True => Self::False,
1187 }
1188 }
1189
1190 /// The predicate that holds when the operands are given the other way round.
1191 #[must_use]
1192 pub const fn swapped(self) -> Self {
1193 match self {
1194 Self::Ogt => Self::Olt,
1195 Self::Olt => Self::Ogt,
1196 Self::Oge => Self::Ole,
1197 Self::Ole => Self::Oge,
1198 Self::Ugt => Self::Ult,
1199 Self::Ult => Self::Ugt,
1200 Self::Uge => Self::Ule,
1201 Self::Ule => Self::Uge,
1202 same => same,
1203 }
1204 }
1205
1206 /// Whether this is false when either operand is a NaN.
1207 ///
1208 /// [`FloatPred::False`] and [`FloatPred::True`] are neither ordered nor unordered, since
1209 /// they do not look at their operands at all, and both answer no here.
1210 #[must_use]
1211 pub const fn is_ordered(self) -> bool {
1212 matches!(
1213 self,
1214 Self::Oeq | Self::Ogt | Self::Oge | Self::Olt | Self::Ole | Self::One | Self::Ord
1215 )
1216 }
1217}
1218
1219impl fmt::Display for FloatPred {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 f.write_str(self.name())
1222 }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227 use super::*;
1228
1229 #[test]
1230 fn every_opcode_is_in_the_table() {
1231 // `InlineAsm` is the last variant, so its discriminant plus one is how many there are.
1232 // A new opcode declared after it moves this number, and a new opcode declared before
1233 // it and not added to `ALL` moves the length, so either mistake fails here.
1234 assert_eq!(ALL.len(), Opcode::InlineAsm as usize + 1);
1235 for (position, &op) in ALL.iter().enumerate() {
1236 assert_eq!(op as usize, position, "{op} is out of order in ALL");
1237 }
1238 }
1239
1240 #[test]
1241 fn every_opcode_name_is_one_word_the_reader_can_take() {
1242 // The textual form keeps the dot for the type suffix and the flags, so an opcode with a
1243 // dot in it reads back as a shorter opcode with a suffix that is not a type. The safety
1244 // instructions are spelled `cap_of` and not `cap.of` for this reason, and the
1245 // specification says so at `spec/safe-memory/06-instrumentation.md` section 6.2.2.
1246 for opcode in Opcode::all() {
1247 let name = opcode.name();
1248 assert!(!name.is_empty(), "an opcode with no name");
1249 assert!(
1250 name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
1251 "{name} is not one word"
1252 );
1253 }
1254 }
1255
1256 #[test]
1257 fn every_opcode_has_its_own_name_and_finds_it_again() {
1258 let mut names: Vec<&str> = Opcode::all().map(Opcode::name).collect();
1259 let total = names.len();
1260 names.sort_unstable();
1261 names.dedup();
1262 assert_eq!(names.len(), total, "two opcodes share a name");
1263 for op in Opcode::all() {
1264 assert_eq!(Opcode::from_name(op.name()), Some(op));
1265 }
1266 assert_eq!(Opcode::from_name("phi"), None);
1267 assert_eq!(Opcode::from_name("getelementptr"), None);
1268 assert_eq!(Opcode::from_name(""), None);
1269 }
1270
1271 #[test]
1272 fn the_terminators_are_the_ones_control_leaves_by() {
1273 let terminators: Vec<&str> =
1274 Opcode::all().filter(|op| op.is_terminator()).map(Opcode::name).collect();
1275 assert_eq!(
1276 terminators,
1277 ["jump", "br_if", "switch", "indirect_br", "return", "unreachable", "tail_call"]
1278 );
1279 }
1280
1281 #[test]
1282 fn a_terminator_produces_nothing() {
1283 for op in Opcode::all().filter(|op| op.is_terminator()) {
1284 assert_eq!(op.results(), Some(0), "{op}");
1285 }
1286 }
1287
1288 #[test]
1289 fn the_pair_producing_opcodes_are_the_ones_with_a_flag_beside_the_value() {
1290 let pairs: Vec<&str> =
1291 Opcode::all().filter(|op| op.results() == Some(2)).map(Opcode::name).collect();
1292 assert_eq!(
1293 pairs,
1294 [
1295 "cmpxchg",
1296 "sadd_overflow",
1297 "uadd_overflow",
1298 "ssub_overflow",
1299 "usub_overflow",
1300 "smul_overflow",
1301 "umul_overflow"
1302 ]
1303 );
1304 }
1305
1306 #[test]
1307 fn the_capability_instructions_are_the_ones_that_make_a_capability() {
1308 let makers: Vec<Opcode> = Opcode::all().filter(|op| op.makes_capability()).collect();
1309 assert_eq!(
1310 makers,
1311 vec![
1312 Opcode::CapOf,
1313 Opcode::CapLoad,
1314 Opcode::CapNull,
1315 Opcode::CapNarrow,
1316 Opcode::CapRecover
1317 ]
1318 );
1319 // The sixth is the one that writes a capability rather than making one, so it produces
1320 // nothing at all and is not on the list.
1321 assert!(!Opcode::CapStore.makes_capability());
1322 assert_eq!(Opcode::CapStore.results(), Some(0));
1323 for opcode in makers {
1324 assert_eq!(opcode.results(), Some(1), "{}", opcode.name());
1325 }
1326 }
1327
1328 #[test]
1329 fn a_check_reads_the_planes_and_writes_nothing() {
1330 let checks = [
1331 Opcode::CheckBounds,
1332 Opcode::CheckLive,
1333 Opcode::CheckType,
1334 Opcode::CheckInit,
1335 Opcode::CheckDeriv,
1336 Opcode::CheckRace,
1337 ];
1338 for opcode in checks {
1339 let name = opcode.name();
1340 // It traps, so it stays where it was put and nothing deletes it for having no
1341 // result. It reads a plane, so it takes a memory operand. It writes nothing, so
1342 // the access after it reads the version the check was given.
1343 assert!(opcode.has_effects(), "{name}");
1344 assert!(opcode.touches_memory(), "{name}");
1345 assert!(!opcode.writes_memory(), "{name}");
1346 assert_eq!(opcode.results(), Some(0), "{name}");
1347 }
1348 }
1349
1350 #[test]
1351 fn the_capability_instructions_that_touch_memory_are_the_three_that_have_to() {
1352 // `cap_load` and `cap_store` are an access to the slot beside a pointer and
1353 // `cap_recover` reads the planes. The other three are arithmetic on a provenance the
1354 // program already had, so the optimizer may treat them as it treats `ptr_add`.
1355 assert!(!Opcode::CapOf.has_effects());
1356 assert!(!Opcode::CapNull.has_effects());
1357 assert!(!Opcode::CapNarrow.has_effects());
1358 assert!(Opcode::CapLoad.touches_memory() && !Opcode::CapLoad.writes_memory());
1359 assert!(Opcode::CapRecover.touches_memory() && !Opcode::CapRecover.writes_memory());
1360 assert!(Opcode::CapStore.writes_memory());
1361 }
1362
1363 #[test]
1364 fn memory_has_effects_and_arithmetic_does_not() {
1365 for op in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Alloca, Opcode::Fence] {
1366 assert!(op.has_effects(), "{op}");
1367 }
1368 for op in [Opcode::Add, Opcode::FDiv, Opcode::ICmp, Opcode::PtrAdd, Opcode::IConst] {
1369 assert!(!op.has_effects(), "{op}");
1370 }
1371 }
1372
1373 #[test]
1374 fn commuting_is_only_claimed_where_it_holds() {
1375 assert!(Opcode::Add.is_commutative());
1376 assert!(Opcode::FAdd.is_commutative());
1377 assert!(!Opcode::Sub.is_commutative());
1378 assert!(!Opcode::FDiv.is_commutative());
1379 assert!(!Opcode::Shl.is_commutative());
1380 }
1381
1382 #[test]
1383 fn an_integer_predicate_inverts_and_swaps_back_to_itself() {
1384 for pred in IntPred::all() {
1385 assert_eq!(pred.inverse().inverse(), pred);
1386 assert_eq!(pred.swapped().swapped(), pred);
1387 assert_eq!(IntPred::from_name(pred.name()), Some(pred));
1388 }
1389 assert_eq!(IntPred::Slt.inverse(), IntPred::Sge);
1390 assert_eq!(IntPred::Slt.swapped(), IntPred::Sgt);
1391 assert_eq!(IntPred::from_name("lt"), None);
1392 }
1393
1394 #[test]
1395 fn a_floating_predicate_inverts_across_the_ordered_line() {
1396 for pred in FloatPred::all() {
1397 assert_eq!(pred.inverse().inverse(), pred);
1398 assert_eq!(pred.swapped().swapped(), pred);
1399 assert_eq!(FloatPred::from_name(pred.name()), Some(pred));
1400 }
1401 // Inverting has to cross the line, because the negation of an ordered comparison is
1402 // true when an operand is a NaN. This is where `!(a < b)` stops being `a >= b`. The
1403 // two constants are outside it: neither of them looks at its operands.
1404 for pred in FloatPred::all().filter(|p| !matches!(p, FloatPred::False | FloatPred::True)) {
1405 assert_ne!(pred.is_ordered(), pred.inverse().is_ordered(), "{pred}");
1406 }
1407 assert_eq!(FloatPred::Olt.inverse(), FloatPred::Uge);
1408 assert_eq!(FloatPred::Olt.swapped(), FloatPred::Ogt);
1409 }
1410
1411 #[test]
1412 fn swapping_a_predicate_keeps_it_ordered_or_unordered() {
1413 for pred in FloatPred::all() {
1414 assert_eq!(pred.is_ordered(), pred.swapped().is_ordered(), "{pred}");
1415 }
1416 for pred in IntPred::all() {
1417 assert_eq!(pred.is_signed(), pred.swapped().is_signed(), "{pred}");
1418 }
1419 }
1420
1421 #[test]
1422 fn no_two_predicates_share_a_name_within_their_family() {
1423 for names in [
1424 IntPred::all().map(IntPred::name).collect::<Vec<_>>(),
1425 FloatPred::all().map(FloatPred::name).collect::<Vec<_>>(),
1426 ] {
1427 let total = names.len();
1428 let mut names = names;
1429 names.sort_unstable();
1430 names.dedup();
1431 assert_eq!(names.len(), total);
1432 }
1433 }
1434}