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 /// How many bytes from an address on the capability covers, asking for no more than a limit.
193 ///
194 /// Three operands, the capability, the address and how many bytes the asker wants, and one
195 /// integer result that is never more than that limit. It is what
196 /// `spec/safe-memory/07-check-elimination.md` section 7.4 needs to split a loop: the checked
197 /// part and the unchecked part are divided at `min(n, extent / sizeof(T))`, and the extent is
198 /// the half of that a compiler cannot work out on its own.
199 ///
200 /// The limit is an operand because under milestone S1 answering means walking the lifetime
201 /// plane, and a walk that stops at the number of bytes the loop was going to read anyway is
202 /// bounded by the work the loop is already doing. An answer smaller than the truth costs
203 /// iterations in the checked half and is never wrong, which is what makes stopping early
204 /// allowed. Once a capability carries its own bounds, which is milestone S2, this is a
205 /// subtraction on the capability and the limit is one `min`.
206 CapExtent,
207 /// How many bytes below an address on the capability covers, asking for no more than a limit.
208 ///
209 /// The mirror of [`Opcode::CapExtent`], with the same three operands and the same kind of
210 /// answer. What it counts is the bytes ending at the address rather than the bytes starting
211 /// there, so an answer of `n` says that `[addr - n, addr)` belongs to one thing. The address
212 /// itself is one past what is asked about, which is what a walk from high to low needs: the
213 /// question is about where the walk ends up, and where it ends up is below where it began.
214 ///
215 /// The ownership asked about is the byte below the address rather than the byte at it, since
216 /// the address may be one past the end of the object and the object is what the question is
217 /// about. Everything else, the limit operand and why an answer short of the truth is allowed,
218 /// is [`Opcode::CapExtent`]'s.
219 CapExtentBack,
220 /// An access is within its capability's bounds, aligned, and permitted.
221 ///
222 /// The size and the alignment are the access's, and they are in the memory payload rather
223 /// than in operands because they are what the front end knew and not what the program
224 /// computed.
225 ///
226 /// A third operand overrides how many bytes are asked about, and it exists for the one check
227 /// the front end did not write. `spec/safe-memory/07-check-elimination.md` section 7.4 replaces
228 /// the checks in a loop that runs `n` times with one check over `n * sizeof(T)` bytes, and that
229 /// is a length the program computes rather than one anybody knew when the access was parsed. The
230 /// payload still holds the alignment and the type information of the access the check came from,
231 /// and its size becomes the size of one of them rather than the size of the question.
232 CheckBounds,
233 /// The capability's provenance is still live.
234 CheckLive,
235 /// The access agrees with the type plane, which is the effective type rule of C 6.5.
236 CheckType,
237 /// The bytes the access reads have been written.
238 CheckInit,
239 /// A pointer derived from another stays inside the capability the first one had.
240 ///
241 /// Three operands, because the answer is about the new pointer and the question is about
242 /// the old one's capability.
243 CheckDeriv,
244 /// The metadata this access is about to consult has not been changed under it.
245 ///
246 /// Judgement J9, which document 09 section 9.5 specifies and which document 04 section 4.5
247 /// keeps out of J1 for the reason the `restrict` checks are kept out: it is a statement about
248 /// two operations rather than about one. The payload holds the size of the access, because the
249 /// question is whether any granule of the range this touches carries a write by another thread.
250 CheckRace,
251 /// This read did not reach a byte another `restrict` pointer of the same block wrote.
252 ///
253 /// Judgement J8, which document 09 section 9.6 specifies and which document 04 section 4.6
254 /// keeps out of J1 because it is a statement about a pair of accesses rather than about one.
255 /// The payload holds the size of the access and the two numbers saying which pointer it went
256 /// through, and those are the same two [`crate::Restrict`] carries on the access itself.
257 ///
258 /// Read and write are two opcodes rather than one with a flag on it, because every bit of
259 /// [`crate::Flags`] is spoken for and because the operand would then be a constant the program
260 /// does not compute, which is the thing [`Opcode::CheckBounds`] says belongs in the payload.
261 CheckRestrictRead,
262 /// The same about a write, which is the half of the pair that makes the other half a violation.
263 ///
264 /// Two accesses that both only read are not a violation of anything, so what the scope records
265 /// is which of them wrote and the check refuses a pair only when at least one did.
266 CheckRestrictWrite,
267 /// A storage instance begins here, over a range, with a class.
268 ///
269 /// Judgement J4. This is the `alloca` for an automatic instance and the allocator's report
270 /// for an allocated one, and the range is a pointer and a length in registers rather than a
271 /// payload, because the length of a variable length array is not known when the instruction
272 /// is written down.
273 MetaBegin,
274 /// A storage instance ends here, which is judgement J5.
275 ///
276 /// Every capability for it fails from this point on and keeps failing after the address is
277 /// handed out again, which is what makes the check a use after free check rather than a use
278 /// after reallocation one.
279 MetaEnd,
280 /// The effective type of a range is now this one.
281 MetaType,
282 /// The effective types of a range are now the ones the range it was copied from had.
283 ///
284 /// Three operands, because a copy has two ranges and one length: the destination, the source,
285 /// and how many bytes moved. A `memcpy` does not store through a type, so there is no type to
286 /// name here and naming one would be wrong: C 6.5 says the copied bytes keep the effective type
287 /// they had, whatever that was, and the only place that is written down is the plane over the
288 /// source.
289 MetaTypeCopy,
290 /// The bytes of a range are now initialized.
291 MetaInit,
292 /// The bytes of a range are now initialized wherever the range they were copied from was.
293 ///
294 /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three. A copy does not write
295 /// values of its own, so whether a destination byte holds anything is whether the byte it came
296 /// from did, and the only place that is written down is the plane over the source. That is what
297 /// makes a structure filled member by member and then copied whole still have padding nothing
298 /// wrote, which is the infoleak the plane is for.
299 MetaInitCopy,
300 /// This thread wrote a range, at whatever step of its own counting it has reached.
301 ///
302 /// The epoch plane's only write, from `spec/safe-memory/09-type-init-and-races.md` section 9.5.
303 /// Two operands like the other plane writes, and the range is a pointer shaped slot rather than
304 /// whatever the access covered: the plane holds one stamp per eight bytes because that is what
305 /// a pointer comes in, and a granule two threads share is one holding no pointer.
306 ///
307 /// It carries no thread and no count. Which thread is running and how far it has counted are
308 /// both facts about the moment the program reaches this, so the runtime reads them and nothing
309 /// here could name them.
310 MetaEpoch,
311 /// Everything this thread has done so far is published at the atomic object named here.
312 ///
313 /// One half of a synchronization edge in the sense of section 9.5, and the half that goes in
314 /// front of the atomic that carries it. The operand is the object's address, because that is
315 /// the key whoever takes the other end will look the clock up under, and there is no payload:
316 /// which thread is publishing and how far it has counted are facts about the moment the program
317 /// reaches this, the same way they are for [`Opcode::MetaEpoch`].
318 ///
319 /// This exists because an atomic is not a call. Every other edge the monitor knows about is a
320 /// `pthread` function and is interposed, and a C11 release store is a machine instruction with
321 /// nothing to interpose, so the compiler is the only thing that can say the edge was there.
322 MetaRelease,
323 /// Everything published at the atomic object named here is now ordered before this thread.
324 ///
325 /// The other half of [`Opcode::MetaRelease`], and it goes after the atomic rather than in front
326 /// of it, because the ordering it takes is the ordering the atomic just read.
327 ///
328 /// A missing edge is the one kind of missing instrumentation in the whole safety pass that
329 /// costs a false report rather than a missed one: two threads that really were ordered by an
330 /// edge nobody recorded look concurrent, and a race is reported against a program doing nothing
331 /// wrong. That is why the edges go in before the race check is ever on by default.
332 MetaAcquire,
333 /// Everything this thread has done so far is published at no object in particular.
334 ///
335 /// What a release fence is, and the reason it cannot reuse [`Opcode::MetaRelease`]: a fence
336 /// orders against every other thread rather than against one object, so there is no address to
337 /// key it on and it takes no operands at all. The relaxed atomic that usually sits beside it in
338 /// the source is not the key either, because the fence orders everything, not that one word.
339 ///
340 /// The runtime pays for that with one cell shared by every fence in the program, which orders
341 /// more pairs of threads than the program really ordered. That direction is safe. A thread put
342 /// further ahead than it needed to be reports fewer races, never a wrong one.
343 MetaFenceRelease,
344 /// Everything published at any release fence is now ordered before this thread.
345 ///
346 /// The other half of [`Opcode::MetaFenceRelease`], after the fence rather than in front of it,
347 /// for the same reason [`Opcode::MetaAcquire`] goes after its atomic.
348 MetaFenceAcquire,
349 /// A range leaves the monitor's authority, or comes back, which is judgement J7.
350 MetaTransfer,
351 /// A declared exemption starts here, with the reason it was declared.
352 ///
353 /// Not an optimization hint. Everything between this and its `safe_region_end` is code the
354 /// monitor is told not to judge, so the reason it carries is a trust set entry, and
355 /// `spec/safe-memory/10-boundaries.md` section 10.2 counts them per build precisely so that
356 /// a reviewer can read what a binary's guarantee rests on.
357 SafeRegionBegin,
358 /// The end of the region the last `safe_region_begin` opened.
359 SafeRegionEnd,
360 /// A block that declares `restrict` pointers begins here, over a slot to keep its record in.
361 ///
362 /// The operand is the storage the record lives in, which is the block's own stack slot, and the
363 /// payload says how large it is. The clique the block was given is [`crate::Restrict::clique`]
364 /// of the payload and how many pointers it declares is [`crate::Restrict::base`], which is the
365 /// one place that field counts bases rather than naming one.
366 ///
367 /// A marker rather than something the front end could fold into the accesses, because the
368 /// promise is about the block's dynamic extent: a function called twice has made the promise
369 /// twice, and what the second call reached says nothing about the first.
370 RestrictEnter,
371 /// The block the last `restrict_enter` opened ends here.
372 ///
373 /// The operand is the same slot, so that the record can be unlinked from whatever encloses it
374 /// without the runtime having to keep a list of its own.
375 RestrictLeave,
376
377 // Control. Every one of these is a terminator.
378 /// An unconditional branch, `jump block1(%a, %b)`.
379 Jump,
380 /// A two-way branch on an `i1`.
381 BrIf,
382 /// A multi-way branch on an integer, with a default.
383 Switch,
384 /// A branch to an address, `indirect_br %0, block1, block2`.
385 ///
386 /// The targets are every block control can arrive at, which is what makes the edges of a
387 /// computed `goto` ordinary edges: nothing else in the compiler has to know that the
388 /// address decides which one it is. A target that is not listed is a branch that does not
389 /// happen, so a frontend that leaves one out has made a promise on the program's behalf.
390 IndirectBr,
391 /// A return, with the values the signature says.
392 Return,
393 /// A place control cannot reach, which the frontend emits after a `noreturn` call.
394 Unreachable,
395
396 // Calls.
397 /// A call to a named function.
398 Call,
399 /// A call through an address, carrying the signature it is called with.
400 CallIndirect,
401 /// A call in tail position that reuses the frame, which is a terminator.
402 TailCall,
403
404 // Intrinsics, which is the closed part. The open part is `TargetIntrinsic`.
405 /// Count leading zeroes.
406 Ctlz,
407 /// Count trailing zeroes.
408 Cttz,
409 /// Count set bits.
410 Ctpop,
411 /// Reverse the bytes.
412 Bswap,
413 /// Reverse the bits.
414 Bitreverse,
415 /// Signed addition, producing the result and whether it overflowed.
416 SAddOverflow,
417 /// Unsigned addition, producing the result and whether it overflowed.
418 UAddOverflow,
419 /// Signed subtraction, producing the result and whether it overflowed.
420 SSubOverflow,
421 /// Unsigned subtraction, producing the result and whether it overflowed.
422 USubOverflow,
423 /// Signed multiplication, producing the result and whether it overflowed.
424 SMulOverflow,
425 /// Unsigned multiplication, producing the result and whether it overflowed.
426 UMulOverflow,
427 /// `__builtin_expect`, which is the value with a hint attached.
428 Expect,
429 /// `__builtin_unreachable` as a hint on a path, distinct from the terminator.
430 UnreachableHint,
431 /// `__builtin_prefetch`.
432 Prefetch,
433 /// `__builtin_frame_address`.
434 FrameAddress,
435 /// `__builtin_return_address`.
436 ReturnAddress,
437 /// The start of a variable argument list.
438 VaStart,
439 /// One argument off a variable argument list, which moves the list on as it reads it. Two
440 /// of these on one list are two arguments and never one argument read twice, so whatever
441 /// decides which instructions may be folded together has to leave these alone.
442 VaArg,
443 /// One argument off a variable argument list, when that argument is an object rather than a
444 /// value, which is what a `struct` or a `union` read out of one is.
445 ///
446 /// It answers the address of the object rather than the object, because an aggregate is not
447 /// a value and there is nothing for one result to be. Where the object arrives in registers
448 /// there is no address until something makes one, so what this asks of a target is a place
449 /// to put the registers and the address of that place, which is the copy every psABI's own
450 /// description of the algorithm makes. It moves the list on for the reason [`Opcode::VaArg`]
451 /// does.
452 VaObject,
453 /// The end of a variable argument list.
454 VaEnd,
455 /// A copy of a variable argument list.
456 VaCopy,
457 /// The stack pointer, saved before a variable length array.
458 StackSave,
459 /// The stack pointer, restored after one.
460 StackRestore,
461 /// The marker a `setjmp` leaves, which pins everything live across it.
462 SetjmpMarker,
463 /// The marker a `longjmp` leaves.
464 LongjmpMarker,
465 /// A target-specific intrinsic, named rather than enumerated, for the vector builtins.
466 TargetIntrinsic,
467
468 /// Inline assembly. A terminator when it has labels, which is `asm goto`.
469 InlineAsm,
470}
471
472impl Opcode {
473 /// The textual form, which is also what the parser reads.
474 #[must_use]
475 pub const fn name(self) -> &'static str {
476 match self {
477 Self::IConst => "iconst",
478 Self::FConst => "fconst",
479 Self::Splat => "splat",
480 Self::GlobalAddr => "global_addr",
481 Self::BlockAddr => "block_addr",
482 Self::Add => "add",
483 Self::Sub => "sub",
484 Self::Mul => "mul",
485 Self::SDiv => "sdiv",
486 Self::UDiv => "udiv",
487 Self::SRem => "srem",
488 Self::URem => "urem",
489 Self::And => "and",
490 Self::Or => "or",
491 Self::Xor => "xor",
492 Self::Shl => "shl",
493 Self::LShr => "lshr",
494 Self::AShr => "ashr",
495 Self::FAdd => "fadd",
496 Self::FSub => "fsub",
497 Self::FMul => "fmul",
498 Self::FDiv => "fdiv",
499 Self::FRem => "frem",
500 Self::FNeg => "fneg",
501 Self::Fma => "fma",
502 Self::ICmp => "icmp",
503 Self::FCmp => "fcmp",
504 Self::Select => "select",
505 Self::Trunc => "trunc",
506 Self::SExt => "sext",
507 Self::ZExt => "zext",
508 Self::FPTrunc => "fptrunc",
509 Self::FPExt => "fpext",
510 Self::FPToSI => "fptosi",
511 Self::FPToUI => "fptoui",
512 Self::SIToFP => "sitofp",
513 Self::UIToFP => "uitofp",
514 Self::PtrToInt => "ptrtoint",
515 Self::IntToPtr => "inttoptr",
516 Self::Bitcast => "bitcast",
517 Self::MemEntry => "mem_entry",
518 Self::Alloca => "alloca",
519 Self::Load => "load",
520 Self::Store => "store",
521 Self::PtrAdd => "ptr_add",
522 Self::Memcpy => "memcpy",
523 Self::Memmove => "memmove",
524 Self::Memset => "memset",
525 Self::AtomicLoad => "atomic_load",
526 Self::AtomicStore => "atomic_store",
527 Self::AtomicRmw => "atomic_rmw",
528 Self::Cmpxchg => "cmpxchg",
529 Self::Fence => "fence",
530 Self::CapOf => "cap_of",
531 Self::CapLoad => "cap_load",
532 Self::CapStore => "cap_store",
533 Self::CapNull => "cap_null",
534 Self::CapNarrow => "cap_narrow",
535 Self::CapRecover => "cap_recover",
536 Self::CapExtent => "cap_extent",
537 Self::CapExtentBack => "cap_extent_back",
538 Self::CheckBounds => "check_bounds",
539 Self::CheckLive => "check_live",
540 Self::CheckType => "check_type",
541 Self::CheckInit => "check_init",
542 Self::CheckDeriv => "check_deriv",
543 Self::CheckRace => "check_race",
544 Self::CheckRestrictRead => "check_restrict_read",
545 Self::CheckRestrictWrite => "check_restrict_write",
546 Self::MetaBegin => "meta_begin",
547 Self::MetaEnd => "meta_end",
548 Self::MetaType => "meta_type",
549 Self::MetaTypeCopy => "meta_type_copy",
550 Self::MetaInit => "meta_init",
551 Self::MetaInitCopy => "meta_init_copy",
552 Self::MetaEpoch => "meta_epoch",
553 Self::MetaRelease => "meta_release",
554 Self::MetaAcquire => "meta_acquire",
555 Self::MetaFenceRelease => "meta_fence_release",
556 Self::MetaFenceAcquire => "meta_fence_acquire",
557 Self::MetaTransfer => "meta_transfer",
558 Self::SafeRegionBegin => "safe_region_begin",
559 Self::SafeRegionEnd => "safe_region_end",
560 Self::RestrictEnter => "restrict_enter",
561 Self::RestrictLeave => "restrict_leave",
562 Self::Jump => "jump",
563 Self::BrIf => "br_if",
564 Self::Switch => "switch",
565 Self::IndirectBr => "indirect_br",
566 Self::Return => "return",
567 Self::Unreachable => "unreachable",
568 Self::Call => "call",
569 Self::CallIndirect => "call_indirect",
570 Self::TailCall => "tail_call",
571 Self::Ctlz => "ctlz",
572 Self::Cttz => "cttz",
573 Self::Ctpop => "ctpop",
574 Self::Bswap => "bswap",
575 Self::Bitreverse => "bitreverse",
576 Self::SAddOverflow => "sadd_overflow",
577 Self::UAddOverflow => "uadd_overflow",
578 Self::SSubOverflow => "ssub_overflow",
579 Self::USubOverflow => "usub_overflow",
580 Self::SMulOverflow => "smul_overflow",
581 Self::UMulOverflow => "umul_overflow",
582 Self::Expect => "expect",
583 Self::UnreachableHint => "unreachable_hint",
584 Self::Prefetch => "prefetch",
585 Self::FrameAddress => "frame_address",
586 Self::ReturnAddress => "return_address",
587 Self::VaStart => "va_start",
588 Self::VaArg => "va_arg",
589 Self::VaObject => "va_object",
590 Self::VaEnd => "va_end",
591 Self::VaCopy => "va_copy",
592 Self::StackSave => "stacksave",
593 Self::StackRestore => "stackrestore",
594 Self::SetjmpMarker => "setjmp_marker",
595 Self::LongjmpMarker => "longjmp_marker",
596 Self::TargetIntrinsic => "target_intrinsic",
597 Self::InlineAsm => "inline_asm",
598 }
599 }
600
601 /// Every opcode, in the order they are declared.
602 ///
603 /// The parser walks this rather than holding a second table, because a second table is a
604 /// table that can disagree with the first one.
605 pub fn all() -> impl Iterator<Item = Self> {
606 ALL.iter().copied()
607 }
608
609 /// The opcode with that name, if there is one.
610 #[must_use]
611 pub fn from_name(name: &str) -> Option<Self> {
612 ALL.iter().copied().find(|op| op.name() == name)
613 }
614
615 /// Whether this ends a block.
616 ///
617 /// [`Opcode::InlineAsm`] is not here and is the one instruction whose answer depends on
618 /// the instruction rather than on the opcode: `asm goto` has successors and everything
619 /// else does not. Ask the instruction, not the opcode.
620 #[must_use]
621 pub const fn is_terminator(self) -> bool {
622 matches!(
623 self,
624 Self::Jump
625 | Self::BrIf
626 | Self::Switch
627 | Self::IndirectBr
628 | Self::Return
629 | Self::Unreachable
630 | Self::TailCall
631 )
632 }
633
634 /// Whether the operands can be swapped without changing the result.
635 ///
636 /// The floating point cases are commutative even under the strictest rounding, because
637 /// swapping the operands of an addition does not change which of them is a NaN, and the
638 /// sign of a NaN result is not something we promise anything about either way.
639 #[must_use]
640 pub const fn is_commutative(self) -> bool {
641 matches!(
642 self,
643 Self::Add
644 | Self::Mul
645 | Self::And
646 | Self::Or
647 | Self::Xor
648 | Self::FAdd
649 | Self::FMul
650 | Self::SAddOverflow
651 | Self::UAddOverflow
652 | Self::SMulOverflow
653 | Self::UMulOverflow
654 )
655 }
656
657 /// Whether this reads or writes memory, or has an effect the optimizer has to preserve.
658 ///
659 /// An instruction that answers no can be deleted when nothing uses its result, moved
660 /// across a call, and merged with another one computing the same thing. Everything else
661 /// has to be argued about individually, so the conservative answer is the true one here
662 /// and the list of exceptions is the part that is checked.
663 #[must_use]
664 pub const fn has_effects(self) -> bool {
665 !matches!(
666 self,
667 Self::IConst
668 | Self::FConst
669 | Self::Splat
670 | Self::GlobalAddr
671 | Self::BlockAddr
672 | Self::Add
673 | Self::Sub
674 | Self::Mul
675 | Self::SDiv
676 | Self::UDiv
677 | Self::SRem
678 | Self::URem
679 | Self::And
680 | Self::Or
681 | Self::Xor
682 | Self::Shl
683 | Self::LShr
684 | Self::AShr
685 | Self::FAdd
686 | Self::FSub
687 | Self::FMul
688 | Self::FDiv
689 | Self::FRem
690 | Self::FNeg
691 | Self::Fma
692 | Self::ICmp
693 | Self::FCmp
694 | Self::Select
695 | Self::Trunc
696 | Self::SExt
697 | Self::ZExt
698 | Self::FPTrunc
699 | Self::FPExt
700 | Self::FPToSI
701 | Self::FPToUI
702 | Self::SIToFP
703 | Self::UIToFP
704 | Self::PtrToInt
705 | Self::IntToPtr
706 | Self::Bitcast
707 | Self::PtrAdd
708 | Self::Ctlz
709 | Self::Cttz
710 | Self::Ctpop
711 | Self::Bswap
712 | Self::Bitreverse
713 | Self::SAddOverflow
714 | Self::UAddOverflow
715 | Self::SSubOverflow
716 | Self::USubOverflow
717 | Self::SMulOverflow
718 | Self::UMulOverflow
719 | Self::Expect
720 | Self::FrameAddress
721 | Self::ReturnAddress
722 | Self::MemEntry
723 // Three of the capability instructions are arithmetic on a pointer's
724 // provenance and touch nothing. The other three do: `cap_load` and
725 // `cap_store` are an access, and `cap_recover` reads the planes.
726 | Self::CapOf
727 | Self::CapNull
728 | Self::CapNarrow
729 )
730 }
731
732 /// Whether an instruction with this opcode touches memory.
733 ///
734 /// This is what decides whether it takes a memory operand once memory SSA is built, per
735 /// document 09 of `spec/optimizer`. It is written as the exceptions to touching memory
736 /// rather than as a list of what does, for the reason document 08.6 gives about the escape
737 /// analysis: an opcode added later has to end up on the conservative side by default, and a
738 /// list of what touches memory would silently leave a new one out.
739 ///
740 /// `mem_entry` answers no. It produces memory rather than touching it, which is the whole
741 /// of what it is for.
742 #[must_use]
743 pub const fn touches_memory(self) -> bool {
744 if !self.has_effects() {
745 return false;
746 }
747 !matches!(
748 self,
749 // Fresh storage nothing could have been reading, and the pointer that names it.
750 Self::Alloca
751 // The stack pointer, which is a register and not memory. Putting it back is a
752 // different matter and is below, because it takes storage away.
753 | Self::StackSave
754 // Control, which goes somewhere rather than touching anything. A tail call is
755 // not here, because it is a call.
756 | Self::Jump
757 | Self::BrIf
758 | Self::Switch
759 | Self::IndirectBr
760 | Self::Return
761 | Self::Unreachable
762 | Self::UnreachableHint
763 )
764 }
765
766 /// Whether an instruction with this opcode writes memory, and so produces a new version of
767 /// it rather than only reading the version it was given.
768 ///
769 /// Everything that touches memory writes it except the ones that plainly do not. A `fence`
770 /// writes nothing and is still a write here, because document 09.5 says an atomic or a
771 /// barrier is a definition nothing walks past, and giving it one is how that is expressed
772 /// in a representation whose only ordering is the memory chain.
773 ///
774 /// The checks read the planes and change nothing, which
775 /// `spec/safe-memory/06-instrumentation.md` section 6.2.4 states as the word `readonly`. A
776 /// check that trapped is a program that stopped and there is no version of memory after it
777 /// for anything to observe, so the trap costs nothing here. What it does cost is that a
778 /// check may not be moved across a plane write, and that is the memory chain saying so
779 /// rather than this.
780 #[must_use]
781 pub const fn writes_memory(self) -> bool {
782 self.touches_memory()
783 && !matches!(
784 self,
785 Self::Load
786 | Self::AtomicLoad
787 | Self::Prefetch
788 | Self::CapLoad
789 | Self::CapRecover
790 | Self::CapExtent
791 | Self::CapExtentBack
792 | Self::CheckBounds
793 | Self::CheckLive
794 | Self::CheckType
795 | Self::CheckInit
796 | Self::CheckDeriv
797 | Self::CheckRace
798 )
799 }
800
801 /// How many values this produces, for the opcodes where the count is fixed.
802 ///
803 /// `None` means the count comes from somewhere else: a call takes it from its signature,
804 /// and inline assembly takes it from its output constraints. A tail call is not one of
805 /// them, because whatever it returns goes straight out of the function and there is no
806 /// instruction after it to use anything.
807 #[must_use]
808 pub const fn results(self) -> Option<u8> {
809 match self {
810 Self::Call | Self::CallIndirect | Self::InlineAsm => None,
811 Self::Cmpxchg
812 | Self::SAddOverflow
813 | Self::UAddOverflow
814 | Self::SSubOverflow
815 | Self::USubOverflow
816 | Self::SMulOverflow
817 | Self::UMulOverflow => Some(2),
818 Self::Store
819 | Self::Memcpy
820 | Self::Memmove
821 | Self::Memset
822 | Self::AtomicStore
823 | Self::Fence
824 | Self::Prefetch
825 | Self::VaStart
826 | Self::VaEnd
827 | Self::VaCopy
828 | Self::StackRestore
829 | Self::UnreachableHint
830 | Self::SetjmpMarker
831 | Self::LongjmpMarker
832 | Self::CapStore
833 | Self::CheckBounds
834 | Self::CheckLive
835 | Self::CheckType
836 | Self::CheckInit
837 | Self::CheckDeriv
838 | Self::CheckRace
839 | Self::CheckRestrictRead
840 | Self::CheckRestrictWrite
841 | Self::MetaBegin
842 | Self::MetaEnd
843 | Self::MetaType
844 | Self::MetaTypeCopy
845 | Self::MetaInit
846 | Self::MetaInitCopy
847 | Self::MetaEpoch
848 | Self::MetaRelease
849 | Self::MetaAcquire
850 | Self::MetaFenceRelease
851 | Self::MetaFenceAcquire
852 | Self::MetaTransfer
853 | Self::SafeRegionBegin
854 | Self::SafeRegionEnd
855 | Self::RestrictEnter
856 | Self::RestrictLeave => Some(0),
857 _ if self.is_terminator() => Some(0),
858 _ => Some(1),
859 }
860 }
861
862 /// Whether an instruction with this opcode produces a capability.
863 ///
864 /// Five of the eight `cap` instructions. The other three consume one instead: `cap_store`
865 /// writes it beside a pointer, and `cap_extent` and `cap_extent_back` ask it a question about
866 /// itself and answer with a number. The reason this is a question about the opcode rather than
867 /// about the
868 /// result type is that the verifier asks it the other way round: it walks the results looking
869 /// for a `cap` and needs to know whether the instruction under it was entitled to make one.
870 #[must_use]
871 pub const fn makes_capability(self) -> bool {
872 matches!(
873 self,
874 Self::CapOf | Self::CapLoad | Self::CapNull | Self::CapNarrow | Self::CapRecover
875 )
876 }
877
878 /// Which payload an instruction with this opcode carries.
879 ///
880 /// The printer reads the payload it finds and does not need this. The parser has only the
881 /// opcode when it reaches the operands, so this is where the two of them agree on what
882 /// comes after them. An instruction carrying a payload of some other kind prints as text
883 /// the parser cannot read back, which is why the verifier checks it against
884 /// [`Extra::kind`](crate::Extra::kind) rather than leaving it to be found later.
885 #[must_use]
886 pub const fn extra_kind(self) -> ExtraKind {
887 match self {
888 Self::IConst | Self::FConst | Self::Splat => ExtraKind::Imm,
889 Self::GlobalAddr | Self::TargetIntrinsic => ExtraKind::Symbol,
890 Self::ICmp => ExtraKind::IntPred,
891 Self::FCmp => ExtraKind::FloatPred,
892 Self::Alloca
893 | Self::Load
894 | Self::Store
895 | Self::Memcpy
896 | Self::Memmove
897 | Self::Memset
898 | Self::AtomicLoad
899 | Self::AtomicStore
900 | Self::Cmpxchg
901 // Four of the checks are about a run of bytes and the payload is where the size
902 // of that run is, along with the alignment `check_bounds` wants and the aliasing
903 // node `check_type` compares against. The other two ask a question about a
904 // pointer and not about a range, so they carry nothing.
905 | Self::CheckBounds
906 | Self::CheckType
907 | Self::CheckInit
908 | Self::CheckRace
909 // The two `restrict` checks and the marker that opens their scope. The first two carry
910 // the size of the access and the two numbers saying which pointer it went through, and
911 // the third carries the size of the slot and the numbers describing the scope itself.
912 | Self::CheckRestrictRead
913 | Self::CheckRestrictWrite
914 | Self::RestrictEnter => ExtraKind::Mem,
915 // The plane writes. What each one needs beyond the range is different, and the range
916 // itself is operands, since the length of a variable length array is a value.
917 Self::MetaBegin => ExtraKind::Class,
918 Self::MetaTransfer => ExtraKind::Owner,
919 Self::MetaType => ExtraKind::Node,
920 Self::SafeRegionBegin => ExtraKind::Reason,
921 Self::VaObject => ExtraKind::VaObject,
922 Self::AtomicRmw => ExtraKind::Rmw,
923 Self::Fence => ExtraKind::Order,
924 Self::Jump | Self::BrIf | Self::BlockAddr | Self::IndirectBr => ExtraKind::Targets,
925 Self::Switch => ExtraKind::Switch,
926 Self::Call | Self::CallIndirect | Self::TailCall => ExtraKind::Call,
927 Self::InlineAsm => ExtraKind::Asm,
928 _ => ExtraKind::None,
929 }
930 }
931}
932
933/// Which of [`Extra`](crate::Extra)'s shapes an instruction carries.
934///
935/// The same list of names, without any of the payloads, so that a question about an opcode can
936/// be answered without an instruction to look at.
937#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
938pub enum ExtraKind {
939 /// Nothing.
940 None,
941 /// A constant.
942 Imm,
943 /// A name.
944 Symbol,
945 /// An integer comparison predicate.
946 IntPred,
947 /// A floating point comparison predicate.
948 FloatPred,
949 /// An access.
950 Mem,
951 /// An atomic read-modify-write.
952 Rmw,
953 /// A barrier's ordering.
954 Order,
955 /// Branch targets.
956 Targets,
957 /// A call.
958 Call,
959 /// A `switch`.
960 Switch,
961 /// Inline assembly.
962 Asm,
963 /// An object read off a variable argument list.
964 VaObject,
965 /// What kind of storage an instance is.
966 Class,
967 /// Who a range of memory went to.
968 Owner,
969 /// A metadata node.
970 Node,
971 /// Why a declared exemption is there.
972 Reason,
973}
974
975impl ExtraKind {
976 /// What it is, in words, for a message that names two of them and has to read as English.
977 #[must_use]
978 pub const fn name(self) -> &'static str {
979 match self {
980 Self::None => "nothing",
981 Self::Imm => "a constant",
982 Self::Symbol => "a name",
983 Self::IntPred => "an integer comparison",
984 Self::FloatPred => "a floating point comparison",
985 Self::Mem => "an access",
986 Self::Rmw => "a read-modify-write",
987 Self::Order => "an ordering",
988 Self::Targets => "branch targets",
989 Self::Call => "a call",
990 Self::Switch => "a switch",
991 Self::Asm => "inline assembly",
992 Self::VaObject => "an object off a variable argument list",
993 Self::Class => "a storage class",
994 Self::Owner => "an owner",
995 Self::Node => "a metadata node",
996 Self::Reason => "a reason",
997 }
998 }
999}
1000
1001impl fmt::Display for Opcode {
1002 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1003 f.write_str(self.name())
1004 }
1005}
1006
1007/// Every opcode, which is what [`Opcode::all`] hands out.
1008///
1009/// This is written out rather than derived, and the test below is what keeps it complete: it
1010/// checks the count against [`Opcode::InlineAsm`], the last variant, so a new opcode that is
1011/// not added here fails the build rather than going quietly missing from the parser.
1012static ALL: &[Opcode] = &[
1013 Opcode::IConst,
1014 Opcode::FConst,
1015 Opcode::Splat,
1016 Opcode::GlobalAddr,
1017 Opcode::BlockAddr,
1018 Opcode::Add,
1019 Opcode::Sub,
1020 Opcode::Mul,
1021 Opcode::SDiv,
1022 Opcode::UDiv,
1023 Opcode::SRem,
1024 Opcode::URem,
1025 Opcode::And,
1026 Opcode::Or,
1027 Opcode::Xor,
1028 Opcode::Shl,
1029 Opcode::LShr,
1030 Opcode::AShr,
1031 Opcode::FAdd,
1032 Opcode::FSub,
1033 Opcode::FMul,
1034 Opcode::FDiv,
1035 Opcode::FRem,
1036 Opcode::FNeg,
1037 Opcode::Fma,
1038 Opcode::ICmp,
1039 Opcode::FCmp,
1040 Opcode::Select,
1041 Opcode::Trunc,
1042 Opcode::SExt,
1043 Opcode::ZExt,
1044 Opcode::FPTrunc,
1045 Opcode::FPExt,
1046 Opcode::FPToSI,
1047 Opcode::FPToUI,
1048 Opcode::SIToFP,
1049 Opcode::UIToFP,
1050 Opcode::PtrToInt,
1051 Opcode::IntToPtr,
1052 Opcode::Bitcast,
1053 Opcode::MemEntry,
1054 Opcode::Alloca,
1055 Opcode::Load,
1056 Opcode::Store,
1057 Opcode::PtrAdd,
1058 Opcode::Memcpy,
1059 Opcode::Memmove,
1060 Opcode::Memset,
1061 Opcode::AtomicLoad,
1062 Opcode::AtomicStore,
1063 Opcode::AtomicRmw,
1064 Opcode::Cmpxchg,
1065 Opcode::Fence,
1066 Opcode::CapOf,
1067 Opcode::CapLoad,
1068 Opcode::CapStore,
1069 Opcode::CapNull,
1070 Opcode::CapNarrow,
1071 Opcode::CapRecover,
1072 Opcode::CapExtent,
1073 Opcode::CapExtentBack,
1074 Opcode::CheckBounds,
1075 Opcode::CheckLive,
1076 Opcode::CheckType,
1077 Opcode::CheckInit,
1078 Opcode::CheckDeriv,
1079 Opcode::CheckRace,
1080 Opcode::CheckRestrictRead,
1081 Opcode::CheckRestrictWrite,
1082 Opcode::MetaBegin,
1083 Opcode::MetaEnd,
1084 Opcode::MetaType,
1085 Opcode::MetaTypeCopy,
1086 Opcode::MetaInit,
1087 Opcode::MetaInitCopy,
1088 Opcode::MetaEpoch,
1089 Opcode::MetaRelease,
1090 Opcode::MetaAcquire,
1091 Opcode::MetaFenceRelease,
1092 Opcode::MetaFenceAcquire,
1093 Opcode::MetaTransfer,
1094 Opcode::SafeRegionBegin,
1095 Opcode::SafeRegionEnd,
1096 Opcode::RestrictEnter,
1097 Opcode::RestrictLeave,
1098 Opcode::Jump,
1099 Opcode::BrIf,
1100 Opcode::Switch,
1101 Opcode::IndirectBr,
1102 Opcode::Return,
1103 Opcode::Unreachable,
1104 Opcode::Call,
1105 Opcode::CallIndirect,
1106 Opcode::TailCall,
1107 Opcode::Ctlz,
1108 Opcode::Cttz,
1109 Opcode::Ctpop,
1110 Opcode::Bswap,
1111 Opcode::Bitreverse,
1112 Opcode::SAddOverflow,
1113 Opcode::UAddOverflow,
1114 Opcode::SSubOverflow,
1115 Opcode::USubOverflow,
1116 Opcode::SMulOverflow,
1117 Opcode::UMulOverflow,
1118 Opcode::Expect,
1119 Opcode::UnreachableHint,
1120 Opcode::Prefetch,
1121 Opcode::FrameAddress,
1122 Opcode::ReturnAddress,
1123 Opcode::VaStart,
1124 Opcode::VaArg,
1125 Opcode::VaObject,
1126 Opcode::VaEnd,
1127 Opcode::VaCopy,
1128 Opcode::StackSave,
1129 Opcode::StackRestore,
1130 Opcode::SetjmpMarker,
1131 Opcode::LongjmpMarker,
1132 Opcode::TargetIntrinsic,
1133 Opcode::InlineAsm,
1134];
1135
1136/// The ten integer comparisons.
1137///
1138/// Signedness is on the predicate rather than on the type, for the same reason it is on
1139/// `sdiv` and `udiv`: the type space is halved and the operation says what it means.
1140#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1141pub enum IntPred {
1142 /// Equal.
1143 Eq,
1144 /// Not equal.
1145 Ne,
1146 /// Signed less than.
1147 Slt,
1148 /// Signed less than or equal.
1149 Sle,
1150 /// Signed greater than.
1151 Sgt,
1152 /// Signed greater than or equal.
1153 Sge,
1154 /// Unsigned less than.
1155 Ult,
1156 /// Unsigned less than or equal.
1157 Ule,
1158 /// Unsigned greater than.
1159 Ugt,
1160 /// Unsigned greater than or equal.
1161 Uge,
1162}
1163
1164impl IntPred {
1165 /// The textual form.
1166 #[must_use]
1167 pub const fn name(self) -> &'static str {
1168 match self {
1169 Self::Eq => "eq",
1170 Self::Ne => "ne",
1171 Self::Slt => "slt",
1172 Self::Sle => "sle",
1173 Self::Sgt => "sgt",
1174 Self::Sge => "sge",
1175 Self::Ult => "ult",
1176 Self::Ule => "ule",
1177 Self::Ugt => "ugt",
1178 Self::Uge => "uge",
1179 }
1180 }
1181
1182 /// The predicate with that name, if there is one.
1183 #[must_use]
1184 pub fn from_name(name: &str) -> Option<Self> {
1185 Self::all().find(|pred| pred.name() == name)
1186 }
1187
1188 /// Every predicate.
1189 pub fn all() -> impl Iterator<Item = Self> {
1190 [
1191 Self::Eq,
1192 Self::Ne,
1193 Self::Slt,
1194 Self::Sle,
1195 Self::Sgt,
1196 Self::Sge,
1197 Self::Ult,
1198 Self::Ule,
1199 Self::Ugt,
1200 Self::Uge,
1201 ]
1202 .into_iter()
1203 }
1204
1205 /// The predicate that holds exactly when this one does not.
1206 #[must_use]
1207 pub const fn inverse(self) -> Self {
1208 match self {
1209 Self::Eq => Self::Ne,
1210 Self::Ne => Self::Eq,
1211 Self::Slt => Self::Sge,
1212 Self::Sge => Self::Slt,
1213 Self::Sle => Self::Sgt,
1214 Self::Sgt => Self::Sle,
1215 Self::Ult => Self::Uge,
1216 Self::Uge => Self::Ult,
1217 Self::Ule => Self::Ugt,
1218 Self::Ugt => Self::Ule,
1219 }
1220 }
1221
1222 /// The predicate that holds when the operands are given the other way round.
1223 #[must_use]
1224 pub const fn swapped(self) -> Self {
1225 match self {
1226 Self::Eq => Self::Eq,
1227 Self::Ne => Self::Ne,
1228 Self::Slt => Self::Sgt,
1229 Self::Sgt => Self::Slt,
1230 Self::Sle => Self::Sge,
1231 Self::Sge => Self::Sle,
1232 Self::Ult => Self::Ugt,
1233 Self::Ugt => Self::Ult,
1234 Self::Ule => Self::Uge,
1235 Self::Uge => Self::Ule,
1236 }
1237 }
1238
1239 /// Whether this reads its operands as signed. Equality reads them as neither.
1240 #[must_use]
1241 pub const fn is_signed(self) -> bool {
1242 matches!(self, Self::Slt | Self::Sle | Self::Sgt | Self::Sge)
1243 }
1244}
1245
1246impl fmt::Display for IntPred {
1247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 f.write_str(self.name())
1249 }
1250}
1251
1252/// The floating point comparisons, ordered and unordered.
1253///
1254/// An ordered predicate is false if either operand is a NaN, and an unordered one is true. C's
1255/// `<` is `olt` and C's `!=` is `une`, which is the whole of why both families are here.
1256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1257pub enum FloatPred {
1258 /// Always false.
1259 False,
1260 /// Ordered and equal.
1261 Oeq,
1262 /// Ordered and greater than.
1263 Ogt,
1264 /// Ordered and greater than or equal.
1265 Oge,
1266 /// Ordered and less than.
1267 Olt,
1268 /// Ordered and less than or equal.
1269 Ole,
1270 /// Ordered and not equal.
1271 One,
1272 /// Ordered, which is to say neither operand is a NaN.
1273 Ord,
1274 /// Unordered, which is to say one of them is.
1275 Uno,
1276 /// Unordered or equal.
1277 Ueq,
1278 /// Unordered or greater than.
1279 Ugt,
1280 /// Unordered or greater than or equal.
1281 Uge,
1282 /// Unordered or less than.
1283 Ult,
1284 /// Unordered or less than or equal.
1285 Ule,
1286 /// Unordered or not equal.
1287 Une,
1288 /// Always true.
1289 True,
1290}
1291
1292impl FloatPred {
1293 /// The textual form.
1294 #[must_use]
1295 pub const fn name(self) -> &'static str {
1296 match self {
1297 Self::False => "false",
1298 Self::Oeq => "oeq",
1299 Self::Ogt => "ogt",
1300 Self::Oge => "oge",
1301 Self::Olt => "olt",
1302 Self::Ole => "ole",
1303 Self::One => "one",
1304 Self::Ord => "ord",
1305 Self::Uno => "uno",
1306 Self::Ueq => "ueq",
1307 Self::Ugt => "ugt",
1308 Self::Uge => "uge",
1309 Self::Ult => "ult",
1310 Self::Ule => "ule",
1311 Self::Une => "une",
1312 Self::True => "true",
1313 }
1314 }
1315
1316 /// The predicate with that name, if there is one.
1317 #[must_use]
1318 pub fn from_name(name: &str) -> Option<Self> {
1319 Self::all().find(|pred| pred.name() == name)
1320 }
1321
1322 /// Every predicate.
1323 pub fn all() -> impl Iterator<Item = Self> {
1324 [
1325 Self::False,
1326 Self::Oeq,
1327 Self::Ogt,
1328 Self::Oge,
1329 Self::Olt,
1330 Self::Ole,
1331 Self::One,
1332 Self::Ord,
1333 Self::Uno,
1334 Self::Ueq,
1335 Self::Ugt,
1336 Self::Uge,
1337 Self::Ult,
1338 Self::Ule,
1339 Self::Une,
1340 Self::True,
1341 ]
1342 .into_iter()
1343 }
1344
1345 /// The predicate that holds exactly when this one does not.
1346 #[must_use]
1347 pub const fn inverse(self) -> Self {
1348 match self {
1349 Self::False => Self::True,
1350 Self::Oeq => Self::Une,
1351 Self::Ogt => Self::Ule,
1352 Self::Oge => Self::Ult,
1353 Self::Olt => Self::Uge,
1354 Self::Ole => Self::Ugt,
1355 Self::One => Self::Ueq,
1356 Self::Ord => Self::Uno,
1357 Self::Uno => Self::Ord,
1358 Self::Ueq => Self::One,
1359 Self::Ugt => Self::Ole,
1360 Self::Uge => Self::Olt,
1361 Self::Ult => Self::Oge,
1362 Self::Ule => Self::Ogt,
1363 Self::Une => Self::Oeq,
1364 Self::True => Self::False,
1365 }
1366 }
1367
1368 /// The predicate that holds when the operands are given the other way round.
1369 #[must_use]
1370 pub const fn swapped(self) -> Self {
1371 match self {
1372 Self::Ogt => Self::Olt,
1373 Self::Olt => Self::Ogt,
1374 Self::Oge => Self::Ole,
1375 Self::Ole => Self::Oge,
1376 Self::Ugt => Self::Ult,
1377 Self::Ult => Self::Ugt,
1378 Self::Uge => Self::Ule,
1379 Self::Ule => Self::Uge,
1380 same => same,
1381 }
1382 }
1383
1384 /// Whether this is false when either operand is a NaN.
1385 ///
1386 /// [`FloatPred::False`] and [`FloatPred::True`] are neither ordered nor unordered, since
1387 /// they do not look at their operands at all, and both answer no here.
1388 #[must_use]
1389 pub const fn is_ordered(self) -> bool {
1390 matches!(
1391 self,
1392 Self::Oeq | Self::Ogt | Self::Oge | Self::Olt | Self::Ole | Self::One | Self::Ord
1393 )
1394 }
1395}
1396
1397impl fmt::Display for FloatPred {
1398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1399 f.write_str(self.name())
1400 }
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405 use super::*;
1406
1407 #[test]
1408 fn every_opcode_is_in_the_table() {
1409 // `InlineAsm` is the last variant, so its discriminant plus one is how many there are.
1410 // A new opcode declared after it moves this number, and a new opcode declared before
1411 // it and not added to `ALL` moves the length, so either mistake fails here.
1412 assert_eq!(ALL.len(), Opcode::InlineAsm as usize + 1);
1413 for (position, &op) in ALL.iter().enumerate() {
1414 assert_eq!(op as usize, position, "{op} is out of order in ALL");
1415 }
1416 }
1417
1418 #[test]
1419 fn every_opcode_name_is_one_word_the_reader_can_take() {
1420 // The textual form keeps the dot for the type suffix and the flags, so an opcode with a
1421 // dot in it reads back as a shorter opcode with a suffix that is not a type. The safety
1422 // instructions are spelled `cap_of` and not `cap.of` for this reason, and the
1423 // specification says so at `spec/safe-memory/06-instrumentation.md` section 6.2.2.
1424 for opcode in Opcode::all() {
1425 let name = opcode.name();
1426 assert!(!name.is_empty(), "an opcode with no name");
1427 assert!(
1428 name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
1429 "{name} is not one word"
1430 );
1431 }
1432 }
1433
1434 #[test]
1435 fn every_opcode_has_its_own_name_and_finds_it_again() {
1436 let mut names: Vec<&str> = Opcode::all().map(Opcode::name).collect();
1437 let total = names.len();
1438 names.sort_unstable();
1439 names.dedup();
1440 assert_eq!(names.len(), total, "two opcodes share a name");
1441 for op in Opcode::all() {
1442 assert_eq!(Opcode::from_name(op.name()), Some(op));
1443 }
1444 assert_eq!(Opcode::from_name("phi"), None);
1445 assert_eq!(Opcode::from_name("getelementptr"), None);
1446 assert_eq!(Opcode::from_name(""), None);
1447 }
1448
1449 #[test]
1450 fn the_terminators_are_the_ones_control_leaves_by() {
1451 let terminators: Vec<&str> =
1452 Opcode::all().filter(|op| op.is_terminator()).map(Opcode::name).collect();
1453 assert_eq!(
1454 terminators,
1455 ["jump", "br_if", "switch", "indirect_br", "return", "unreachable", "tail_call"]
1456 );
1457 }
1458
1459 #[test]
1460 fn a_terminator_produces_nothing() {
1461 for op in Opcode::all().filter(|op| op.is_terminator()) {
1462 assert_eq!(op.results(), Some(0), "{op}");
1463 }
1464 }
1465
1466 #[test]
1467 fn the_pair_producing_opcodes_are_the_ones_with_a_flag_beside_the_value() {
1468 let pairs: Vec<&str> =
1469 Opcode::all().filter(|op| op.results() == Some(2)).map(Opcode::name).collect();
1470 assert_eq!(
1471 pairs,
1472 [
1473 "cmpxchg",
1474 "sadd_overflow",
1475 "uadd_overflow",
1476 "ssub_overflow",
1477 "usub_overflow",
1478 "smul_overflow",
1479 "umul_overflow"
1480 ]
1481 );
1482 }
1483
1484 #[test]
1485 fn the_capability_instructions_are_the_ones_that_make_a_capability() {
1486 let makers: Vec<Opcode> = Opcode::all().filter(|op| op.makes_capability()).collect();
1487 assert_eq!(
1488 makers,
1489 vec![
1490 Opcode::CapOf,
1491 Opcode::CapLoad,
1492 Opcode::CapNull,
1493 Opcode::CapNarrow,
1494 Opcode::CapRecover
1495 ]
1496 );
1497 // The other three read a capability rather than making one. `cap_store` writes it out and
1498 // produces nothing at all, and the two extent queries answer with a number.
1499 assert!(!Opcode::CapStore.makes_capability());
1500 assert_eq!(Opcode::CapStore.results(), Some(0));
1501 assert!(!Opcode::CapExtent.makes_capability());
1502 assert_eq!(Opcode::CapExtent.results(), Some(1));
1503 assert!(!Opcode::CapExtentBack.makes_capability());
1504 assert_eq!(Opcode::CapExtentBack.results(), Some(1));
1505 for opcode in makers {
1506 assert_eq!(opcode.results(), Some(1), "{}", opcode.name());
1507 }
1508 }
1509
1510 #[test]
1511 fn a_check_reads_the_planes_and_writes_nothing() {
1512 let checks = [
1513 Opcode::CheckBounds,
1514 Opcode::CheckLive,
1515 Opcode::CheckType,
1516 Opcode::CheckInit,
1517 Opcode::CheckDeriv,
1518 Opcode::CheckRace,
1519 ];
1520 for opcode in checks {
1521 let name = opcode.name();
1522 // It traps, so it stays where it was put and nothing deletes it for having no
1523 // result. It reads a plane, so it takes a memory operand. It writes nothing, so
1524 // the access after it reads the version the check was given.
1525 assert!(opcode.has_effects(), "{name}");
1526 assert!(opcode.touches_memory(), "{name}");
1527 assert!(!opcode.writes_memory(), "{name}");
1528 assert_eq!(opcode.results(), Some(0), "{name}");
1529 }
1530 }
1531
1532 #[test]
1533 fn a_restrict_check_writes_memory_because_it_records_what_it_saw() {
1534 // The one place the sentence above does not hold. Every other check reads a plane and
1535 // leaves it alone, so the optimizer may hoist one out of a loop or keep the later of two
1536 // identical ones. These record the range they were asked about into the block's own slot,
1537 // so a check that ran twice saw two accesses and a check that was hoisted saw one, and
1538 // either rewrite changes what the next one answers. Saying they write memory is how the
1539 // memory chain refuses both.
1540 let recording = [
1541 Opcode::CheckRestrictRead,
1542 Opcode::CheckRestrictWrite,
1543 Opcode::RestrictEnter,
1544 Opcode::RestrictLeave,
1545 ];
1546 for opcode in recording {
1547 let name = opcode.name();
1548 assert!(opcode.has_effects(), "{name}");
1549 assert!(opcode.touches_memory(), "{name}");
1550 assert!(opcode.writes_memory(), "{name}");
1551 assert_eq!(opcode.results(), Some(0), "{name}");
1552 }
1553 }
1554
1555 #[test]
1556 fn the_capability_instructions_that_touch_memory_are_the_five_that_have_to() {
1557 // `cap_load` and `cap_store` are an access to the slot beside a pointer, and `cap_recover`
1558 // and the two extent queries read the planes. The other three are arithmetic on a
1559 // provenance the program already had, so the optimizer may treat them as it treats
1560 // `ptr_add`.
1561 assert!(!Opcode::CapOf.has_effects());
1562 assert!(!Opcode::CapNull.has_effects());
1563 assert!(!Opcode::CapNarrow.has_effects());
1564 assert!(Opcode::CapLoad.touches_memory() && !Opcode::CapLoad.writes_memory());
1565 assert!(Opcode::CapRecover.touches_memory() && !Opcode::CapRecover.writes_memory());
1566 assert!(Opcode::CapExtent.touches_memory() && !Opcode::CapExtent.writes_memory());
1567 assert!(Opcode::CapExtentBack.touches_memory() && !Opcode::CapExtentBack.writes_memory());
1568 assert!(Opcode::CapStore.writes_memory());
1569 }
1570
1571 #[test]
1572 fn memory_has_effects_and_arithmetic_does_not() {
1573 for op in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Alloca, Opcode::Fence] {
1574 assert!(op.has_effects(), "{op}");
1575 }
1576 for op in [Opcode::Add, Opcode::FDiv, Opcode::ICmp, Opcode::PtrAdd, Opcode::IConst] {
1577 assert!(!op.has_effects(), "{op}");
1578 }
1579 }
1580
1581 #[test]
1582 fn commuting_is_only_claimed_where_it_holds() {
1583 assert!(Opcode::Add.is_commutative());
1584 assert!(Opcode::FAdd.is_commutative());
1585 assert!(!Opcode::Sub.is_commutative());
1586 assert!(!Opcode::FDiv.is_commutative());
1587 assert!(!Opcode::Shl.is_commutative());
1588 }
1589
1590 #[test]
1591 fn an_integer_predicate_inverts_and_swaps_back_to_itself() {
1592 for pred in IntPred::all() {
1593 assert_eq!(pred.inverse().inverse(), pred);
1594 assert_eq!(pred.swapped().swapped(), pred);
1595 assert_eq!(IntPred::from_name(pred.name()), Some(pred));
1596 }
1597 assert_eq!(IntPred::Slt.inverse(), IntPred::Sge);
1598 assert_eq!(IntPred::Slt.swapped(), IntPred::Sgt);
1599 assert_eq!(IntPred::from_name("lt"), None);
1600 }
1601
1602 #[test]
1603 fn a_floating_predicate_inverts_across_the_ordered_line() {
1604 for pred in FloatPred::all() {
1605 assert_eq!(pred.inverse().inverse(), pred);
1606 assert_eq!(pred.swapped().swapped(), pred);
1607 assert_eq!(FloatPred::from_name(pred.name()), Some(pred));
1608 }
1609 // Inverting has to cross the line, because the negation of an ordered comparison is
1610 // true when an operand is a NaN. This is where `!(a < b)` stops being `a >= b`. The
1611 // two constants are outside it: neither of them looks at its operands.
1612 for pred in FloatPred::all().filter(|p| !matches!(p, FloatPred::False | FloatPred::True)) {
1613 assert_ne!(pred.is_ordered(), pred.inverse().is_ordered(), "{pred}");
1614 }
1615 assert_eq!(FloatPred::Olt.inverse(), FloatPred::Uge);
1616 assert_eq!(FloatPred::Olt.swapped(), FloatPred::Ogt);
1617 }
1618
1619 #[test]
1620 fn swapping_a_predicate_keeps_it_ordered_or_unordered() {
1621 for pred in FloatPred::all() {
1622 assert_eq!(pred.is_ordered(), pred.swapped().is_ordered(), "{pred}");
1623 }
1624 for pred in IntPred::all() {
1625 assert_eq!(pred.is_signed(), pred.swapped().is_signed(), "{pred}");
1626 }
1627 }
1628
1629 #[test]
1630 fn no_two_predicates_share_a_name_within_their_family() {
1631 for names in [
1632 IntPred::all().map(IntPred::name).collect::<Vec<_>>(),
1633 FloatPred::all().map(FloatPred::name).collect::<Vec<_>>(),
1634 ] {
1635 let total = names.len();
1636 let mut names = names;
1637 names.sort_unstable();
1638 names.dedup();
1639 assert_eq!(names.len(), total);
1640 }
1641 }
1642}