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 between addresses that do not overlap, of the payload's size or of a third operand.
153 Memcpy,
154 /// A copy between addresses that may overlap, of the payload's size or of a third operand.
155 Memmove,
156 /// A fill with one byte, of the payload's size or of a third operand.
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 ///
174 /// One operand, the pointer, and one capability out. This is the general question and the other
175 /// producers are all the special cases of it that have a cheap answer, which is why it is the
176 /// one that always works and the one to reach for last. A pointer whose provenance the compiler
177 /// still holds should have got its capability from wherever that provenance came from: from the
178 /// allocation site, from the aux slot beside it in memory, from the frame its caller wrote, or
179 /// from the derivation that narrowed it. One of these is what is left when none of those did.
180 ///
181 /// So it has two lowerings and which one it gets is not a property of the instruction. A pointer
182 /// the lowering can trace back to an allocation site gets the cheap answer, which is a subtract
183 /// and a load off the header the allocator wrote. Anything else gets the plane walk, which is
184 /// the expensive answer and the only one that is always available, and comes back marked as
185 /// recovered so the summary counts it as the weakening it is.
186 ///
187 /// An interior pointer is always the second of those, and that is the answer to the question
188 /// document 05 section 5.2.3 leaves open rather than a gap in it. The header is behind the
189 /// payload so that finding it is a subtract by a constant, which is true of a pointer to the
190 /// base of an object and false of a pointer to the middle of one, and the lowering asks for the
191 /// base by construction rather than by checking.
192 CapOf,
193 /// The capability in the auxiliary slot beside a stored pointer, read back.
194 ///
195 /// A pointer written to memory and read again has to bring its capability with it, and where
196 /// the capability lives is document 05's question rather than this one's. What this says is
197 /// that a capability comes back from an address.
198 ///
199 /// Three operands: the capability of the object the word is in, the address of the word, and
200 /// the pointer that was loaded from it. The first is what says where the slot is, since the
201 /// aux is in front of the object and the arithmetic is over the object's own base and extent,
202 /// and the third is what the slot's two numbers are relative to. Both of those are facts about
203 /// the representation document 05 section 5.2.2 chose, and an instrumented load has both
204 /// values in hand already, since the capability is the one its bounds check used and the
205 /// pointer is what the load produced.
206 CapLoad,
207 /// The other half of [`Opcode::CapLoad`], writing one into the slot beside a pointer.
208 ///
209 /// Four operands: the capability of the object the word is in, the address of the word, the
210 /// pointer being stored there, and that pointer's capability. The first three are the same
211 /// three [`Opcode::CapLoad`] takes and for the same reasons, and the fourth is what is being
212 /// written down.
213 CapStore,
214 /// The slots beside a run of copied words, carried over from the run they were copied from.
215 ///
216 /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three: the destination, the
217 /// source, and how many bytes moved. A copy of a structure moves whatever pointers are in it
218 /// and the capability of each of those lives in the slot beside it, so a copy that moved the
219 /// bytes and left the slots alone would leave every pointer in the destination described by
220 /// whatever was there before, which is nothing at best and another instance's answer at worst.
221 ///
222 /// No capability operand, for the reason the other two copies name no node. What each
223 /// destination slot ends up saying is whatever the slot beside the word it came from said, and
224 /// the only place that is written down is the aux over the source.
225 CapCopy,
226 /// The capability that permits nothing, which is what a null pointer has.
227 CapNull,
228 /// A capability narrowed to a sub-object of what it covered.
229 ///
230 /// Only under `-fsafety-subobject`. Narrowing is what catches an overflow from one member of
231 /// a struct into the next, and it is separate because C code that walks off the end of a
232 /// member on purpose exists and a project has to be able to say so.
233 CapNarrow,
234 /// The capability for an address that arrived from outside, recovered from the planes.
235 CapRecover,
236 /// How many bytes from an address on the capability covers, asking for no more than a limit.
237 ///
238 /// Three operands, the capability, the address and how many bytes the asker wants, and one
239 /// integer result that is never more than that limit. It is what
240 /// `spec/safe-memory/07-check-elimination.md` section 7.4 needs to split a loop: the checked
241 /// part and the unchecked part are divided at `min(n, extent / sizeof(T))`, and the extent is
242 /// the half of that a compiler cannot work out on its own.
243 ///
244 /// The limit is an operand because under milestone S1 answering means walking the lifetime
245 /// plane, and a walk that stops at the number of bytes the loop was going to read anyway is
246 /// bounded by the work the loop is already doing. An answer smaller than the truth costs
247 /// iterations in the checked half and is never wrong, which is what makes stopping early
248 /// allowed. Once a capability carries its own bounds, which is milestone S2, this is a
249 /// subtraction on the capability and the limit is one `min`.
250 CapExtent,
251 /// How many bytes below an address on the capability covers, asking for no more than a limit.
252 ///
253 /// The mirror of [`Opcode::CapExtent`], with the same three operands and the same kind of
254 /// answer. What it counts is the bytes ending at the address rather than the bytes starting
255 /// there, so an answer of `n` says that `[addr - n, addr)` belongs to one thing. The address
256 /// itself is one past what is asked about, which is what a walk from high to low needs: the
257 /// question is about where the walk ends up, and where it ends up is below where it began.
258 ///
259 /// The ownership asked about is the byte below the address rather than the byte at it, since
260 /// the address may be one past the end of the object and the object is what the question is
261 /// about. Everything else, the limit operand and why an answer short of the truth is allowed,
262 /// is [`Opcode::CapExtent`]'s.
263 CapExtentBack,
264 /// The capabilities of a call's pointer arguments, handed over beside the arguments.
265 ///
266 /// Document 05 section 5.3 is the whole of why this is an instruction of its own rather than
267 /// more operands on the call. An instrumented function's calling convention is unchanged, so a
268 /// pointer argument goes in the register it always went in and `sizeof(void *)` is still eight,
269 /// which is what lets an object this compiler built link against one nobody instrumented. The
270 /// capability therefore travels out of band, in a small per thread frame the caller writes and
271 /// the callee reads, indexed by argument position.
272 ///
273 /// One operand per pointer argument, in the order the call passes them, and no operand for the
274 /// arguments that are not pointers. A call handing over more pointers than the frame has room
275 /// for describes the ones that fit and the callee recovers the rest, which is a weakening the
276 /// summary counts rather than a refusal. How many fit is the runtime's number and
277 /// `rucc_safety::frame` is where the compiler keeps it, so nothing here is a bound on the
278 /// operand count.
279 ///
280 /// It goes immediately in front of the call it is about, which is how the two are tied
281 /// together, the same way [`Opcode::MetaRelease`] is tied to the atomic it goes in front of.
282 CapPublish,
283 /// There is no frame for this call, which is what a callee that might not be instrumented gets.
284 ///
285 /// The other half of [`Opcode::CapPublish`] and not the absence of one. Publishing to a callee
286 /// that never reads the frame leaves it in place for whatever that callee calls back into, and
287 /// a callback entered from uninstrumented code holding somebody else's capabilities is worse
288 /// than one entered holding none. So a call the compiler cannot say reads frames says there is
289 /// nothing rather than saying nothing at all, and document 10 section 10.8's callback recovers
290 /// its arguments the way an entry from outside always does.
291 CapClear,
292 /// The capability of a pointer parameter, out of the frame the caller published.
293 ///
294 /// The reading end of [`Opcode::CapPublish`], in the callee rather than in the caller. Two
295 /// operands, the parameter itself and which position it is in the call, and one capability out.
296 ///
297 /// The parameter is an operand because it is the answer when there is no frame. A function
298 /// entered from code this build never compiled finds nothing published, and so does one whose
299 /// caller could not vouch for it and said `cap_clear`, and in both cases the capability has to be
300 /// worked out from the pointer the way [`Opcode::CapRecover`] does. That is the expensive answer
301 /// the frame exists to avoid, it is available whatever the caller did, and it is counted as the
302 /// weakening it is.
303 ///
304 /// The position is an operand rather than a payload for the same reason [`Opcode::CapNarrow`]'s
305 /// offset and length are: it is a number the runtime is handed. A position the frame does not
306 /// reach is not an error either, since it is the recovery again, so nothing here has to know how
307 /// many capabilities a frame holds.
308 CapArg,
309 /// The capability of the pointer this function is returning, left where its caller reads.
310 ///
311 /// One operand, the capability, and it goes immediately in front of the `ret` it is about, which
312 /// is the tie [`Opcode::CapPublish`] has with its call. A function that returns from several
313 /// places has one of these in front of each of them, because what is being said is about the
314 /// value leaving by that particular one.
315 ///
316 /// This is the only thing in the design that writes into a frame somebody else made. It is
317 /// allowed to because the frame is the caller's stack and the caller is waiting for this
318 /// function to return, and it is needed because a returned pointer is the one value that crosses
319 /// a call in the other direction.
320 CapYield,
321 /// The capability of the pointer a call gave back, out of the frame the call was published with.
322 ///
323 /// The reading end of [`Opcode::CapYield`], in the caller. One operand, the pointer that came
324 /// back, and one capability out. The operand is there for the reason [`Opcode::CapArg`]'s is: a
325 /// callee that wrote nothing leaves the bottom capability where the caller put it, and the
326 /// bottom one is the signal to work the answer out from the pointer instead.
327 ///
328 /// It goes immediately after the call it is about, and that call has to be one a `cap_publish`
329 /// goes in front of. A call that says there is no frame has no frame for a callee to have
330 /// written into, so there would be nothing for this to read.
331 CapResult,
332 /// An access is within its capability's bounds, aligned, and permitted.
333 ///
334 /// The size and the alignment are the access's, and they are in the memory payload rather
335 /// than in operands because they are what the front end knew and not what the program
336 /// computed.
337 ///
338 /// A third operand overrides how many bytes are asked about, and it exists for the one check
339 /// the front end did not write. `spec/safe-memory/07-check-elimination.md` section 7.4 replaces
340 /// the checks in a loop that runs `n` times with one check over `n * sizeof(T)` bytes, and that
341 /// is a length the program computes rather than one anybody knew when the access was parsed. The
342 /// payload still holds the alignment and the type information of the access the check came from,
343 /// and its size becomes the size of one of them rather than the size of the question.
344 CheckBounds,
345 /// The capability's provenance is still live.
346 CheckLive,
347 /// The access agrees with the type plane, which is the effective type rule of C 6.5.
348 ///
349 /// A third operand overrides how many bytes are asked about, as on [`Opcode::CheckBounds`] and
350 /// for the same reason. Agreeing with a type is a property of a range that holds of every
351 /// subrange of it, so one check over a loop's whole walk says what the loop's checks were going
352 /// to say, which is `spec/safe-memory/07-check-elimination.md` section 7.4's transformation
353 /// applied to this plane rather than to the bounds. The plane entry stays in the payload, since
354 /// the checks a hoisted one stands for all asked at the same type or it would not have been
355 /// written.
356 ///
357 /// A fourth operand is a step, and then the check is not about a range. It asks about one
358 /// access of the payload's width at the pointer and at every step along from it that still
359 /// fits in the third operand's span, which is a loop's checks over a walk that leaves gaps
360 /// written in front of it. Nothing may read one of these as saying anything about the bytes
361 /// between the accesses.
362 CheckType,
363 /// The bytes the access reads have been written.
364 ///
365 /// A third operand overrides how many bytes are asked about, and a fourth is a step, both as on
366 /// [`Opcode::CheckType`].
367 CheckInit,
368 /// A pointer derived from another stays inside the capability the first one had.
369 ///
370 /// Three operands, because the answer is about the new pointer and the question is about
371 /// the old one's capability.
372 CheckDeriv,
373 /// The metadata this access is about to consult has not been changed under it.
374 ///
375 /// Judgement J9, which document 09 section 9.5 specifies and which document 04 section 4.5
376 /// keeps out of J1 for the reason the `restrict` checks are kept out: it is a statement about
377 /// two operations rather than about one. The payload holds the size of the access, because the
378 /// question is whether any granule of the range this touches carries a write by another thread.
379 CheckRace,
380 /// This read did not reach a byte another `restrict` pointer of the same block wrote.
381 ///
382 /// Judgement J8, which document 09 section 9.6 specifies and which document 04 section 4.6
383 /// keeps out of J1 because it is a statement about a pair of accesses rather than about one.
384 /// The payload holds the size of the access and the two numbers saying which pointer it went
385 /// through, and those are the same two [`crate::Restrict`] carries on the access itself.
386 ///
387 /// Read and write are two opcodes rather than one with a flag on it, because every bit of
388 /// [`crate::Flags`] is spoken for and because the operand would then be a constant the program
389 /// does not compute, which is the thing [`Opcode::CheckBounds`] says belongs in the payload.
390 CheckRestrictRead,
391 /// The same about a write, which is the half of the pair that makes the other half a violation.
392 ///
393 /// Two accesses that both only read are not a violation of anything, so what the scope records
394 /// is which of them wrote and the check refuses a pair only when at least one did.
395 CheckRestrictWrite,
396 /// The capability this free goes through still names the instance that owns the address.
397 ///
398 /// Judgement J6, and the same two operands [`Opcode::CheckLive`] has for the same reason: a
399 /// capability and the pointer it is about, with no payload, because how many bytes are at the
400 /// address is not something a free asks. What separates it from the lifetime check is where it
401 /// goes and what it is about. This one sits in front of a call that ends a storage instance
402 /// rather than in front of an access, and the question it decides is whether the pointer being
403 /// handed over still names the instance it was made for.
404 ///
405 /// It exists because that question has no other way of being asked. `free` takes an address and
406 /// nothing else, so a second free of a block the allocator has already handed back out looks
407 /// like an ordinary free to the allocator and releases somebody else's live object.
408 /// tamnd/rucc#492 is that, and the version the capability carries is what tells the two apart.
409 ///
410 /// Nothing discharges one. A bounds fact says nothing about it and a lifetime fact about an
411 /// access says nothing about a free, so it stays where the pass put it and the cost is one
412 /// check per free rather than one per access.
413 CheckFree,
414 /// A storage instance begins here, over a range, with a class.
415 ///
416 /// Judgement J4. This is the `alloca` for an automatic instance and the allocator's report
417 /// for an allocated one, and the range is a pointer and a length in registers rather than a
418 /// payload, because the length of a variable length array is not known when the instruction
419 /// is written down.
420 MetaBegin,
421 /// A storage instance ends here, which is judgement J5.
422 ///
423 /// Every capability for it fails from this point on and keeps failing after the address is
424 /// handed out again, which is what makes the check a use after free check rather than a use
425 /// after reallocation one.
426 MetaEnd,
427 /// The effective type of a range is now this one.
428 MetaType,
429 /// The effective types of a range are now the ones the range it was copied from had.
430 ///
431 /// Three operands, because a copy has two ranges and one length: the destination, the source,
432 /// and how many bytes moved. A `memcpy` does not store through a type, so there is no type to
433 /// name here and naming one would be wrong: C 6.5 says the copied bytes keep the effective type
434 /// they had, whatever that was, and the only place that is written down is the plane over the
435 /// source.
436 MetaTypeCopy,
437 /// The bytes of a range are now initialized.
438 MetaInit,
439 /// The bytes of a range are now initialized wherever the range they were copied from was.
440 ///
441 /// Three operands, for the reason [`Opcode::MetaTypeCopy`] has three. A copy does not write
442 /// values of its own, so whether a destination byte holds anything is whether the byte it came
443 /// from did, and the only place that is written down is the plane over the source. That is what
444 /// makes a structure filled member by member and then copied whole still have padding nothing
445 /// wrote, which is the infoleak the plane is for.
446 MetaInitCopy,
447 /// This thread wrote a range, at whatever step of its own counting it has reached.
448 ///
449 /// The epoch plane's only write, from `spec/safe-memory/09-type-init-and-races.md` section 9.5.
450 /// Two operands like the other plane writes, and the range is a pointer shaped slot rather than
451 /// whatever the access covered: the plane holds one stamp per eight bytes because that is what
452 /// a pointer comes in, and a granule two threads share is one holding no pointer.
453 ///
454 /// It carries no thread and no count. Which thread is running and how far it has counted are
455 /// both facts about the moment the program reaches this, so the runtime reads them and nothing
456 /// here could name them.
457 MetaEpoch,
458 /// Everything this thread has done so far is published at the atomic object named here.
459 ///
460 /// One half of a synchronization edge in the sense of section 9.5, and the half that goes in
461 /// front of the atomic that carries it. The operand is the object's address, because that is
462 /// the key whoever takes the other end will look the clock up under, and there is no payload:
463 /// which thread is publishing and how far it has counted are facts about the moment the program
464 /// reaches this, the same way they are for [`Opcode::MetaEpoch`].
465 ///
466 /// This exists because an atomic is not a call. Every other edge the monitor knows about is a
467 /// `pthread` function and is interposed, and a C11 release store is a machine instruction with
468 /// nothing to interpose, so the compiler is the only thing that can say the edge was there.
469 MetaRelease,
470 /// Everything published at the atomic object named here is now ordered before this thread.
471 ///
472 /// The other half of [`Opcode::MetaRelease`], and it goes after the atomic rather than in front
473 /// of it, because the ordering it takes is the ordering the atomic just read.
474 ///
475 /// A missing edge is the one kind of missing instrumentation in the whole safety pass that
476 /// costs a false report rather than a missed one: two threads that really were ordered by an
477 /// edge nobody recorded look concurrent, and a race is reported against a program doing nothing
478 /// wrong. That is why the edges go in before the race check is ever on by default.
479 MetaAcquire,
480 /// Everything this thread has done so far is published at no object in particular.
481 ///
482 /// What a release fence is, and the reason it cannot reuse [`Opcode::MetaRelease`]: a fence
483 /// orders against every other thread rather than against one object, so there is no address to
484 /// key it on and it takes no operands at all. The relaxed atomic that usually sits beside it in
485 /// the source is not the key either, because the fence orders everything, not that one word.
486 ///
487 /// The runtime pays for that with one cell shared by every fence in the program, which orders
488 /// more pairs of threads than the program really ordered. That direction is safe. A thread put
489 /// further ahead than it needed to be reports fewer races, never a wrong one.
490 MetaFenceRelease,
491 /// Everything published at any release fence is now ordered before this thread.
492 ///
493 /// The other half of [`Opcode::MetaFenceRelease`], after the fence rather than in front of it,
494 /// for the same reason [`Opcode::MetaAcquire`] goes after its atomic.
495 MetaFenceAcquire,
496 /// A range leaves the monitor's authority, or comes back, which is judgement J7.
497 MetaTransfer,
498 /// A declared exemption starts here, with the reason it was declared.
499 ///
500 /// Not an optimization hint. Everything between this and its `safe_region_end` is code the
501 /// monitor is told not to judge, so the reason it carries is a trust set entry, and
502 /// `spec/safe-memory/10-boundaries.md` section 10.2 counts them per build precisely so that
503 /// a reviewer can read what a binary's guarantee rests on.
504 SafeRegionBegin,
505 /// The end of the region the last `safe_region_begin` opened.
506 SafeRegionEnd,
507 /// A block that declares `restrict` pointers begins here, over a slot to keep its record in.
508 ///
509 /// The operand is the storage the record lives in, which is the block's own stack slot, and the
510 /// payload says how large it is. The clique the block was given is [`crate::Restrict::clique`]
511 /// of the payload and how many pointers it declares is [`crate::Restrict::base`], which is the
512 /// one place that field counts bases rather than naming one.
513 ///
514 /// A marker rather than something the front end could fold into the accesses, because the
515 /// promise is about the block's dynamic extent: a function called twice has made the promise
516 /// twice, and what the second call reached says nothing about the first.
517 RestrictEnter,
518 /// The block the last `restrict_enter` opened ends here.
519 ///
520 /// The operand is the same slot, so that the record can be unlinked from whatever encloses it
521 /// without the runtime having to keep a list of its own.
522 RestrictLeave,
523
524 // Control. Every one of these is a terminator.
525 /// An unconditional branch, `jump block1(%a, %b)`.
526 Jump,
527 /// A two-way branch on an `i1`.
528 BrIf,
529 /// A multi-way branch on an integer, with a default.
530 Switch,
531 /// A branch to an address, `indirect_br %0, block1, block2`.
532 ///
533 /// The targets are every block control can arrive at, which is what makes the edges of a
534 /// computed `goto` ordinary edges: nothing else in the compiler has to know that the
535 /// address decides which one it is. A target that is not listed is a branch that does not
536 /// happen, so a frontend that leaves one out has made a promise on the program's behalf.
537 IndirectBr,
538 /// A return, with the values the signature says.
539 Return,
540 /// A place control cannot reach, which the frontend emits after a `noreturn` call.
541 Unreachable,
542
543 // Calls.
544 /// A call to a named function.
545 Call,
546 /// A call through an address, carrying the signature it is called with.
547 CallIndirect,
548 /// A call in tail position that reuses the frame, which is a terminator.
549 TailCall,
550
551 // Intrinsics, which is the closed part. The open part is `TargetIntrinsic`.
552 /// Count leading zeroes.
553 Ctlz,
554 /// Count trailing zeroes.
555 Cttz,
556 /// Count set bits.
557 Ctpop,
558 /// Reverse the bytes.
559 Bswap,
560 /// Reverse the bits.
561 Bitreverse,
562 /// Signed addition, producing the result and whether it overflowed.
563 SAddOverflow,
564 /// Unsigned addition, producing the result and whether it overflowed.
565 UAddOverflow,
566 /// Signed subtraction, producing the result and whether it overflowed.
567 SSubOverflow,
568 /// Unsigned subtraction, producing the result and whether it overflowed.
569 USubOverflow,
570 /// Signed multiplication, producing the result and whether it overflowed.
571 SMulOverflow,
572 /// Unsigned multiplication, producing the result and whether it overflowed.
573 UMulOverflow,
574 /// `__builtin_expect`, which is the value with a hint attached.
575 Expect,
576 /// `__builtin_unreachable` as a hint on a path, distinct from the terminator.
577 UnreachableHint,
578 /// `__builtin_trap`, which stops the program where it stands.
579 ///
580 /// Not a terminator, for the reason `unreachable_hint` is not one: what ends a block here is
581 /// control going somewhere, and this goes nowhere at all. The block it is in goes on being
582 /// lowered and whatever follows it is written and never run, which costs a few bytes nothing
583 /// reaches and keeps every pass that walks a block from needing a second shape for it.
584 Trap,
585 /// `__builtin_prefetch`.
586 Prefetch,
587 /// `__builtin_frame_address`.
588 FrameAddress,
589 /// `__builtin_return_address`.
590 ReturnAddress,
591 /// `__builtin_thread_pointer`, the address of the storage the running thread has.
592 ///
593 /// It takes nothing and answers a pointer. Unlike the two above it there is no walk to do and
594 /// no frame to have kept: the machine holds the address in a place of its own, so this is one
595 /// instruction on every target that has the builtin at all.
596 ThreadPointer,
597 /// `__builtin_object_size` where the front end could not see the object, which is how many
598 /// bytes there are from the address to the end of whatever it points into.
599 ///
600 /// One operand, the address, and the question as a number from zero to three beside it: the
601 /// low bit asks about the closest member rather than the whole object and the high bit asks
602 /// for the smallest answer rather than the largest. It never reaches the back end:
603 /// `rucc_opt::objsize` answers every one before any other pass runs, from the allocations and
604 /// the arithmetic the address was built out of, and says it does not know where it cannot
605 /// see, which is the largest number there is for the first two questions and zero for the
606 /// other two.
607 ObjectSize,
608 /// What is in a machine register, for `register long x asm ("rbx");`.
609 ///
610 /// The GNU extension that puts an object in a named register rather than in the frame. The
611 /// name of the register is the payload and the result is whatever that register holds where
612 /// this stands, which is the value the object starts with. A garbage collector written in C
613 /// reads the callee saved registers this way, because a root that is only in one of those is
614 /// a root no walk of the stack finds.
615 ///
616 /// It is not pure. Two of these on the same register in one function are two different
617 /// answers, since anything in between may have written the register, so neither may be moved
618 /// to where the other is and neither may be dropped for the other.
619 RegisterValue,
620 /// The start of a variable argument list.
621 VaStart,
622 /// One argument off a variable argument list, which moves the list on as it reads it. Two
623 /// of these on one list are two arguments and never one argument read twice, so whatever
624 /// decides which instructions may be folded together has to leave these alone.
625 VaArg,
626 /// One argument off a variable argument list, when that argument is an object rather than a
627 /// value, which is what a `struct` or a `union` read out of one is.
628 ///
629 /// It answers the address of the object rather than the object, because an aggregate is not
630 /// a value and there is nothing for one result to be. Where the object arrives in registers
631 /// there is no address until something makes one, so what this asks of a target is a place
632 /// to put the registers and the address of that place, which is the copy every psABI's own
633 /// description of the algorithm makes. It moves the list on for the reason [`Opcode::VaArg`]
634 /// does.
635 VaObject,
636 /// The end of a variable argument list.
637 VaEnd,
638 /// A copy of a variable argument list.
639 VaCopy,
640 /// The stack pointer, saved before a variable length array.
641 StackSave,
642 /// The stack pointer, restored after one.
643 StackRestore,
644 /// The marker a `setjmp` leaves, which pins everything live across it.
645 ///
646 /// One operand, the buffer, and one result, which is the `int` the save answers with: zero
647 /// where control went past it and one where control came back to it. That is the one
648 /// instruction here whose value depends on how control reached it, and it is one instruction
649 /// rather than a branch and a block because the edge a `longjmp` travels is not in this
650 /// function's control flow graph. It is written into the buffer and taken at run time, so a
651 /// pass that walked the edges would find a block nothing reaches and take it away.
652 SetjmpMarker,
653 /// The marker a `longjmp` leaves.
654 ///
655 /// One operand, the buffer, and no result, and not a terminator either, for the reason above:
656 /// where control goes is not a block of this function. What follows it is written and never
657 /// reached.
658 LongjmpMarker,
659 /// A target-specific intrinsic, named rather than enumerated, for the vector builtins.
660 TargetIntrinsic,
661
662 /// Inline assembly. A terminator when it has labels, which is `asm goto`.
663 InlineAsm,
664}
665
666impl Opcode {
667 /// The textual form, which is also what the parser reads.
668 #[must_use]
669 pub const fn name(self) -> &'static str {
670 match self {
671 Self::IConst => "iconst",
672 Self::FConst => "fconst",
673 Self::Splat => "splat",
674 Self::GlobalAddr => "global_addr",
675 Self::BlockAddr => "block_addr",
676 Self::Add => "add",
677 Self::Sub => "sub",
678 Self::Mul => "mul",
679 Self::SDiv => "sdiv",
680 Self::UDiv => "udiv",
681 Self::SRem => "srem",
682 Self::URem => "urem",
683 Self::And => "and",
684 Self::Or => "or",
685 Self::Xor => "xor",
686 Self::Shl => "shl",
687 Self::LShr => "lshr",
688 Self::AShr => "ashr",
689 Self::FAdd => "fadd",
690 Self::FSub => "fsub",
691 Self::FMul => "fmul",
692 Self::FDiv => "fdiv",
693 Self::FRem => "frem",
694 Self::FNeg => "fneg",
695 Self::Fma => "fma",
696 Self::ICmp => "icmp",
697 Self::FCmp => "fcmp",
698 Self::Select => "select",
699 Self::Trunc => "trunc",
700 Self::SExt => "sext",
701 Self::ZExt => "zext",
702 Self::FPTrunc => "fptrunc",
703 Self::FPExt => "fpext",
704 Self::FPToSI => "fptosi",
705 Self::FPToUI => "fptoui",
706 Self::SIToFP => "sitofp",
707 Self::UIToFP => "uitofp",
708 Self::PtrToInt => "ptrtoint",
709 Self::IntToPtr => "inttoptr",
710 Self::Bitcast => "bitcast",
711 Self::MemEntry => "mem_entry",
712 Self::Alloca => "alloca",
713 Self::Load => "load",
714 Self::Store => "store",
715 Self::PtrAdd => "ptr_add",
716 Self::Memcpy => "memcpy",
717 Self::Memmove => "memmove",
718 Self::Memset => "memset",
719 Self::AtomicLoad => "atomic_load",
720 Self::AtomicStore => "atomic_store",
721 Self::AtomicRmw => "atomic_rmw",
722 Self::Cmpxchg => "cmpxchg",
723 Self::Fence => "fence",
724 Self::CapOf => "cap_of",
725 Self::CapLoad => "cap_load",
726 Self::CapStore => "cap_store",
727 Self::CapCopy => "cap_copy",
728 Self::CapNull => "cap_null",
729 Self::CapNarrow => "cap_narrow",
730 Self::CapRecover => "cap_recover",
731 Self::CapExtent => "cap_extent",
732 Self::CapExtentBack => "cap_extent_back",
733 Self::CapPublish => "cap_publish",
734 Self::CapClear => "cap_clear",
735 Self::CapArg => "cap_arg",
736 Self::CapYield => "cap_yield",
737 Self::CapResult => "cap_result",
738 Self::CheckBounds => "check_bounds",
739 Self::CheckLive => "check_live",
740 Self::CheckType => "check_type",
741 Self::CheckInit => "check_init",
742 Self::CheckDeriv => "check_deriv",
743 Self::CheckRace => "check_race",
744 Self::CheckRestrictRead => "check_restrict_read",
745 Self::CheckRestrictWrite => "check_restrict_write",
746 Self::CheckFree => "check_free",
747 Self::MetaBegin => "meta_begin",
748 Self::MetaEnd => "meta_end",
749 Self::MetaType => "meta_type",
750 Self::MetaTypeCopy => "meta_type_copy",
751 Self::MetaInit => "meta_init",
752 Self::MetaInitCopy => "meta_init_copy",
753 Self::MetaEpoch => "meta_epoch",
754 Self::MetaRelease => "meta_release",
755 Self::MetaAcquire => "meta_acquire",
756 Self::MetaFenceRelease => "meta_fence_release",
757 Self::MetaFenceAcquire => "meta_fence_acquire",
758 Self::MetaTransfer => "meta_transfer",
759 Self::SafeRegionBegin => "safe_region_begin",
760 Self::SafeRegionEnd => "safe_region_end",
761 Self::RestrictEnter => "restrict_enter",
762 Self::RestrictLeave => "restrict_leave",
763 Self::Jump => "jump",
764 Self::BrIf => "br_if",
765 Self::Switch => "switch",
766 Self::IndirectBr => "indirect_br",
767 Self::Return => "return",
768 Self::Unreachable => "unreachable",
769 Self::Call => "call",
770 Self::CallIndirect => "call_indirect",
771 Self::TailCall => "tail_call",
772 Self::Ctlz => "ctlz",
773 Self::Cttz => "cttz",
774 Self::Ctpop => "ctpop",
775 Self::Bswap => "bswap",
776 Self::Bitreverse => "bitreverse",
777 Self::SAddOverflow => "sadd_overflow",
778 Self::UAddOverflow => "uadd_overflow",
779 Self::SSubOverflow => "ssub_overflow",
780 Self::USubOverflow => "usub_overflow",
781 Self::SMulOverflow => "smul_overflow",
782 Self::UMulOverflow => "umul_overflow",
783 Self::Expect => "expect",
784 Self::UnreachableHint => "unreachable_hint",
785 Self::Trap => "trap",
786 Self::Prefetch => "prefetch",
787 Self::FrameAddress => "frame_address",
788 Self::ReturnAddress => "return_address",
789 Self::ThreadPointer => "thread_pointer",
790 Self::ObjectSize => "object_size",
791 Self::RegisterValue => "register_value",
792 Self::VaStart => "va_start",
793 Self::VaArg => "va_arg",
794 Self::VaObject => "va_object",
795 Self::VaEnd => "va_end",
796 Self::VaCopy => "va_copy",
797 Self::StackSave => "stacksave",
798 Self::StackRestore => "stackrestore",
799 Self::SetjmpMarker => "setjmp_marker",
800 Self::LongjmpMarker => "longjmp_marker",
801 Self::TargetIntrinsic => "target_intrinsic",
802 Self::InlineAsm => "inline_asm",
803 }
804 }
805
806 /// Every opcode, in the order they are declared.
807 ///
808 /// The parser walks this rather than holding a second table, because a second table is a
809 /// table that can disagree with the first one.
810 pub fn all() -> impl Iterator<Item = Self> {
811 ALL.iter().copied()
812 }
813
814 /// The opcode with that name, if there is one.
815 #[must_use]
816 pub fn from_name(name: &str) -> Option<Self> {
817 ALL.iter().copied().find(|op| op.name() == name)
818 }
819
820 /// Whether this ends a block.
821 ///
822 /// [`Opcode::InlineAsm`] is not here and is the one instruction whose answer depends on
823 /// the instruction rather than on the opcode: `asm goto` has successors and everything
824 /// else does not. Ask the instruction, not the opcode.
825 #[must_use]
826 pub const fn is_terminator(self) -> bool {
827 matches!(
828 self,
829 Self::Jump
830 | Self::BrIf
831 | Self::Switch
832 | Self::IndirectBr
833 | Self::Return
834 | Self::Unreachable
835 | Self::TailCall
836 )
837 }
838
839 /// Whether the operands can be swapped without changing the result.
840 ///
841 /// The floating point cases are commutative even under the strictest rounding, because
842 /// swapping the operands of an addition does not change which of them is a NaN, and the
843 /// sign of a NaN result is not something we promise anything about either way.
844 #[must_use]
845 pub const fn is_commutative(self) -> bool {
846 matches!(
847 self,
848 Self::Add
849 | Self::Mul
850 | Self::And
851 | Self::Or
852 | Self::Xor
853 | Self::FAdd
854 | Self::FMul
855 | Self::SAddOverflow
856 | Self::UAddOverflow
857 | Self::SMulOverflow
858 | Self::UMulOverflow
859 )
860 }
861
862 /// Whether this reads or writes memory, or has an effect the optimizer has to preserve.
863 ///
864 /// An instruction that answers no can be deleted when nothing uses its result, moved
865 /// across a call, and merged with another one computing the same thing. Everything else
866 /// has to be argued about individually, so the conservative answer is the true one here
867 /// and the list of exceptions is the part that is checked.
868 #[must_use]
869 pub const fn has_effects(self) -> bool {
870 !matches!(
871 self,
872 Self::IConst
873 | Self::FConst
874 | Self::Splat
875 | Self::GlobalAddr
876 | Self::BlockAddr
877 | Self::Add
878 | Self::Sub
879 | Self::Mul
880 | Self::SDiv
881 | Self::UDiv
882 | Self::SRem
883 | Self::URem
884 | Self::And
885 | Self::Or
886 | Self::Xor
887 | Self::Shl
888 | Self::LShr
889 | Self::AShr
890 | Self::FAdd
891 | Self::FSub
892 | Self::FMul
893 | Self::FDiv
894 | Self::FRem
895 | Self::FNeg
896 | Self::Fma
897 | Self::ICmp
898 | Self::FCmp
899 | Self::Select
900 | Self::Trunc
901 | Self::SExt
902 | Self::ZExt
903 | Self::FPTrunc
904 | Self::FPExt
905 | Self::FPToSI
906 | Self::FPToUI
907 | Self::SIToFP
908 | Self::UIToFP
909 | Self::PtrToInt
910 | Self::IntToPtr
911 | Self::Bitcast
912 | Self::PtrAdd
913 | Self::Ctlz
914 | Self::Cttz
915 | Self::Ctpop
916 | Self::Bswap
917 | Self::Bitreverse
918 | Self::SAddOverflow
919 | Self::UAddOverflow
920 | Self::SSubOverflow
921 | Self::USubOverflow
922 | Self::SMulOverflow
923 | Self::UMulOverflow
924 | Self::Expect
925 | Self::FrameAddress
926 | Self::ReturnAddress
927 // The same address for as long as the thread runs, and a thread cannot change
928 // which one it is part way through a function, so two of these in one function
929 // are the same value and either may be moved to where the other is.
930 | Self::ThreadPointer
931 // A question about an address that reads nothing: the answer is a fact about where
932 // the address came from, which is the same fact wherever the question is asked.
933 | Self::ObjectSize
934 | Self::MemEntry
935 // Three of the capability instructions are arithmetic on a pointer's
936 // provenance and touch nothing. The other four do: `cap_load`, `cap_store` and
937 // `cap_copy` are an access, and `cap_recover` reads the planes.
938 | Self::CapOf
939 | Self::CapNull
940 | Self::CapNarrow
941 )
942 }
943
944 /// Whether an instruction with this opcode touches memory.
945 ///
946 /// This is what decides whether it takes a memory operand once memory SSA is built, per
947 /// document 09 of `spec/optimizer`. It is written as the exceptions to touching memory
948 /// rather than as a list of what does, for the reason document 08.6 gives about the escape
949 /// analysis: an opcode added later has to end up on the conservative side by default, and a
950 /// list of what touches memory would silently leave a new one out.
951 ///
952 /// `mem_entry` answers no. It produces memory rather than touching it, which is the whole
953 /// of what it is for.
954 #[must_use]
955 pub const fn touches_memory(self) -> bool {
956 if !self.has_effects() {
957 return false;
958 }
959 !matches!(
960 self,
961 // Fresh storage nothing could have been reading, and the pointer that names it.
962 Self::Alloca
963 // The stack pointer, which is a register and not memory. Putting it back is a
964 // different matter and is below, because it takes storage away.
965 | Self::StackSave
966 // Control, which goes somewhere rather than touching anything. A tail call is
967 // not here, because it is a call.
968 | Self::Jump
969 | Self::BrIf
970 | Self::Switch
971 | Self::IndirectBr
972 | Self::Return
973 | Self::Unreachable
974 | Self::UnreachableHint
975 )
976 }
977
978 /// Whether an instruction with this opcode writes memory, and so produces a new version of
979 /// it rather than only reading the version it was given.
980 ///
981 /// Everything that touches memory writes it except the ones that plainly do not. A `fence`
982 /// writes nothing and is still a write here, because document 09.5 says an atomic or a
983 /// barrier is a definition nothing walks past, and giving it one is how that is expressed
984 /// in a representation whose only ordering is the memory chain.
985 ///
986 /// The checks read the planes and change nothing, which
987 /// `spec/safe-memory/06-instrumentation.md` section 6.2.4 states as the word `readonly`. A
988 /// check that trapped is a program that stopped and there is no version of memory after it
989 /// for anything to observe, so the trap costs nothing here. What it does cost is that a
990 /// check may not be moved across a plane write, and that is the memory chain saying so
991 /// rather than this.
992 #[must_use]
993 pub const fn writes_memory(self) -> bool {
994 self.touches_memory()
995 && !matches!(
996 self,
997 Self::Load
998 | Self::AtomicLoad
999 | Self::Prefetch
1000 | Self::CapLoad
1001 | Self::CapRecover
1002 | Self::CapArg
1003 | Self::CapResult
1004 | Self::CapExtent
1005 | Self::CapExtentBack
1006 | Self::CheckBounds
1007 | Self::CheckLive
1008 | Self::CheckType
1009 | Self::CheckInit
1010 | Self::CheckDeriv
1011 | Self::CheckRace
1012 | Self::CheckFree
1013 )
1014 }
1015
1016 /// Whether the only memory this touches is the safety planes.
1017 ///
1018 /// The planes are storage the runtime keeps for itself, one entry per range of program bytes,
1019 /// laid out by `spec/safe-memory/05-representation.md` section 5.2. What matters here is that
1020 /// no name in the program reaches one. A plane write and a program store can never be the same
1021 /// byte, and neither can a plane read and a program load, so an alias oracle that knows this
1022 /// answers no to every pair with one of each.
1023 ///
1024 /// The aux plane sits in the same allocation as the object rather than in a map of its own, so
1025 /// an address far enough outside an object does land in somebody's plane. That is an access
1026 /// outside the bounds of the thing it was derived from, which is the access every check in this
1027 /// list exists to refuse, and it is undefined before it is refused. An optimizer is entitled to
1028 /// the assumption that the program does not make one, and this is that assumption and not a
1029 /// second one.
1030 ///
1031 /// Nothing above can work that out by looking at the access, which is why this is here. The
1032 /// address operand of one of these is a locator and not the memory it touches: `meta_init %p`
1033 /// writes the entry the plane keeps for `%p` and does not write `%p`, so an oracle reading the
1034 /// operand the ordinary way sees a write to exactly the bytes a load of `%p` wants.
1035 ///
1036 /// A list of what does rather than the exceptions to it, which is the other way round from
1037 /// [`Opcode::touches_memory`] and for the same reason: an opcode added later and left out of
1038 /// this one is an opcode the oracle says nothing about, which costs a missed optimization,
1039 /// and an opcode added later that lands in here without anybody reading what it does would be
1040 /// a wrong answer about memory in the safety pass of all places.
1041 ///
1042 /// Two families are deliberately not here even though their names look like they belong. The
1043 /// `restrict` markers take the block's own stack slot as an operand and write their record into
1044 /// it. The synchronization edges say something about the ordering of program memory rather than
1045 /// only about a plane, and a wrong answer there is a false report rather than a missed one.
1046 ///
1047 /// The capability instructions are mostly out and not all of them, so the line between them is
1048 /// worth saying plainly: it is whether every pointer the instruction takes is a locator.
1049 /// `cap_load`, `cap_store` and `cap_recover` each have one that is not, because the point of
1050 /// the aux pair is that a pointer written into a slot comes back out of one, so an address
1051 /// handed to any of those has gone somewhere a later instruction can get it from. `cap_copy`
1052 /// has no such operand. Its three are a destination, a source and a length, it writes nothing
1053 /// but the slots over the destination and reads nothing but the slots over the source, and a
1054 /// slot holds a displacement from the pointer beside it rather than an address, so a run of
1055 /// slots that ends up saying what another run said has moved no address anywhere the copy of
1056 /// the words themselves did not move it already.
1057 #[must_use]
1058 pub const fn touches_only_planes(self) -> bool {
1059 matches!(
1060 self,
1061 Self::CheckBounds
1062 | Self::CheckLive
1063 | Self::CheckType
1064 | Self::CheckInit
1065 | Self::CheckDeriv
1066 | Self::CheckRace
1067 | Self::CheckFree
1068 | Self::CapExtent
1069 | Self::CapExtentBack
1070 | Self::CapCopy
1071 | Self::MetaBegin
1072 | Self::MetaEnd
1073 | Self::MetaType
1074 | Self::MetaTypeCopy
1075 | Self::MetaInit
1076 | Self::MetaInitCopy
1077 | Self::MetaEpoch
1078 | Self::MetaTransfer
1079 )
1080 }
1081
1082 /// Whether this marks one end of a jump along an edge this function's control flow graph does
1083 /// not have.
1084 ///
1085 /// The two `setjmp` markers and nothing else. It exists because an alias oracle that reasons
1086 /// about a call reasons from what the call was handed, and neither of these was handed
1087 /// anything. Control arrives at the instruction after a `setjmp_marker` from wherever the
1088 /// matching `longjmp` sits, so the memory there is a join of the chain that flows into the
1089 /// marker and the memory at every one of those points, and a `longjmp_marker` is the other end
1090 /// of that join and so reads everything the landing will look at. An object whose address never
1091 /// left this function is as exposed to both as anything else, because the jump comes back into
1092 /// this frame and the program reads the frame's own slots afterwards. The only answer about a
1093 /// reference across one of these that cannot be wrong is that it may be touched.
1094 #[must_use]
1095 pub const fn is_jump_marker(self) -> bool {
1096 matches!(self, Self::SetjmpMarker | Self::LongjmpMarker)
1097 }
1098
1099 /// How many values this produces, for the opcodes where the count is fixed.
1100 ///
1101 /// `None` means the count comes from somewhere else: a call takes it from its signature,
1102 /// and inline assembly takes it from its output constraints. A tail call is not one of
1103 /// them, because whatever it returns goes straight out of the function and there is no
1104 /// instruction after it to use anything.
1105 #[must_use]
1106 pub const fn results(self) -> Option<u8> {
1107 match self {
1108 Self::Call | Self::CallIndirect | Self::InlineAsm => None,
1109 Self::Cmpxchg
1110 | Self::SAddOverflow
1111 | Self::UAddOverflow
1112 | Self::SSubOverflow
1113 | Self::USubOverflow
1114 | Self::SMulOverflow
1115 | Self::UMulOverflow => Some(2),
1116 Self::Store
1117 | Self::Memcpy
1118 | Self::Memmove
1119 | Self::Memset
1120 | Self::AtomicStore
1121 | Self::Fence
1122 | Self::Prefetch
1123 | Self::VaStart
1124 | Self::VaEnd
1125 | Self::VaCopy
1126 | Self::StackRestore
1127 | Self::UnreachableHint
1128 | Self::Trap
1129 | Self::LongjmpMarker
1130 | Self::CapStore
1131 | Self::CapCopy
1132 | Self::CapPublish
1133 | Self::CapClear
1134 | Self::CapYield
1135 | Self::CheckBounds
1136 | Self::CheckLive
1137 | Self::CheckType
1138 | Self::CheckInit
1139 | Self::CheckDeriv
1140 | Self::CheckRace
1141 | Self::CheckRestrictRead
1142 | Self::CheckRestrictWrite
1143 | Self::CheckFree
1144 | Self::MetaBegin
1145 | Self::MetaEnd
1146 | Self::MetaType
1147 | Self::MetaTypeCopy
1148 | Self::MetaInit
1149 | Self::MetaInitCopy
1150 | Self::MetaEpoch
1151 | Self::MetaRelease
1152 | Self::MetaAcquire
1153 | Self::MetaFenceRelease
1154 | Self::MetaFenceAcquire
1155 | Self::MetaTransfer
1156 | Self::SafeRegionBegin
1157 | Self::SafeRegionEnd
1158 | Self::RestrictEnter
1159 | Self::RestrictLeave => Some(0),
1160 _ if self.is_terminator() => Some(0),
1161 _ => Some(1),
1162 }
1163 }
1164
1165 /// Whether an instruction with this opcode produces a capability.
1166 ///
1167 /// Seven of the fourteen `cap` instructions. The other seven consume one instead, or none at
1168 /// all: `cap_store` writes one beside a pointer, `cap_copy` moves a run of them from beside one
1169 /// set of words to beside another, `cap_extent` and `cap_extent_back` ask one a
1170 /// question about itself and answer with a number, `cap_publish` hands a call's worth of them
1171 /// to a callee, `cap_yield` leaves one where the caller of this function will look for it, and
1172 /// `cap_clear` takes no operands because saying there is no frame is not a statement about any
1173 /// capability. The reason this is a question about the opcode rather than
1174 /// about the result type is that the verifier asks it the other way round: it walks the results
1175 /// looking for a `cap` and needs to know whether the instruction under it was entitled to make
1176 /// one.
1177 #[must_use]
1178 pub const fn makes_capability(self) -> bool {
1179 matches!(
1180 self,
1181 Self::CapOf
1182 | Self::CapLoad
1183 | Self::CapNull
1184 | Self::CapNarrow
1185 | Self::CapRecover
1186 | Self::CapArg
1187 | Self::CapResult
1188 )
1189 }
1190
1191 /// Which operand of a capability producer names the pointer the capability is about.
1192 ///
1193 /// Five of the seven [`Opcode::makes_capability`] lists, and they all mean the same thing by it:
1194 /// the capability describes the object that pointer is in. Where they differ is only in how the
1195 /// answer was arrived at, which is a walk of the lifetime plane for `cap_recover`, a read of the
1196 /// slot beside the word for `cap_load`, a read of the caller's frame for `cap_arg`, a read of
1197 /// the frame the caller published for `cap_result`, and whatever the back end has at hand for
1198 /// `cap_of`.
1199 ///
1200 /// That is worth stating as one question because the optimizer asks it. A rule that discharges a
1201 /// check by knowing which pointer the check's capability is about has no business caring which
1202 /// producer supplied it, and while `cap_of` was the only one anything emitted, asking for the
1203 /// opcode by name and taking operand zero was the same question. It stopped being the same
1204 /// question when tamnd/rucc#1241 started emitting the cheap producers, and a rule that still
1205 /// asked by name would quietly discharge less the better the code got.
1206 ///
1207 /// The two that answer nothing are the two that are not about a pointer at all. A `cap_narrow`
1208 /// is about another capability and a `cap_null` is about nothing by construction.
1209 ///
1210 /// `cap_result` was in that group and did not belong there. The reasoning was that it is about a
1211 /// pointer the callee returned, which sounds like a value this function has only as the call's
1212 /// own result, and the opcode carries that pointer as operand zero for the same reason
1213 /// `cap_arg` carries one: a callee that wrote nothing leaves the bottom capability in the slot,
1214 /// and the pointer is what the runtime falls back to working the answer out from. So the
1215 /// operand was there the whole time and this said there was none. It is the same mistake the
1216 /// paragraph above is about, made once more in the place that exists to stop it, which is
1217 /// exactly how much care this question wants: every producer that names a pointer has to be
1218 /// here, and the way to tell is to read the opcode's operands rather than its purpose.
1219 #[must_use]
1220 pub const fn capability_names(self) -> Option<usize> {
1221 match self {
1222 Self::CapOf | Self::CapRecover | Self::CapArg | Self::CapResult => Some(0),
1223 // The third, because the first two are the container's capability and the address of
1224 // the word, and the pointer this one is about is the value that came out of the word.
1225 Self::CapLoad => Some(2),
1226 _ => None,
1227 }
1228 }
1229
1230 /// Which payload an instruction with this opcode carries.
1231 ///
1232 /// The printer reads the payload it finds and does not need this. The parser has only the
1233 /// opcode when it reaches the operands, so this is where the two of them agree on what
1234 /// comes after them. An instruction carrying a payload of some other kind prints as text
1235 /// the parser cannot read back, which is why the verifier checks it against
1236 /// [`Extra::kind`](crate::Extra::kind) rather than leaving it to be found later.
1237 #[must_use]
1238 pub const fn extra_kind(self) -> ExtraKind {
1239 match self {
1240 Self::IConst | Self::FConst | Self::Splat => ExtraKind::Imm,
1241 Self::GlobalAddr | Self::TargetIntrinsic | Self::RegisterValue => ExtraKind::Symbol,
1242 Self::ICmp => ExtraKind::IntPred,
1243 Self::FCmp => ExtraKind::FloatPred,
1244 Self::Alloca
1245 | Self::Load
1246 | Self::Store
1247 | Self::Memcpy
1248 | Self::Memmove
1249 | Self::Memset
1250 | Self::AtomicLoad
1251 | Self::AtomicStore
1252 | Self::Cmpxchg
1253 // Four of the checks are about a run of bytes and the payload is where the size
1254 // of that run is, along with the alignment `check_bounds` wants and the aliasing
1255 // node `check_type` compares against. The other two ask a question about a
1256 // pointer and not about a range, so they carry nothing.
1257 | Self::CheckBounds
1258 | Self::CheckType
1259 | Self::CheckInit
1260 | Self::CheckRace
1261 // The two `restrict` checks and the marker that opens their scope. The first two carry
1262 // the size of the access and the two numbers saying which pointer it went through, and
1263 // the third carries the size of the slot and the numbers describing the scope itself.
1264 | Self::CheckRestrictRead
1265 | Self::CheckRestrictWrite
1266 | Self::RestrictEnter => ExtraKind::Mem,
1267 // The plane writes. What each one needs beyond the range is different, and the range
1268 // itself is operands, since the length of a variable length array is a value.
1269 Self::MetaBegin => ExtraKind::Class,
1270 Self::MetaTransfer => ExtraKind::Owner,
1271 Self::MetaType => ExtraKind::Node,
1272 Self::SafeRegionBegin => ExtraKind::Reason,
1273 Self::VaObject => ExtraKind::VaObject,
1274 Self::AtomicRmw => ExtraKind::Rmw,
1275 Self::Fence => ExtraKind::Order,
1276 Self::Prefetch => ExtraKind::Prefetch,
1277 Self::ObjectSize => ExtraKind::Question,
1278 // How far up the chain of frames to walk, which is a number written in the instruction
1279 // and never a value. The builtins these came from take a constant and nothing else, for
1280 // the reason `prefetch` takes one: the instructions this becomes are a walk of that
1281 // length, and a length not known until the program runs has nothing to walk.
1282 Self::FrameAddress | Self::ReturnAddress => ExtraKind::Depth,
1283 Self::Jump | Self::BrIf | Self::BlockAddr | Self::IndirectBr => ExtraKind::Targets,
1284 Self::Switch => ExtraKind::Switch,
1285 Self::Call | Self::CallIndirect | Self::TailCall => ExtraKind::Call,
1286 Self::InlineAsm => ExtraKind::Asm,
1287 _ => ExtraKind::None,
1288 }
1289 }
1290}
1291
1292/// Which of [`Extra`](crate::Extra)'s shapes an instruction carries.
1293///
1294/// The same list of names, without any of the payloads, so that a question about an opcode can
1295/// be answered without an instruction to look at.
1296#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1297pub enum ExtraKind {
1298 /// Nothing.
1299 None,
1300 /// A constant.
1301 Imm,
1302 /// A name.
1303 Symbol,
1304 /// An integer comparison predicate.
1305 IntPred,
1306 /// A floating point comparison predicate.
1307 FloatPred,
1308 /// An access.
1309 Mem,
1310 /// An atomic read-modify-write.
1311 Rmw,
1312 /// A barrier's ordering.
1313 Order,
1314 /// What a prefetch is a hint about.
1315 Prefetch,
1316 /// How many frames up to walk.
1317 Depth,
1318 /// Which of the four object size questions.
1319 Question,
1320 /// Branch targets.
1321 Targets,
1322 /// A call.
1323 Call,
1324 /// A `switch`.
1325 Switch,
1326 /// Inline assembly.
1327 Asm,
1328 /// An object read off a variable argument list.
1329 VaObject,
1330 /// What kind of storage an instance is.
1331 Class,
1332 /// Who a range of memory went to.
1333 Owner,
1334 /// A metadata node.
1335 Node,
1336 /// Why a declared exemption is there.
1337 Reason,
1338}
1339
1340impl ExtraKind {
1341 /// What it is, in words, for a message that names two of them and has to read as English.
1342 #[must_use]
1343 pub const fn name(self) -> &'static str {
1344 match self {
1345 Self::None => "nothing",
1346 Self::Imm => "a constant",
1347 Self::Symbol => "a name",
1348 Self::IntPred => "an integer comparison",
1349 Self::FloatPred => "a floating point comparison",
1350 Self::Mem => "an access",
1351 Self::Rmw => "a read-modify-write",
1352 Self::Order => "an ordering",
1353 Self::Prefetch => "a prefetch hint",
1354 Self::Depth => "a depth",
1355 Self::Question => "an object size question",
1356 Self::Targets => "branch targets",
1357 Self::Call => "a call",
1358 Self::Switch => "a switch",
1359 Self::Asm => "inline assembly",
1360 Self::VaObject => "an object off a variable argument list",
1361 Self::Class => "a storage class",
1362 Self::Owner => "an owner",
1363 Self::Node => "a metadata node",
1364 Self::Reason => "a reason",
1365 }
1366 }
1367}
1368
1369impl fmt::Display for Opcode {
1370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1371 f.write_str(self.name())
1372 }
1373}
1374
1375/// Every opcode, which is what [`Opcode::all`] hands out.
1376///
1377/// This is written out rather than derived, and the test below is what keeps it complete: it
1378/// checks the count against [`Opcode::InlineAsm`], the last variant, so a new opcode that is
1379/// not added here fails the build rather than going quietly missing from the parser.
1380static ALL: &[Opcode] = &[
1381 Opcode::IConst,
1382 Opcode::FConst,
1383 Opcode::Splat,
1384 Opcode::GlobalAddr,
1385 Opcode::BlockAddr,
1386 Opcode::Add,
1387 Opcode::Sub,
1388 Opcode::Mul,
1389 Opcode::SDiv,
1390 Opcode::UDiv,
1391 Opcode::SRem,
1392 Opcode::URem,
1393 Opcode::And,
1394 Opcode::Or,
1395 Opcode::Xor,
1396 Opcode::Shl,
1397 Opcode::LShr,
1398 Opcode::AShr,
1399 Opcode::FAdd,
1400 Opcode::FSub,
1401 Opcode::FMul,
1402 Opcode::FDiv,
1403 Opcode::FRem,
1404 Opcode::FNeg,
1405 Opcode::Fma,
1406 Opcode::ICmp,
1407 Opcode::FCmp,
1408 Opcode::Select,
1409 Opcode::Trunc,
1410 Opcode::SExt,
1411 Opcode::ZExt,
1412 Opcode::FPTrunc,
1413 Opcode::FPExt,
1414 Opcode::FPToSI,
1415 Opcode::FPToUI,
1416 Opcode::SIToFP,
1417 Opcode::UIToFP,
1418 Opcode::PtrToInt,
1419 Opcode::IntToPtr,
1420 Opcode::Bitcast,
1421 Opcode::MemEntry,
1422 Opcode::Alloca,
1423 Opcode::Load,
1424 Opcode::Store,
1425 Opcode::PtrAdd,
1426 Opcode::Memcpy,
1427 Opcode::Memmove,
1428 Opcode::Memset,
1429 Opcode::AtomicLoad,
1430 Opcode::AtomicStore,
1431 Opcode::AtomicRmw,
1432 Opcode::Cmpxchg,
1433 Opcode::Fence,
1434 Opcode::CapOf,
1435 Opcode::CapLoad,
1436 Opcode::CapStore,
1437 Opcode::CapCopy,
1438 Opcode::CapNull,
1439 Opcode::CapNarrow,
1440 Opcode::CapRecover,
1441 Opcode::CapExtent,
1442 Opcode::CapExtentBack,
1443 Opcode::CapPublish,
1444 Opcode::CapClear,
1445 Opcode::CapArg,
1446 Opcode::CapYield,
1447 Opcode::CapResult,
1448 Opcode::CheckBounds,
1449 Opcode::CheckLive,
1450 Opcode::CheckType,
1451 Opcode::CheckInit,
1452 Opcode::CheckDeriv,
1453 Opcode::CheckRace,
1454 Opcode::CheckRestrictRead,
1455 Opcode::CheckRestrictWrite,
1456 Opcode::CheckFree,
1457 Opcode::MetaBegin,
1458 Opcode::MetaEnd,
1459 Opcode::MetaType,
1460 Opcode::MetaTypeCopy,
1461 Opcode::MetaInit,
1462 Opcode::MetaInitCopy,
1463 Opcode::MetaEpoch,
1464 Opcode::MetaRelease,
1465 Opcode::MetaAcquire,
1466 Opcode::MetaFenceRelease,
1467 Opcode::MetaFenceAcquire,
1468 Opcode::MetaTransfer,
1469 Opcode::SafeRegionBegin,
1470 Opcode::SafeRegionEnd,
1471 Opcode::RestrictEnter,
1472 Opcode::RestrictLeave,
1473 Opcode::Jump,
1474 Opcode::BrIf,
1475 Opcode::Switch,
1476 Opcode::IndirectBr,
1477 Opcode::Return,
1478 Opcode::Unreachable,
1479 Opcode::Call,
1480 Opcode::CallIndirect,
1481 Opcode::TailCall,
1482 Opcode::Ctlz,
1483 Opcode::Cttz,
1484 Opcode::Ctpop,
1485 Opcode::Bswap,
1486 Opcode::Bitreverse,
1487 Opcode::SAddOverflow,
1488 Opcode::UAddOverflow,
1489 Opcode::SSubOverflow,
1490 Opcode::USubOverflow,
1491 Opcode::SMulOverflow,
1492 Opcode::UMulOverflow,
1493 Opcode::Expect,
1494 Opcode::UnreachableHint,
1495 Opcode::Trap,
1496 Opcode::Prefetch,
1497 Opcode::FrameAddress,
1498 Opcode::ReturnAddress,
1499 Opcode::ThreadPointer,
1500 Opcode::ObjectSize,
1501 Opcode::RegisterValue,
1502 Opcode::VaStart,
1503 Opcode::VaArg,
1504 Opcode::VaObject,
1505 Opcode::VaEnd,
1506 Opcode::VaCopy,
1507 Opcode::StackSave,
1508 Opcode::StackRestore,
1509 Opcode::SetjmpMarker,
1510 Opcode::LongjmpMarker,
1511 Opcode::TargetIntrinsic,
1512 Opcode::InlineAsm,
1513];
1514
1515/// The ten integer comparisons.
1516///
1517/// Signedness is on the predicate rather than on the type, for the same reason it is on
1518/// `sdiv` and `udiv`: the type space is halved and the operation says what it means.
1519#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1520pub enum IntPred {
1521 /// Equal.
1522 Eq,
1523 /// Not equal.
1524 Ne,
1525 /// Signed less than.
1526 Slt,
1527 /// Signed less than or equal.
1528 Sle,
1529 /// Signed greater than.
1530 Sgt,
1531 /// Signed greater than or equal.
1532 Sge,
1533 /// Unsigned less than.
1534 Ult,
1535 /// Unsigned less than or equal.
1536 Ule,
1537 /// Unsigned greater than.
1538 Ugt,
1539 /// Unsigned greater than or equal.
1540 Uge,
1541}
1542
1543impl IntPred {
1544 /// The textual form.
1545 #[must_use]
1546 pub const fn name(self) -> &'static str {
1547 match self {
1548 Self::Eq => "eq",
1549 Self::Ne => "ne",
1550 Self::Slt => "slt",
1551 Self::Sle => "sle",
1552 Self::Sgt => "sgt",
1553 Self::Sge => "sge",
1554 Self::Ult => "ult",
1555 Self::Ule => "ule",
1556 Self::Ugt => "ugt",
1557 Self::Uge => "uge",
1558 }
1559 }
1560
1561 /// The predicate with that name, if there is one.
1562 #[must_use]
1563 pub fn from_name(name: &str) -> Option<Self> {
1564 Self::all().find(|pred| pred.name() == name)
1565 }
1566
1567 /// Every predicate.
1568 pub fn all() -> impl Iterator<Item = Self> {
1569 [
1570 Self::Eq,
1571 Self::Ne,
1572 Self::Slt,
1573 Self::Sle,
1574 Self::Sgt,
1575 Self::Sge,
1576 Self::Ult,
1577 Self::Ule,
1578 Self::Ugt,
1579 Self::Uge,
1580 ]
1581 .into_iter()
1582 }
1583
1584 /// The predicate that holds exactly when this one does not.
1585 #[must_use]
1586 pub const fn inverse(self) -> Self {
1587 match self {
1588 Self::Eq => Self::Ne,
1589 Self::Ne => Self::Eq,
1590 Self::Slt => Self::Sge,
1591 Self::Sge => Self::Slt,
1592 Self::Sle => Self::Sgt,
1593 Self::Sgt => Self::Sle,
1594 Self::Ult => Self::Uge,
1595 Self::Uge => Self::Ult,
1596 Self::Ule => Self::Ugt,
1597 Self::Ugt => Self::Ule,
1598 }
1599 }
1600
1601 /// The predicate that holds when the operands are given the other way round.
1602 #[must_use]
1603 pub const fn swapped(self) -> Self {
1604 match self {
1605 Self::Eq => Self::Eq,
1606 Self::Ne => Self::Ne,
1607 Self::Slt => Self::Sgt,
1608 Self::Sgt => Self::Slt,
1609 Self::Sle => Self::Sge,
1610 Self::Sge => Self::Sle,
1611 Self::Ult => Self::Ugt,
1612 Self::Ugt => Self::Ult,
1613 Self::Ule => Self::Uge,
1614 Self::Uge => Self::Ule,
1615 }
1616 }
1617
1618 /// Whether this reads its operands as signed. Equality reads them as neither.
1619 #[must_use]
1620 pub const fn is_signed(self) -> bool {
1621 matches!(self, Self::Slt | Self::Sle | Self::Sgt | Self::Sge)
1622 }
1623
1624 /// The predicate that asks the same question with the bits read as unsigned.
1625 ///
1626 /// Each ordering has a counterpart the other way round and equality is the same question at
1627 /// both readings, so every predicate has one and nothing here is a refusal. What it is for is
1628 /// operands known not to be negative: the two readings agree on those, so a signed comparison
1629 /// of two of them is the unsigned comparison of them, and the unsigned one is the one that
1630 /// still holds when the same values are looked at in fewer bits.
1631 #[must_use]
1632 pub const fn unsigned(self) -> Self {
1633 match self {
1634 Self::Slt => Self::Ult,
1635 Self::Sle => Self::Ule,
1636 Self::Sgt => Self::Ugt,
1637 Self::Sge => Self::Uge,
1638 other => other,
1639 }
1640 }
1641}
1642
1643impl fmt::Display for IntPred {
1644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1645 f.write_str(self.name())
1646 }
1647}
1648
1649/// The floating point comparisons, ordered and unordered.
1650///
1651/// An ordered predicate is false if either operand is a NaN, and an unordered one is true. C's
1652/// `<` is `olt` and C's `!=` is `une`, which is the whole of why both families are here.
1653#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1654pub enum FloatPred {
1655 /// Always false.
1656 False,
1657 /// Ordered and equal.
1658 Oeq,
1659 /// Ordered and greater than.
1660 Ogt,
1661 /// Ordered and greater than or equal.
1662 Oge,
1663 /// Ordered and less than.
1664 Olt,
1665 /// Ordered and less than or equal.
1666 Ole,
1667 /// Ordered and not equal.
1668 One,
1669 /// Ordered, which is to say neither operand is a NaN.
1670 Ord,
1671 /// Unordered, which is to say one of them is.
1672 Uno,
1673 /// Unordered or equal.
1674 Ueq,
1675 /// Unordered or greater than.
1676 Ugt,
1677 /// Unordered or greater than or equal.
1678 Uge,
1679 /// Unordered or less than.
1680 Ult,
1681 /// Unordered or less than or equal.
1682 Ule,
1683 /// Unordered or not equal.
1684 Une,
1685 /// Always true.
1686 True,
1687}
1688
1689impl FloatPred {
1690 /// The textual form.
1691 #[must_use]
1692 pub const fn name(self) -> &'static str {
1693 match self {
1694 Self::False => "false",
1695 Self::Oeq => "oeq",
1696 Self::Ogt => "ogt",
1697 Self::Oge => "oge",
1698 Self::Olt => "olt",
1699 Self::Ole => "ole",
1700 Self::One => "one",
1701 Self::Ord => "ord",
1702 Self::Uno => "uno",
1703 Self::Ueq => "ueq",
1704 Self::Ugt => "ugt",
1705 Self::Uge => "uge",
1706 Self::Ult => "ult",
1707 Self::Ule => "ule",
1708 Self::Une => "une",
1709 Self::True => "true",
1710 }
1711 }
1712
1713 /// The predicate with that name, if there is one.
1714 #[must_use]
1715 pub fn from_name(name: &str) -> Option<Self> {
1716 Self::all().find(|pred| pred.name() == name)
1717 }
1718
1719 /// Every predicate.
1720 pub fn all() -> impl Iterator<Item = Self> {
1721 [
1722 Self::False,
1723 Self::Oeq,
1724 Self::Ogt,
1725 Self::Oge,
1726 Self::Olt,
1727 Self::Ole,
1728 Self::One,
1729 Self::Ord,
1730 Self::Uno,
1731 Self::Ueq,
1732 Self::Ugt,
1733 Self::Uge,
1734 Self::Ult,
1735 Self::Ule,
1736 Self::Une,
1737 Self::True,
1738 ]
1739 .into_iter()
1740 }
1741
1742 /// The predicate that holds exactly when this one does not.
1743 #[must_use]
1744 pub const fn inverse(self) -> Self {
1745 match self {
1746 Self::False => Self::True,
1747 Self::Oeq => Self::Une,
1748 Self::Ogt => Self::Ule,
1749 Self::Oge => Self::Ult,
1750 Self::Olt => Self::Uge,
1751 Self::Ole => Self::Ugt,
1752 Self::One => Self::Ueq,
1753 Self::Ord => Self::Uno,
1754 Self::Uno => Self::Ord,
1755 Self::Ueq => Self::One,
1756 Self::Ugt => Self::Ole,
1757 Self::Uge => Self::Olt,
1758 Self::Ult => Self::Oge,
1759 Self::Ule => Self::Ogt,
1760 Self::Une => Self::Oeq,
1761 Self::True => Self::False,
1762 }
1763 }
1764
1765 /// The predicate that holds when the operands are given the other way round.
1766 #[must_use]
1767 pub const fn swapped(self) -> Self {
1768 match self {
1769 Self::Ogt => Self::Olt,
1770 Self::Olt => Self::Ogt,
1771 Self::Oge => Self::Ole,
1772 Self::Ole => Self::Oge,
1773 Self::Ugt => Self::Ult,
1774 Self::Ult => Self::Ugt,
1775 Self::Uge => Self::Ule,
1776 Self::Ule => Self::Uge,
1777 same => same,
1778 }
1779 }
1780
1781 /// Whether this is false when either operand is a NaN.
1782 ///
1783 /// [`FloatPred::False`] and [`FloatPred::True`] are neither ordered nor unordered, since
1784 /// they do not look at their operands at all, and both answer no here.
1785 #[must_use]
1786 pub const fn is_ordered(self) -> bool {
1787 matches!(
1788 self,
1789 Self::Oeq | Self::Ogt | Self::Oge | Self::Olt | Self::Ole | Self::One | Self::Ord
1790 )
1791 }
1792}
1793
1794impl fmt::Display for FloatPred {
1795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1796 f.write_str(self.name())
1797 }
1798}
1799
1800#[cfg(test)]
1801mod tests {
1802 use super::*;
1803
1804 #[test]
1805 fn every_opcode_is_in_the_table() {
1806 // `InlineAsm` is the last variant, so its discriminant plus one is how many there are.
1807 // A new opcode declared after it moves this number, and a new opcode declared before
1808 // it and not added to `ALL` moves the length, so either mistake fails here.
1809 assert_eq!(ALL.len(), Opcode::InlineAsm as usize + 1);
1810 for (position, &op) in ALL.iter().enumerate() {
1811 assert_eq!(op as usize, position, "{op} is out of order in ALL");
1812 }
1813 }
1814
1815 #[test]
1816 fn every_opcode_name_is_one_word_the_reader_can_take() {
1817 // The textual form keeps the dot for the type suffix and the flags, so an opcode with a
1818 // dot in it reads back as a shorter opcode with a suffix that is not a type. The safety
1819 // instructions are spelled `cap_of` and not `cap.of` for this reason, and the
1820 // specification says so at `spec/safe-memory/06-instrumentation.md` section 6.2.2.
1821 for opcode in Opcode::all() {
1822 let name = opcode.name();
1823 assert!(!name.is_empty(), "an opcode with no name");
1824 assert!(
1825 name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
1826 "{name} is not one word"
1827 );
1828 }
1829 }
1830
1831 #[test]
1832 fn every_opcode_has_its_own_name_and_finds_it_again() {
1833 let mut names: Vec<&str> = Opcode::all().map(Opcode::name).collect();
1834 let total = names.len();
1835 names.sort_unstable();
1836 names.dedup();
1837 assert_eq!(names.len(), total, "two opcodes share a name");
1838 for op in Opcode::all() {
1839 assert_eq!(Opcode::from_name(op.name()), Some(op));
1840 }
1841 assert_eq!(Opcode::from_name("phi"), None);
1842 assert_eq!(Opcode::from_name("getelementptr"), None);
1843 assert_eq!(Opcode::from_name(""), None);
1844 }
1845
1846 #[test]
1847 fn the_terminators_are_the_ones_control_leaves_by() {
1848 let terminators: Vec<&str> =
1849 Opcode::all().filter(|op| op.is_terminator()).map(Opcode::name).collect();
1850 assert_eq!(
1851 terminators,
1852 ["jump", "br_if", "switch", "indirect_br", "return", "unreachable", "tail_call"]
1853 );
1854 }
1855
1856 #[test]
1857 fn a_terminator_produces_nothing() {
1858 for op in Opcode::all().filter(|op| op.is_terminator()) {
1859 assert_eq!(op.results(), Some(0), "{op}");
1860 }
1861 }
1862
1863 #[test]
1864 fn the_pair_producing_opcodes_are_the_ones_with_a_flag_beside_the_value() {
1865 let pairs: Vec<&str> =
1866 Opcode::all().filter(|op| op.results() == Some(2)).map(Opcode::name).collect();
1867 assert_eq!(
1868 pairs,
1869 [
1870 "cmpxchg",
1871 "sadd_overflow",
1872 "uadd_overflow",
1873 "ssub_overflow",
1874 "usub_overflow",
1875 "smul_overflow",
1876 "umul_overflow"
1877 ]
1878 );
1879 }
1880
1881 #[test]
1882 fn the_capability_instructions_are_the_ones_that_make_a_capability() {
1883 let makers: Vec<Opcode> = Opcode::all().filter(|op| op.makes_capability()).collect();
1884 assert_eq!(
1885 makers,
1886 vec![
1887 Opcode::CapOf,
1888 Opcode::CapLoad,
1889 Opcode::CapNull,
1890 Opcode::CapNarrow,
1891 Opcode::CapRecover,
1892 Opcode::CapArg,
1893 Opcode::CapResult
1894 ]
1895 );
1896 // The other three read a capability rather than making one. `cap_store` writes it out and
1897 // produces nothing at all, and the two extent queries answer with a number.
1898 assert!(!Opcode::CapStore.makes_capability());
1899 assert_eq!(Opcode::CapStore.results(), Some(0));
1900 assert!(!Opcode::CapExtent.makes_capability());
1901 assert_eq!(Opcode::CapExtent.results(), Some(1));
1902 assert!(!Opcode::CapExtentBack.makes_capability());
1903 assert_eq!(Opcode::CapExtentBack.results(), Some(1));
1904 for opcode in makers {
1905 assert_eq!(opcode.results(), Some(1), "{}", opcode.name());
1906 }
1907 }
1908
1909 #[test]
1910 fn a_producer_says_which_of_its_operands_is_the_pointer_it_is_about() {
1911 // Five of the seven, and the one that is not operand zero is the one whose first two
1912 // operands are the container and the word rather than the value that came out of it.
1913 assert_eq!(Opcode::CapOf.capability_names(), Some(0));
1914 assert_eq!(Opcode::CapRecover.capability_names(), Some(0));
1915 assert_eq!(Opcode::CapArg.capability_names(), Some(0));
1916 assert_eq!(Opcode::CapResult.capability_names(), Some(0));
1917 assert_eq!(Opcode::CapLoad.capability_names(), Some(2));
1918
1919 // The two that are about something other than a pointer this function has an operand for.
1920 assert_eq!(Opcode::CapNarrow.capability_names(), None);
1921 assert_eq!(Opcode::CapNull.capability_names(), None);
1922
1923 // Nothing that is not a producer answers, since the question is what a capability describes
1924 // and those have no capability to describe anything with.
1925 assert_eq!(Opcode::CapStore.capability_names(), None);
1926 assert_eq!(Opcode::Load.capability_names(), None);
1927 assert_eq!(Opcode::CheckLive.capability_names(), None);
1928 }
1929
1930 #[test]
1931 fn a_check_reads_the_planes_and_writes_nothing() {
1932 let checks = [
1933 Opcode::CheckBounds,
1934 Opcode::CheckLive,
1935 Opcode::CheckType,
1936 Opcode::CheckInit,
1937 Opcode::CheckDeriv,
1938 Opcode::CheckRace,
1939 Opcode::CheckFree,
1940 ];
1941 for opcode in checks {
1942 let name = opcode.name();
1943 // It traps, so it stays where it was put and nothing deletes it for having no
1944 // result. It reads a plane, so it takes a memory operand. It writes nothing, so
1945 // the access after it reads the version the check was given.
1946 assert!(opcode.has_effects(), "{name}");
1947 assert!(opcode.touches_memory(), "{name}");
1948 assert!(!opcode.writes_memory(), "{name}");
1949 assert_eq!(opcode.results(), Some(0), "{name}");
1950 }
1951 }
1952
1953 #[test]
1954 fn a_restrict_check_writes_memory_because_it_records_what_it_saw() {
1955 // The one place the sentence above does not hold. Every other check reads a plane and
1956 // leaves it alone, so the optimizer may hoist one out of a loop or keep the later of two
1957 // identical ones. These record the range they were asked about into the block's own slot,
1958 // so a check that ran twice saw two accesses and a check that was hoisted saw one, and
1959 // either rewrite changes what the next one answers. Saying they write memory is how the
1960 // memory chain refuses both.
1961 let recording = [
1962 Opcode::CheckRestrictRead,
1963 Opcode::CheckRestrictWrite,
1964 Opcode::RestrictEnter,
1965 Opcode::RestrictLeave,
1966 ];
1967 for opcode in recording {
1968 let name = opcode.name();
1969 assert!(opcode.has_effects(), "{name}");
1970 assert!(opcode.touches_memory(), "{name}");
1971 assert!(opcode.writes_memory(), "{name}");
1972 assert_eq!(opcode.results(), Some(0), "{name}");
1973 }
1974 }
1975
1976 #[test]
1977 fn the_capability_instructions_that_touch_memory_are_the_five_that_have_to() {
1978 // `cap_load` and `cap_store` are an access to the slot beside a pointer, and `cap_recover`
1979 // and the two extent queries read the planes. The other three are arithmetic on a
1980 // provenance the program already had, so the optimizer may treat them as it treats
1981 // `ptr_add`.
1982 assert!(!Opcode::CapOf.has_effects());
1983 assert!(!Opcode::CapNull.has_effects());
1984 assert!(!Opcode::CapNarrow.has_effects());
1985 assert!(Opcode::CapLoad.touches_memory() && !Opcode::CapLoad.writes_memory());
1986 assert!(Opcode::CapRecover.touches_memory() && !Opcode::CapRecover.writes_memory());
1987 assert!(Opcode::CapExtent.touches_memory() && !Opcode::CapExtent.writes_memory());
1988 assert!(Opcode::CapExtentBack.touches_memory() && !Opcode::CapExtentBack.writes_memory());
1989 assert!(Opcode::CapStore.writes_memory());
1990 }
1991
1992 #[test]
1993 fn what_only_touches_a_plane_touches_memory_and_is_not_an_access() {
1994 // Two halves. Everything in the list is on the memory chain, because an instruction the
1995 // chain does not carry is one the walk never sees and saying anything about it would be
1996 // saying it about nothing. And everything in the list comes from the safety lowering,
1997 // because the planes are the lowering's own storage and an opcode from somewhere else
1998 // claiming to touch only them is the claim being made about the wrong memory.
1999 for opcode in Opcode::all() {
2000 if !opcode.touches_only_planes() {
2001 continue;
2002 }
2003 let name = opcode.name();
2004 assert!(opcode.touches_memory(), "{name}");
2005 let instrumentation = name.starts_with("check_")
2006 || name.starts_with("meta_")
2007 || name.starts_with("cap_extent")
2008 || name == "cap_copy";
2009 assert!(instrumentation, "{name}");
2010 }
2011 for opcode in [Opcode::MetaInit, Opcode::MetaType, Opcode::CheckBounds, Opcode::CapExtent] {
2012 assert!(opcode.touches_only_planes(), "{opcode}");
2013 }
2014 }
2015
2016 #[test]
2017 fn what_goes_through_a_frame_slot_is_not_a_plane_access() {
2018 // What the list leaves out on purpose. The three capability instructions here each take a
2019 // pointer that is not a locator, since a pointer written into a slot is one a later
2020 // instruction reads back out, and the `restrict` markers write their record into the
2021 // block's own slot. The synchronization edges are left out for a different reason, which is
2022 // that they say something about the ordering of program memory and not only about a plane.
2023 let outside = [
2024 Opcode::CapLoad,
2025 Opcode::CapStore,
2026 Opcode::CapRecover,
2027 Opcode::CheckRestrictRead,
2028 Opcode::CheckRestrictWrite,
2029 Opcode::RestrictEnter,
2030 Opcode::RestrictLeave,
2031 Opcode::MetaRelease,
2032 Opcode::MetaAcquire,
2033 Opcode::MetaFenceRelease,
2034 Opcode::MetaFenceAcquire,
2035 ];
2036 for opcode in outside {
2037 assert!(!opcode.touches_only_planes(), "{opcode}");
2038 }
2039 // And nothing ordinary is in it either, since a store answering yes would be the whole
2040 // optimizer told that program memory is unreachable.
2041 for opcode in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Memcpy, Opcode::Fence] {
2042 assert!(!opcode.touches_only_planes(), "{opcode}");
2043 }
2044 }
2045
2046 #[test]
2047 fn memory_has_effects_and_arithmetic_does_not() {
2048 for op in [Opcode::Load, Opcode::Store, Opcode::Call, Opcode::Alloca, Opcode::Fence] {
2049 assert!(op.has_effects(), "{op}");
2050 }
2051 for op in [Opcode::Add, Opcode::FDiv, Opcode::ICmp, Opcode::PtrAdd, Opcode::IConst] {
2052 assert!(!op.has_effects(), "{op}");
2053 }
2054 }
2055
2056 #[test]
2057 fn commuting_is_only_claimed_where_it_holds() {
2058 assert!(Opcode::Add.is_commutative());
2059 assert!(Opcode::FAdd.is_commutative());
2060 assert!(!Opcode::Sub.is_commutative());
2061 assert!(!Opcode::FDiv.is_commutative());
2062 assert!(!Opcode::Shl.is_commutative());
2063 }
2064
2065 #[test]
2066 fn an_integer_predicate_inverts_and_swaps_back_to_itself() {
2067 for pred in IntPred::all() {
2068 assert_eq!(pred.inverse().inverse(), pred);
2069 assert_eq!(pred.swapped().swapped(), pred);
2070 assert_eq!(IntPred::from_name(pred.name()), Some(pred));
2071 }
2072 assert_eq!(IntPred::Slt.inverse(), IntPred::Sge);
2073 assert_eq!(IntPred::Slt.swapped(), IntPred::Sgt);
2074 assert_eq!(IntPred::from_name("lt"), None);
2075 }
2076
2077 #[test]
2078 fn an_integer_predicate_has_an_unsigned_counterpart_that_asks_the_same_way_round() {
2079 for pred in IntPred::all() {
2080 let unsigned = pred.unsigned();
2081 assert!(!unsigned.is_signed(), "{pred}");
2082 assert_eq!(unsigned.unsigned(), unsigned, "{pred}");
2083 // The same way round, so inverting or swapping either first gives the same answer.
2084 assert_eq!(pred.inverse().unsigned(), unsigned.inverse(), "{pred}");
2085 assert_eq!(pred.swapped().unsigned(), unsigned.swapped(), "{pred}");
2086 }
2087 assert_eq!(IntPred::Slt.unsigned(), IntPred::Ult);
2088 assert_eq!(IntPred::Sge.unsigned(), IntPred::Uge);
2089 // Equality is the same question at both readings, so it is already its own counterpart.
2090 assert_eq!(IntPred::Eq.unsigned(), IntPred::Eq);
2091 assert_eq!(IntPred::Ne.unsigned(), IntPred::Ne);
2092 }
2093
2094 #[test]
2095 fn a_floating_predicate_inverts_across_the_ordered_line() {
2096 for pred in FloatPred::all() {
2097 assert_eq!(pred.inverse().inverse(), pred);
2098 assert_eq!(pred.swapped().swapped(), pred);
2099 assert_eq!(FloatPred::from_name(pred.name()), Some(pred));
2100 }
2101 // Inverting has to cross the line, because the negation of an ordered comparison is
2102 // true when an operand is a NaN. This is where `!(a < b)` stops being `a >= b`. The
2103 // two constants are outside it: neither of them looks at its operands.
2104 for pred in FloatPred::all().filter(|p| !matches!(p, FloatPred::False | FloatPred::True)) {
2105 assert_ne!(pred.is_ordered(), pred.inverse().is_ordered(), "{pred}");
2106 }
2107 assert_eq!(FloatPred::Olt.inverse(), FloatPred::Uge);
2108 assert_eq!(FloatPred::Olt.swapped(), FloatPred::Ogt);
2109 }
2110
2111 #[test]
2112 fn swapping_a_predicate_keeps_it_ordered_or_unordered() {
2113 for pred in FloatPred::all() {
2114 assert_eq!(pred.is_ordered(), pred.swapped().is_ordered(), "{pred}");
2115 }
2116 for pred in IntPred::all() {
2117 assert_eq!(pred.is_signed(), pred.swapped().is_signed(), "{pred}");
2118 }
2119 }
2120
2121 #[test]
2122 fn no_two_predicates_share_a_name_within_their_family() {
2123 for names in [
2124 IntPred::all().map(IntPred::name).collect::<Vec<_>>(),
2125 FloatPred::all().map(FloatPred::name).collect::<Vec<_>>(),
2126 ] {
2127 let total = names.len();
2128 let mut names = names;
2129 names.sort_unstable();
2130 names.dedup();
2131 assert_eq!(names.len(), total);
2132 }
2133 }
2134}