rucc_codegen/expand.rs
1//! The IR rewrites the machine needs before a rule can be asked anything.
2//!
3//! Design: `spec/10-backend.md` section 10.2, which is where the ordering comes from.
4//!
5//! Everything else in this crate turns an instruction into instructions. There are two things a
6//! rule cannot do, and one of them is dealt with here and one next door.
7//!
8//! The one next door is a new shape of control flow. A rule replaces a term with a term and the
9//! replacement has nowhere to put a block, so a construct that becomes blocks has to be rewritten
10//! before selection rather than during it. There is one such construct and it is `switch`. Every
11//! other terminator leaves a block with one successor or two, which is what the block layout
12//! writes jumps for, and a `switch` leaves it with as many as the program had cases. What it
13//! becomes is a decision large enough to have a document of its own, so it has a module of its
14//! own, which is [`crate::switch`].
15//!
16//! The one here is arithmetic on what a rule matched. A rule may name a constant and pass it along,
17//! and it may not add to one or read it as something else, because the pattern language is a
18//! pattern language and giving it a way to compute would make a rule set a program the solver has
19//! to reason about rather than a table it can check a line of at a time. So an instruction whose
20//! lowering needs a value worked out from another one is rewritten here into instructions whose
21//! lowerings do not. Four of them are floats: a float constant, a negation, and the two conversions
22//! between a float and an unsigned integer. The other two move a block of memory, where the
23//! arithmetic is the offset of each word from the front of it.
24//!
25//! # Why a copy is a run of moves and not a call
26//!
27//! A `memcpy` in the IR is not a call to `memcpy`. It is what the front end writes for a structure
28//! assigned, passed or returned by value, and a `memset` is what it writes for the part of an
29//! object an initialiser left unnamed, so a program with a `struct` in it reaches one almost at
30//! once and the size is a constant every time.
31//!
32//! A constant size is what makes the moves the right answer. A four byte copy written as a call
33//! costs the call and the two arguments and gives back four bytes moved, which is more instructions
34//! than the move it replaced and slower than all of them. Every real compiler writes the moves
35//! under some threshold for that reason, and above the threshold writes the call, which is where
36//! this stops: the call needs a `memcpy` to exist, and a statically linked program has nowhere to
37//! get one from until the compiler runtime in tamnd/rucc#277 exists. So a copy larger than the
38//! threshold is refused by name rather than written wrong.
39
40use std::cmp::Ordering;
41use std::collections::HashMap;
42
43use rucc_base::{Idx, Interner};
44use rucc_ir::{
45 CallInfo, Def, Extra, Flags, FloatPred, Func, Imm, Inst, InstData, IntPred, MemInfo, MemOrder,
46 Opcode, Signature, Type, Value,
47};
48
49use crate::capability;
50
51/// Rewrites every ordered access into the plain access this machine already makes ordered, and
52/// leaves a barrier where the machine needs one.
53///
54/// This is the one pass here whose reason is a memory model rather than a missing instruction, so
55/// it is worth writing down what the model says. x86-64 is total store order. Every load is an
56/// acquire, every store is a release, and an aligned access no wider than a word is indivisible
57/// whether or not anybody asked for one. So an `atomic_load` at any ordering is the same `mov` a
58/// `load` is, and so is an `atomic_store` at every ordering except the strongest, and rewriting
59/// them into the plain access is not an approximation: it is the whole of what the machine does.
60///
61/// The one thing total store order does not give is a store followed by a load of a different
62/// address staying in that order, and that is exactly what sequential consistency is missing. So a
63/// sequentially consistent store is the same `mov` with an `mfence` behind it, which is the pair
64/// gcc 16.2.0 writes. The fence is left in the IR as a `fence` rather than written here, because
65/// what a barrier costs is a target question and [`crate::lower`] is where the target answers are.
66///
67/// A `fence` the program wrote is left alone for the same reason. Every ordering below the
68/// strongest is nothing at all on this machine and the strongest is one instruction, and both of
69/// those are decided by name in [`crate::lower`] where the instruction lives.
70///
71/// # Why the width is checked
72///
73/// An access is only indivisible if the machine can do it in one go, which here means one, two,
74/// four or eight bytes at an address aligned to its own width. Anything else is a run of accesses
75/// and a run of accesses is not atomic at all, so it is left as the opcode it was and no rule
76/// covers it, which is a compile error naming the instruction. That is the right answer: an
77/// atomic access the machine cannot make atomic has no correct lowering, and a wrong one that
78/// looks right is worse than a refusal. C says the same thing through `__atomic_is_lock_free`.
79///
80/// `word` is how many bytes the widest indivisible access carries, which is the same number the
81/// widest move carries and is read from the machine for the reason [`bulk`] reads it.
82///
83/// This runs before every other pass here, so that what it produces is an ordinary load or store
84/// that the width legalisation and everything after it get to see. An ordered access at a width the
85/// machine has no register for would otherwise be a shape nothing later understands, since every
86/// pass after this one is written about `load` and `store` by name.
87pub fn orderings(func: &mut Func, word: u32) {
88 let found: Vec<Inst> =
89 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
90 for inst in found {
91 match func[inst].opcode {
92 Opcode::AtomicLoad => relaxed(func, inst, Opcode::Load, word),
93 Opcode::AtomicStore => relaxed(func, inst, Opcode::Store, word),
94 _ => {}
95 }
96 }
97}
98
99/// One ordered access as the plain one, with a barrier behind it when the ordering asked for more
100/// than the machine gives for free.
101///
102/// The ordering is taken off the access rather than left on it, because the IR verifier refuses an
103/// ordering on a plain access, and it refuses one for a good reason: a plain load may be moved,
104/// duplicated and dropped, and an ordering that survived on one would be a claim nothing downstream
105/// honours. What is true after this pass is that the ordering has been discharged, and the way to
106/// say that is to stop carrying it.
107///
108/// A sequentially consistent store becomes the store and then the fence, and it is built that way
109/// round: the plain store is put in front of the instruction and the instruction itself becomes the
110/// fence. Doing it the other way would need somewhere to insert behind an instruction, and there is
111/// nothing to gain from having two ways to insert.
112fn relaxed(func: &mut Func, inst: Inst, plain: Opcode, word: u32) {
113 let Extra::Mem(mem) = func[inst].extra else { return };
114 let info = func[mem];
115 let ty = match plain {
116 Opcode::Store => match func[func[inst].args].first() {
117 Some(&value) => func[value].ty,
118 None => return,
119 },
120 _ => produced(func, inst),
121 };
122 if !indivisible(ty, info, word) {
123 return;
124 }
125 let unordered = MemInfo { order: MemOrder::NotAtomic, ..info };
126
127 if plain == Opcode::Store && info.order == MemOrder::SeqCst {
128 let [value, addr] = func[func[inst].args] else { return };
129 write(func, inst, value, addr, unordered);
130 let none = func.push_values(&[]);
131 let data = &mut func[inst];
132 data.opcode = Opcode::Fence;
133 data.args = none;
134 data.extra = Extra::Order(MemOrder::SeqCst);
135 data.flags = data.flags.intersection(Flags::legal_on(Opcode::Fence));
136 return;
137 }
138
139 let plainly = func.add_mem(unordered);
140 let data = &mut func[inst];
141 data.opcode = plain;
142 data.extra = Extra::Mem(plainly);
143 data.flags = data.flags.intersection(Flags::legal_on(plain));
144}
145
146/// Whether this machine does an access of this type in one go.
147///
148/// One, two, four or eight bytes, at an address aligned to at least that many. The alignment is the
149/// front end's answer for the type being accessed, which for every type C can spell is its own
150/// width, so what this actually refuses is a `long double` and an access the program underaligned
151/// on purpose.
152///
153/// The width is the storage the value takes and not the bits it holds, because that is what the
154/// access moves. A `bool` is one bit of value in one byte of memory and one byte is indivisible, so
155/// rounding up is what makes an ordered access of one work rather than a refusal nobody wanted. An
156/// address is the exception the other way: the IR gives a pointer no width at all, since how wide
157/// one is belongs to the target, so the target's number is used for it.
158fn indivisible(ty: Type, info: MemInfo, word: u32) -> bool {
159 let bytes = if ty.is_ptr() { word } else { ty.bits().div_ceil(8) };
160 ty.is_scalar() && bytes.is_power_of_two() && bytes <= word && info.align >= bytes
161}
162
163/// Rewrites the float instructions no rule can be written for, and leaves the rest alone.
164///
165/// Each of them needs a value worked out from one the pattern matched, which is the one thing the
166/// rule language deliberately cannot do. A float constant is an integer constant read as a float,
167/// and reading it is arithmetic on the immediate. A negation is an exclusive or with a mask that
168/// depends on the format. A conversion between a float and an integer is that conversion at a
169/// width the machine has, which is a width neither the pattern nor the replacement can work out.
170///
171/// What is left after this is a function whose float instructions are each one machine
172/// instruction, so what a rule is asked stays a table. The conversions between a float and an
173/// unsigned sixty four bit integer are the two that are not a widening or a narrowing away from a
174/// signed one, because there is no signed width that holds those values, and each gets a rewrite
175/// of its own below.
176pub fn floats(func: &mut Func) {
177 let found: Vec<Inst> =
178 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
179 for inst in found {
180 match func[inst].opcode {
181 Opcode::FConst => constant(func, inst),
182 Opcode::FNeg => negate(func, inst),
183 Opcode::SIToFP | Opcode::UIToFP => widen_then_convert(func, inst),
184 Opcode::FPToSI | Opcode::FPToUI => convert_then_narrow(func, inst),
185 _ => {}
186 }
187 }
188}
189
190/// A float constant, as the integer that spells it and a reading of those bits as the float.
191///
192/// This is the whole of what a `movsd` from a literal would be if there were a section to put the
193/// literal in, and there is not one yet. Two instructions in a register beats a constant pool that
194/// nothing else needs, and it is exactly what the bits of the immediate already say, since the IR
195/// holds a float constant as its bit pattern rather than as a number.
196///
197/// Not above sixty four bits, for the reason [`negate`] is not: the integer that would spell an
198/// eighty bit constant has no register either, so the exchange gains nothing. A back end with a
199/// float that wide writes the bits where the value lives, which for this one is a stack slot.
200fn constant(func: &mut Func, inst: Inst) {
201 let ty = produced(func, inst);
202 let Extra::Imm(imm) = func[inst].extra else { return };
203 if !ty.is_float() || !ty.is_scalar() || ty.bits() > 64 {
204 return;
205 }
206 let int = Type::int(ty.bits());
207 let bits = func[imm].bits();
208 // The cast is the bits as they are stored, and `Imm::int` keeps the width, so a constant whose
209 // top bit is set stays the negative integer that spells it rather than becoming a wider one.
210 let spelled = ahead_const(func, inst, Imm::int(bits as i128, int), int);
211 becomes(func, inst, Opcode::Bitcast, &[spelled]);
212}
213
214/// A negation, as an exclusive or with the sign bit.
215///
216/// C says negation flips the sign and says nothing else about it, which is not what subtracting
217/// from zero does to a zero or to a not a number, so this is the operation the IR already calls
218/// out as not being `0 - x`. Flipping the bit is the whole of it, and it is right for every value
219/// a float can hold, the payload of a not a number included, because no other bit is touched.
220///
221/// The bit is flipped in a general purpose register rather than in the one the float is in. The
222/// other way is one instruction rather than three and it wants the mask in memory aligned to the
223/// register, which is the same section a constant pool would need.
224///
225/// Not above sixty four bits, where the exchange stops being one. An `i80` is as far from a
226/// register as an `f80` is, so what this would hand the back end is three instructions it cannot
227/// write instead of one it can: a machine with a float that wide has a sign flip for it, because a
228/// machine with no way to flip the sign of its own widest float would be a strange machine.
229fn negate(func: &mut Func, inst: Inst) {
230 let ty = produced(func, inst);
231 let Some(&arg) = func[func[inst].args].first() else { return };
232 if !ty.is_float() || !ty.is_scalar() || ty.bits() > 64 {
233 return;
234 }
235 let int = Type::int(ty.bits());
236 let bits = ahead(func, inst, Opcode::Bitcast, &[arg], int);
237 let mask = ahead_const(func, inst, Imm::int(1i128 << (ty.bits() - 1), int), int);
238 let flipped = ahead(func, inst, Opcode::Xor, &[bits, mask], int);
239 becomes(func, inst, Opcode::Bitcast, &[flipped]);
240}
241
242/// An integer becoming a float, as a widening and the signed conversion at a width there is one at.
243///
244/// The widening is with the sign for a signed integer and with zeroes for an unsigned one, and
245/// after it the value is the same number in a signed integer the machine converts from, so the
246/// conversion is the same value and the same rounding. That is the whole of why the machine needs
247/// no unsigned conversion and none at a width narrower than an `int`.
248fn widen_then_convert(func: &mut Func, inst: Inst) {
249 let signed = func[inst].opcode == Opcode::SIToFP;
250 let Some(&arg) = func[func[inst].args].first() else { return };
251 let from = func[arg].ty;
252 if !from.is_int() || !from.is_scalar() {
253 return;
254 }
255 let Some(width) = holder(from.bits(), signed) else {
256 from_unsigned_word(func, inst, arg, from);
257 return;
258 };
259 if width == from.bits() {
260 return;
261 }
262 let widen = if signed { Opcode::SExt } else { Opcode::ZExt };
263 let wide = ahead(func, inst, widen, &[arg], Type::int(width));
264 becomes(func, inst, Opcode::SIToFP, &[wide]);
265}
266
267/// A float becoming an integer, as the signed conversion at such a width and a narrowing.
268///
269/// The same argument the other way round. A float the program says fits in the integer it asked
270/// for fits in the signed one that holds every value of it, so converting there and keeping the
271/// low bits is that value however it is read, and a float that does not fit is undefined in C and
272/// unspecified in the model at either width.
273fn convert_then_narrow(func: &mut Func, inst: Inst) {
274 let signed = func[inst].opcode == Opcode::FPToSI;
275 let ty = produced(func, inst);
276 let Some(&arg) = func[func[inst].args].first() else { return };
277 if !ty.is_int() || !ty.is_scalar() {
278 return;
279 }
280 let Some(width) = holder(ty.bits(), signed) else {
281 to_unsigned_word(func, inst, arg, ty);
282 return;
283 };
284 if width == ty.bits() {
285 return;
286 }
287 let wide = ahead(func, inst, Opcode::FPToSI, &[arg], Type::int(width));
288 becomes(func, inst, Opcode::Trunc, &[wide]);
289}
290
291/// An unsigned sixty four bit integer becoming a float, without a branch.
292///
293/// This is the one conversion into a float that is not the signed one at some width, because there
294/// is no signed width that holds every value of it. What the machine can do is the signed
295/// conversion, so the value has to be brought under half of its range first and put back after.
296///
297/// Halving it is a shift, and a shift throws away the bit it shifts out, which is the difference
298/// between a number that rounds up and one that rounds down. So the bit is put back as the lowest
299/// bit of the half: a half that was exact stays exact, and one that was not comes out odd, which is
300/// never a value the conversion rounds to and so never a value it rounds the wrong way from. That
301/// is round to odd, and rounding to odd and then to nearest is the same answer as rounding to
302/// nearest once, at every width a float here has. Doubling afterwards is exact, since a float
303/// multiplied by two is the same digits with one more on the exponent and nothing here is near the
304/// top of the range.
305///
306/// A value whose top bit is clear needs none of that and is the signed conversion as it stands, so
307/// there are two answers and the machine has to pick one. gcc writes a branch. This writes the
308/// choice as arithmetic, because a branch here would mean splitting the block this instruction is
309/// in, and every rewrite in this pass stays inside one block. A mask that is every bit or no bit
310/// picks the source, and the same mask over the bits of the result picks between doubling it and
311/// adding a zero to it. That is more instructions than gcc's and no branch to predict wrong.
312fn from_unsigned_word(func: &mut Func, inst: Inst, arg: Value, from: Type) {
313 let ty = produced(func, inst);
314 if !ty.is_float() || !ty.is_scalar() {
315 return;
316 }
317 if ty.bits() > 64 {
318 from_unsigned_word_wide(func, inst, arg, from);
319 return;
320 }
321 let spread = spread_top_bit(func, inst, arg, from);
322
323 // The value halved, with the bit the halving lost put back as the lowest bit of it.
324 let one = ahead_const(func, inst, Imm::int(1, from), from);
325 let lost = ahead(func, inst, Opcode::And, &[arg, one], from);
326 let half = ahead(func, inst, Opcode::LShr, &[arg, one], from);
327 let odd = ahead(func, inst, Opcode::Or, &[half, lost], from);
328
329 // The source, as the value with the difference between the two conditionally taken out of it.
330 let differ = ahead(func, inst, Opcode::Xor, &[arg, odd], from);
331 let taken = ahead(func, inst, Opcode::And, &[differ, spread], from);
332 let source = ahead(func, inst, Opcode::Xor, &[arg, taken], from);
333 let converted = ahead(func, inst, Opcode::SIToFP, &[source], ty);
334
335 // The doubling, as the result added to itself or to a zero. The mask is the same one narrowed
336 // to the width of the float, since the top bit it came from is a fact about the integer.
337 let bits = Type::int(ty.bits());
338 let narrow = same_width(func, inst, spread, from, bits);
339 let raw = ahead(func, inst, Opcode::Bitcast, &[converted], bits);
340 let again = ahead(func, inst, Opcode::And, &[raw, narrow], bits);
341 let addend = ahead(func, inst, Opcode::Bitcast, &[again], ty);
342 becomes(func, inst, Opcode::FAdd, &[converted, addend]);
343}
344
345/// A float becoming an unsigned sixty four bit integer, without a branch.
346///
347/// The same argument the other way round, and the same reason there is no branch. A float below
348/// half the range converts as the signed one and is already the answer. One at or above it has half
349/// the range subtracted first, which is exact because the two have the same exponent or a smaller
350/// one, converts into the signed integer that now holds it, and gets the top bit put back on.
351///
352/// The subtraction is of a constant that is either half the range or a positive zero, which is the
353/// same mask trick as above written over the bits of the float, and subtracting a positive zero
354/// leaves every value alone including a negative zero. A float too big for the answer, or a not a
355/// number, is undefined in C and unspecified in the model, so the comparison being false for a not
356/// a number costs nothing: it takes the path whose answer was never promised either way.
357fn to_unsigned_word(func: &mut Func, inst: Inst, arg: Value, ty: Type) {
358 let from = func[arg].ty;
359 if !from.is_float() || !from.is_scalar() {
360 return;
361 }
362 if from.bits() > 64 {
363 to_unsigned_word_wide(func, inst, arg, ty);
364 return;
365 }
366 // Half the range, as the float that spells it and the bits that spell the float.
367 let bits = Type::int(from.bits());
368 let pattern = Imm::int(half_the_range(from.bits()), bits);
369 let spelled = ahead_const(func, inst, pattern, bits);
370 let half = ahead(func, inst, Opcode::Bitcast, &[spelled], from);
371
372 let over = ahead_cmp(func, inst, Opcode::FCmp, Extra::FloatPred(FloatPred::Oge), &[arg, half]);
373 let wide = ahead(func, inst, Opcode::ZExt, &[over], bits);
374 let zero = ahead_const(func, inst, Imm::int(0, bits), bits);
375 let spread = ahead(func, inst, Opcode::Sub, &[zero, wide], bits);
376
377 let amount = ahead(func, inst, Opcode::And, &[spread, spelled], bits);
378 let taken = ahead(func, inst, Opcode::Bitcast, &[amount], from);
379 let under = ahead(func, inst, Opcode::FSub, &[arg, taken], from);
380 let low = ahead(func, inst, Opcode::FPToSI, &[under], ty);
381
382 // The top bit back on, from the same comparison at the width of the answer.
383 let again = ahead(func, inst, Opcode::ZExt, &[over], ty);
384 let up = ahead_const(func, inst, Imm::int(i128::from(ty.bits() - 1), ty), ty);
385 let top = ahead(func, inst, Opcode::Shl, &[again, up], ty);
386 becomes(func, inst, Opcode::Xor, &[low, top]);
387}
388
389/// An unsigned sixty four bit integer becoming a float wider than that, without a branch.
390///
391/// Neither sequence above can be written at this width, and for the same reason both of them end in
392/// a `bitcast`: the mask that picks between the two answers is laid over the bits of the result, and
393/// a float this wide has no integer holding its bits any more than it has a register holding it. So
394/// the choice has to be made somewhere other than in the bits, and the somewhere is the float
395/// arithmetic itself.
396///
397/// What replaces it is also smaller than what it replaces, because a float this wide has sixty four
398/// bits of significand and so holds every value of a sixty four bit integer exactly. Nothing rounds,
399/// so there is nothing to round to odd first, and the halving and the doubling both go away. The
400/// value is converted as a signed integer, which is the number when the top bit is clear and the
401/// number less two to the sixty fourth when it is set, and that constant is added back in the second
402/// case. Both of those additions are exact, since either operand of one is a value the significand
403/// holds and so is the answer.
404///
405/// The choice is a comparison turned into a one or a zero, converted into a float and multiplied by
406/// the constant, which is where the mask would have been. A float times one is itself and a float
407/// times a positive zero is a positive zero, so what the addition gets is the constant or a zero it
408/// leaves every value alone including a negative zero, and the conversion never produces one of
409/// those anyway.
410fn from_unsigned_word_wide(func: &mut Func, inst: Inst, arg: Value, from: Type) {
411 let ty = produced(func, inst);
412 let zero = ahead_const(func, inst, Imm::int(0, from), from);
413 let over = ahead_cmp(func, inst, Opcode::ICmp, Extra::IntPred(IntPred::Slt), &[arg, zero]);
414
415 let signed = ahead(func, inst, Opcode::SIToFP, &[arg], ty);
416 let range = ahead_float(func, inst, two_to_the(64), ty);
417 let flag = flag_as_float(func, inst, over, ty);
418 let addend = ahead(func, inst, Opcode::FMul, &[range, flag], ty);
419 becomes(func, inst, Opcode::FAdd, &[signed, addend]);
420}
421
422/// A float wider than sixty four bits becoming an unsigned sixty four bit integer, without a branch.
423///
424/// The same argument the other way round and the same answer to it. The shape is the sequence above
425/// this one with the two `bitcast`s gone: half the range is a constant of the float's own type
426/// rather than an integer read as one, and the conditional subtraction is that constant multiplied
427/// by a one or a zero rather than masked with one.
428///
429/// Subtracting is exact here for the reason it is at the narrower widths, since the value is at
430/// least as large as what is taken off it. A value too big for the answer, or a not a number, takes
431/// the path whose answer C never promised, which is the same place the comparison being false for a
432/// not a number puts it.
433fn to_unsigned_word_wide(func: &mut Func, inst: Inst, arg: Value, ty: Type) {
434 let from = func[arg].ty;
435 let half = ahead_float(func, inst, two_to_the(63), from);
436 let over = ahead_cmp(func, inst, Opcode::FCmp, Extra::FloatPred(FloatPred::Oge), &[arg, half]);
437
438 let flag = flag_as_float(func, inst, over, from);
439 let taken = ahead(func, inst, Opcode::FMul, &[half, flag], from);
440 let under = ahead(func, inst, Opcode::FSub, &[arg, taken], from);
441 let low = ahead(func, inst, Opcode::FPToSI, &[under], ty);
442
443 // The top bit back on, from the same comparison at the width of the answer.
444 let again = ahead(func, inst, Opcode::ZExt, &[over], ty);
445 let up = ahead_const(func, inst, Imm::int(i128::from(ty.bits() - 1), ty), ty);
446 let top = ahead(func, inst, Opcode::Shl, &[again, up], ty);
447 becomes(func, inst, Opcode::Xor, &[low, top]);
448}
449
450/// A condition as a float that is a one or a positive zero, which is what stands in for a mask.
451///
452/// The widening is to sixty four bits rather than to whatever the float came from, since the value
453/// is a one or a zero and the conversion wants an integer the machine converts from. Neither of the
454/// two numbers is anywhere near needing rounding.
455fn flag_as_float(func: &mut Func, inst: Inst, cond: Value, ty: Type) -> Value {
456 let wide = ahead(func, inst, Opcode::ZExt, &[cond], Type::int(64));
457 ahead(func, inst, Opcode::SIToFP, &[wide], ty)
458}
459
460/// The bits of the eighty bit float that is two to this power.
461///
462/// The significand of a power of two is the leading bit and nothing else, which in this format is
463/// written down rather than implied, and the exponent is the power with the bias on it.
464const fn two_to_the(power: u32) -> u128 {
465 ((0x3fff + power as u128) << 64) | 0x8000_0000_0000_0000
466}
467
468/// The top bit of an integer spread over every bit of one, which is every bit or no bit.
469///
470/// A comparison against zero rather than a shift, because the answer wanted is a mask and the
471/// machine writes a mask out of a condition the same way either way, and the comparison says what
472/// the question was.
473fn spread_top_bit(func: &mut Func, inst: Inst, arg: Value, ty: Type) -> Value {
474 let zero = ahead_const(func, inst, Imm::int(0, ty), ty);
475 let set = ahead_cmp(func, inst, Opcode::ICmp, Extra::IntPred(IntPred::Slt), &[arg, zero]);
476 let wide = ahead(func, inst, Opcode::ZExt, &[set], ty);
477 ahead(func, inst, Opcode::Sub, &[zero, wide], ty)
478}
479
480/// A value brought to another integer width, and itself when the two are already the same.
481fn same_width(func: &mut Func, inst: Inst, value: Value, from: Type, to: Type) -> Value {
482 match to.bits().cmp(&from.bits()) {
483 Ordering::Equal => value,
484 Ordering::Less => ahead(func, inst, Opcode::Trunc, &[value], to),
485 Ordering::Greater => ahead(func, inst, Opcode::SExt, &[value], to),
486 }
487}
488
489/// The bits of the float of this width that is two to the sixty third.
490///
491/// Half of what an unsigned sixty four bit integer holds, which is the one number both conversions
492/// above are written around. The exponent is biased and the significand is zero in both formats,
493/// so it is the bias plus sixty three shifted up past the significand.
494fn half_the_range(width: u32) -> i128 {
495 match width {
496 32 => 0x5F00_0000,
497 _ => 0x43E0_0000_0000_0000,
498 }
499}
500
501/// Rewrites every byte swap into the shifts and masks that are one, and leaves the rest alone.
502///
503/// A byte swap is a rule on a machine that has the instruction and this everywhere else, and until
504/// `x64.bswap` is a term the model knows about, this is what x86-64 gets too. That is tamnd/rucc#307
505/// and the whole of what is left of it: what is written below is correct at every width and slower
506/// than the one instruction, which is the trade `spec/10-backend.md` section 10.3 says the fast path
507/// makes everywhere.
508///
509/// It is here rather than in the front end because the masks are worked out from the width, and
510/// arithmetic on a value a pattern matched is the one thing the rule language deliberately cannot
511/// do. It is here rather than in the walk to the IR because a byte swap is one instruction in the
512/// IR and should stay one for as long as anything is reading the IR, so that the day the rule
513/// exists nothing above the backend has to change.
514pub fn bytes(func: &mut Func) {
515 let found: Vec<Inst> =
516 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
517 for inst in found {
518 if func[inst].opcode == Opcode::Bswap {
519 swap(func, inst);
520 }
521 }
522}
523
524/// One byte swap, as a halving run of swaps of adjacent groups of bits.
525///
526/// Reversing eight bytes is swapping the two halves, then the two halves of each half, then the two
527/// bytes of each of those, and the three steps commute because each is a permutation of positions
528/// the others do not touch. So the run goes from the widest group down to a byte, and every step is
529/// the same five instructions: keep the even numbered groups, move them up, move the odd numbered
530/// ones down, keep those, and put the two together.
531///
532/// Nine instructions for two bytes, seventeen for four, twenty five for eight, before the constants.
533/// Writing it as a shift and a mask per byte instead is fewer steps to read and more instructions at
534/// every width above two, since the cost there grows with the number of bytes rather than with the
535/// logarithm of it.
536///
537/// A width that is not a whole number of bytes is left alone. The verifier does not allow one, and
538/// silently reversing something else would be worse than the instruction surviving to a selector
539/// that has no rule for it and says so.
540fn swap(func: &mut Func, inst: Inst) {
541 let ty = produced(func, inst);
542 let Some(&arg) = func[func[inst].args].first() else { return };
543 if !ty.is_int() || !ty.is_scalar() || ty.bits() < 16 || ty.bits() % 8 != 0 {
544 return;
545 }
546
547 let mut value = arg;
548 let mut group = ty.bits() / 2;
549 while group >= 8 {
550 // The pattern that keeps every other run of `group` bits, counting the run at the bottom as
551 // the first one kept. It is what says which half of each pair moves up and which moves down.
552 let mask = alternating(ty.bits(), group);
553 let keep = ahead_const(func, inst, Imm::int(mask, ty), ty);
554 let count = ahead_const(func, inst, Imm::int(i128::from(group), ty), ty);
555 let low = ahead(func, inst, Opcode::And, &[value, keep], ty);
556 let up = ahead(func, inst, Opcode::Shl, &[low, count], ty);
557 let down = ahead(func, inst, Opcode::LShr, &[value, count], ty);
558 let high = ahead(func, inst, Opcode::And, &[down, keep], ty);
559 // The last step of the last round is the instruction itself, so the value everything
560 // downstream already reads is the answer and nothing has to be substituted.
561 if group == 8 {
562 becomes(func, inst, Opcode::Or, &[up, high]);
563 return;
564 }
565 value = ahead(func, inst, Opcode::Or, &[up, high], ty);
566 group /= 2;
567 }
568}
569
570/// The mask that keeps every other run of `group` bits out of `width` of them, starting with the
571/// run at the bottom.
572///
573/// Sixteen bits in groups of eight is `0x00ff`, thirty two in groups of eight is `0x00ff00ff`, and
574/// thirty two in groups of sixteen is `0x0000ffff`. Built rather than written down because there is
575/// one of these per width per group and a table of them is a table to get wrong.
576///
577/// The top group is always one of the dropped ones, since the run at the bottom is kept and the
578/// width is an even number of groups, so the answer never has its sign bit set and reads the same
579/// as a number as it does as a pattern.
580fn alternating(width: u32, group: u32) -> i128 {
581 every(width, group * 2, group)
582}
583
584/// The pattern with the low `run` bits of every `step` bit group set, out of `width` of them.
585///
586/// `every(32, 2, 1)` is `0x55555555` and `every(64, 8, 1)` is `0x0101010101010101`. Built rather
587/// than written down for the reason the byte swap masks are: there is one of these per width per
588/// group and a table of them is a table to get wrong.
589///
590/// The top group is never a full one when `run` is less than `step`, so the answer never has its
591/// sign bit set and reads the same as a number as it does as a pattern.
592fn every(width: u32, step: u32, run: u32) -> i128 {
593 let ones = (1i128 << run) - 1;
594 let mut mask = 0i128;
595 let mut at = 0;
596 while at < width {
597 mask |= ones << at;
598 at += step;
599 }
600 mask
601}
602
603/// Rewrites every bit count into the arithmetic that is one, and leaves the rest alone.
604///
605/// Three instructions and no rules, which is tamnd/rucc#310. `popcnt` is one instruction on a
606/// machine that has it and `bsr` and `bsf` are the two searches, and none of the three is a term the
607/// model knows about yet, so what runs today is what runs everywhere. The trade is the one
608/// `spec/10-backend.md` section 10.3 describes and `expand::bytes` above makes for the same reason:
609/// slower than the instruction, right on every target, and built only out of rules the verifier has
610/// already discharged.
611///
612/// The two searches are rewritten first, into a set bit count and a little arithmetic, and then
613/// every set bit count is rewritten. That is one pass rather than two because the second sweep picks
614/// up what the first one wrote, and it means there is one place that knows how to count bits rather
615/// than three.
616pub fn counts(func: &mut Func) {
617 let found: Vec<Inst> =
618 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
619 for inst in found {
620 match func[inst].opcode {
621 Opcode::Ctlz => searched(func, inst, true),
622 Opcode::Cttz => searched(func, inst, false),
623 _ => {}
624 }
625 }
626 let found: Vec<Inst> =
627 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
628 for inst in found {
629 if func[inst].opcode == Opcode::Ctpop {
630 counted(func, inst);
631 }
632 }
633}
634
635/// A leading or trailing zero count, as the set bit count of a value with those zeroes turned into
636/// the only bits that are set.
637///
638/// For trailing zeroes that is `~x & (x - 1)`, which is exactly the run of zeroes below the lowest
639/// set bit and nothing else, because `x - 1` sets that run and clears the bit above it while `~x`
640/// keeps only positions `x` did not have.
641///
642/// For leading zeroes it is the same idea upside down. Smearing every set bit downwards, by folding
643/// the value into itself shifted right by one, two, four and so on, leaves ones everywhere at or
644/// below the highest set bit, so the complement is exactly the leading zeroes. That is five extra
645/// steps at thirty two bits and six at sixty four, which is why the search instruction is worth
646/// having and why #310 stays open for it.
647///
648/// Both answer the width for a zero argument, which is what they have to answer for `ffs` to be
649/// masked correctly and is more than C asks for: `__builtin_clz(0)` and `__builtin_ctz(0)` are
650/// undefined, so nothing may rely on this, and the point of writing it down is that it is defined
651/// here rather than being whatever a register happened to hold.
652fn searched(func: &mut Func, inst: Inst, leading: bool) {
653 let ty = produced(func, inst);
654 let Some(&arg) = func[func[inst].args].first() else { return };
655 if !countable(ty) {
656 return;
657 }
658 let ones = ahead_const(func, inst, Imm::int(-1, ty), ty);
659 if leading {
660 let mut value = arg;
661 let mut by = 1;
662 while by < ty.bits() {
663 let count = ahead_const(func, inst, Imm::int(i128::from(by), ty), ty);
664 let down = ahead(func, inst, Opcode::LShr, &[value, count], ty);
665 value = ahead(func, inst, Opcode::Or, &[value, down], ty);
666 by *= 2;
667 }
668 let above = ahead(func, inst, Opcode::Xor, &[value, ones], ty);
669 becomes(func, inst, Opcode::Ctpop, &[above]);
670 return;
671 }
672 let missing = ahead(func, inst, Opcode::Xor, &[arg, ones], ty);
673 let less = ahead(func, inst, Opcode::Add, &[arg, ones], ty);
674 let below = ahead(func, inst, Opcode::And, &[missing, less], ty);
675 becomes(func, inst, Opcode::Ctpop, &[below]);
676}
677
678/// One set bit count, as the halving sum every bit counting routine is written as.
679///
680/// Adjacent bits are added into pairs, pairs into nibbles, nibbles into bytes, and then the bytes
681/// are added together at once by a multiply whose top byte is their sum. The first step is written
682/// as a subtraction rather than as two masks and an add, which is the usual form and is one
683/// instruction shorter: a two bit field minus its own high bit is the number of bits set in it.
684///
685/// Twelve instructions and four constants at sixty four bits, against one `popcnt`, which is the
686/// size of what #310 is worth.
687///
688/// The multiply is the last step only because the byte sums are each at most eight and there are at
689/// most eight of them, so the running total in the top byte cannot carry out of it. At eight bits
690/// there are no bytes to add and the third step is already the answer.
691fn counted(func: &mut Func, inst: Inst) {
692 let ty = produced(func, inst);
693 let Some(&arg) = func[func[inst].args].first() else { return };
694 if !countable(ty) {
695 return;
696 }
697 let width = ty.bits();
698 let pairs = ahead_const(func, inst, Imm::int(alternating(width, 1), ty), ty);
699 let two = ahead_const(func, inst, Imm::int(2, ty), ty);
700 let one = ahead_const(func, inst, Imm::int(1, ty), ty);
701 let high = ahead(func, inst, Opcode::LShr, &[arg, one], ty);
702 let odd = ahead(func, inst, Opcode::And, &[high, pairs], ty);
703 let bits = ahead(func, inst, Opcode::Sub, &[arg, odd], ty);
704
705 let quads = ahead_const(func, inst, Imm::int(alternating(width, 2), ty), ty);
706 let low = ahead(func, inst, Opcode::And, &[bits, quads], ty);
707 let up = ahead(func, inst, Opcode::LShr, &[bits, two], ty);
708 let rest = ahead(func, inst, Opcode::And, &[up, quads], ty);
709 let nibbles = ahead(func, inst, Opcode::Add, &[low, rest], ty);
710
711 let four = ahead_const(func, inst, Imm::int(4, ty), ty);
712 let bytes = ahead_const(func, inst, Imm::int(alternating(width, 4), ty), ty);
713 let folded = ahead(func, inst, Opcode::LShr, &[nibbles, four], ty);
714 let summed = ahead(func, inst, Opcode::Add, &[nibbles, folded], ty);
715 if width == 8 {
716 becomes(func, inst, Opcode::And, &[summed, bytes]);
717 return;
718 }
719 let held = ahead(func, inst, Opcode::And, &[summed, bytes], ty);
720
721 let spread = ahead_const(func, inst, Imm::int(every(width, 8, 1), ty), ty);
722 let top = ahead_const(func, inst, Imm::int(i128::from(width - 8), ty), ty);
723 let total = ahead(func, inst, Opcode::Mul, &[held, spread], ty);
724 becomes(func, inst, Opcode::LShr, &[total, top]);
725}
726
727/// Rewrites every overflow checked instruction into the arithmetic and the test that is one.
728///
729/// Six instructions and no rules, which is tamnd/rucc#309. The trade is the one `expand::bytes` and
730/// `expand::counts` above make, with one thing on top of it: these are the only instructions in the
731/// IR whose result is two things, a value and a bit, and the rule language has no way to write a
732/// term that produces two. So even on a machine whose add sets a carry flag, a rule for one of
733/// these could not name both halves of what it answers, and the rewrite would have to happen
734/// somewhere. Here is that somewhere.
735///
736/// Because the instruction goes away rather than becoming another one, the values the rest of the
737/// function read have to be pointed at what replaced them. That is what `substitute` below does,
738/// once, after every instruction has been rewritten.
739pub fn overflows(func: &mut Func) {
740 let found: Vec<Inst> =
741 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
742 let mut forward = HashMap::new();
743 for inst in found {
744 let checked = match func[inst].opcode {
745 Opcode::UAddOverflow => Checked::Add(false),
746 Opcode::SAddOverflow => Checked::Add(true),
747 Opcode::USubOverflow => Checked::Sub(false),
748 Opcode::SSubOverflow => Checked::Sub(true),
749 Opcode::UMulOverflow => Checked::Mul(false),
750 Opcode::SMulOverflow => Checked::Mul(true),
751 _ => continue,
752 };
753 overflowed(func, inst, checked, &mut forward);
754 }
755 if !forward.is_empty() {
756 substitute(func, &forward);
757 }
758}
759
760/// Which of the six an instruction is, as the arithmetic and whether the operands are signed.
761#[derive(Debug, Clone, Copy)]
762enum Checked {
763 /// An add, whose answer wraps when the exact sum needed one more bit at the top.
764 Add(bool),
765 /// A subtract.
766 Sub(bool),
767 /// A multiply, which is the expensive one because the test needs the high half of the product.
768 Mul(bool),
769}
770
771/// One overflow checked instruction, as the ordinary arithmetic and a test on the operands.
772///
773/// The value is always the ordinary instruction, because that is what the wrapped answer is. What
774/// differs between the six is how the bit is worked out.
775///
776/// The two adds and the two subtracts are one comparison each. An unsigned sum wraps exactly when
777/// it came out below either operand, and an unsigned difference wraps exactly when the left operand
778/// was below the right. A signed sum wraps exactly when both operands had the same sign and the
779/// answer had the other one, which `(a ^ v) & (b ^ v)` has the sign bit of, and a signed difference
780/// wraps exactly when the operands had different signs and the answer took the right one's, which
781/// `(a ^ b) & (a ^ v)` has the sign bit of.
782///
783/// The multiplies are the high half of the product against what the low half implies it should be.
784/// For an unsigned multiply the product fits exactly when the high half is zero, and for a signed
785/// one it fits exactly when the high half is the sign extension of the low half, which is the low
786/// half shifted right arithmetically by every bit but one.
787fn overflowed(func: &mut Func, inst: Inst, checked: Checked, forward: &mut HashMap<Value, Value>) {
788 let ty = produced(func, inst);
789 let [a, b] = func[func[inst].args] else { return };
790 if !checkable(ty) {
791 return;
792 }
793 let (value, bit) = match checked {
794 Checked::Add(signed) => {
795 let value = ahead(func, inst, Opcode::Add, &[a, b], ty);
796 let bit = if signed {
797 let left = ahead(func, inst, Opcode::Xor, &[a, value], ty);
798 let right = ahead(func, inst, Opcode::Xor, &[b, value], ty);
799 let both = ahead(func, inst, Opcode::And, &[left, right], ty);
800 negative(func, inst, both, ty)
801 } else {
802 compared(func, inst, IntPred::Ult, value, a)
803 };
804 (value, bit)
805 }
806 Checked::Sub(signed) => {
807 let value = ahead(func, inst, Opcode::Sub, &[a, b], ty);
808 let bit = if signed {
809 let apart = ahead(func, inst, Opcode::Xor, &[a, b], ty);
810 let moved = ahead(func, inst, Opcode::Xor, &[a, value], ty);
811 let both = ahead(func, inst, Opcode::And, &[apart, moved], ty);
812 negative(func, inst, both, ty)
813 } else {
814 compared(func, inst, IntPred::Ult, a, b)
815 };
816 (value, bit)
817 }
818 Checked::Mul(signed) => {
819 let value = ahead(func, inst, Opcode::Mul, &[a, b], ty);
820 let high = high_half(func, inst, a, b, signed, ty);
821 let bit = if signed {
822 let sign = ahead_const(func, inst, Imm::int(i128::from(ty.bits() - 1), ty), ty);
823 let wanted = ahead(func, inst, Opcode::AShr, &[value, sign], ty);
824 compared(func, inst, IntPred::Ne, high, wanted)
825 } else {
826 let zero = ahead_const(func, inst, Imm::int(0, ty), ty);
827 compared(func, inst, IntPred::Ne, high, zero)
828 };
829 (value, bit)
830 }
831 };
832 let mut answers = func[inst].results();
833 if let (Some(wrapped), Some(flag)) = (answers.next(), answers.next()) {
834 forward.insert(wrapped, value);
835 forward.insert(flag, bit);
836 }
837 func.remove_inst(inst);
838}
839
840/// The high half of the product of two values, at the width they are.
841///
842/// Both operands are split into halves of half the width and multiplied four ways, which is long
843/// multiplication in base two to the half width. The three partial products that reach the top are
844/// added with the carry out of the bottom ones, and every step of that fits in the width because
845/// the total is the high half of the product and that is what a high half is.
846///
847/// The whole of it is unsigned, and a signed high half is the unsigned one with a correction: a
848/// negative operand contributed the width's worth of sign bits to the unsigned product that it
849/// should not have, so the other operand is subtracted off once for each negative operand. Spreading
850/// the sign bit of each with an arithmetic shift is what turns that into a mask rather than a
851/// branch.
852///
853/// This is the expensive one. Six multiplies and a dozen other instructions at sixty four bits,
854/// against one `mul` on a machine whose multiply writes the high half into a second register. That
855/// is most of what #309 is worth and it is what makes the multiply the one to give a rule to first.
856///
857/// [`crate::wide`] calls it as well, for the carry out of the low halves of a multiply at a hundred
858/// and twenty eight bits, which is the same question asked at the width below. That pass runs
859/// before this one, so what it writes here is already at a width the machine has and nothing in
860/// this module needs to look at it again.
861pub(crate) fn high_half(
862 func: &mut Func,
863 inst: Inst,
864 a: Value,
865 b: Value,
866 signed: bool,
867 ty: Type,
868) -> Value {
869 let width = ty.bits();
870 let half = width / 2;
871 let shift = ahead_const(func, inst, Imm::int(i128::from(half), ty), ty);
872 let mask = ahead_const(func, inst, Imm::int((1i128 << half) - 1, ty), ty);
873
874 let al = ahead(func, inst, Opcode::And, &[a, mask], ty);
875 let ah = ahead(func, inst, Opcode::LShr, &[a, shift], ty);
876 let bl = ahead(func, inst, Opcode::And, &[b, mask], ty);
877 let bh = ahead(func, inst, Opcode::LShr, &[b, shift], ty);
878
879 let ll = ahead(func, inst, Opcode::Mul, &[al, bl], ty);
880 let lh = ahead(func, inst, Opcode::Mul, &[al, bh], ty);
881 let hl = ahead(func, inst, Opcode::Mul, &[ah, bl], ty);
882 let hh = ahead(func, inst, Opcode::Mul, &[ah, bh], ty);
883
884 // The carry out of the low half, which is the top of the smallest partial product plus the
885 // bottoms of the two middle ones.
886 let over = ahead(func, inst, Opcode::LShr, &[ll, shift], ty);
887 let lh_low = ahead(func, inst, Opcode::And, &[lh, mask], ty);
888 let hl_low = ahead(func, inst, Opcode::And, &[hl, mask], ty);
889 let some = ahead(func, inst, Opcode::Add, &[over, lh_low], ty);
890 let carry = ahead(func, inst, Opcode::Add, &[some, hl_low], ty);
891
892 let lh_high = ahead(func, inst, Opcode::LShr, &[lh, shift], ty);
893 let hl_high = ahead(func, inst, Opcode::LShr, &[hl, shift], ty);
894 let up = ahead(func, inst, Opcode::LShr, &[carry, shift], ty);
895 let first = ahead(func, inst, Opcode::Add, &[hh, lh_high], ty);
896 let second = ahead(func, inst, Opcode::Add, &[first, hl_high], ty);
897 let high = ahead(func, inst, Opcode::Add, &[second, up], ty);
898 if !signed {
899 return high;
900 }
901 let top = ahead_const(func, inst, Imm::int(i128::from(width - 1), ty), ty);
902 let a_sign = ahead(func, inst, Opcode::AShr, &[a, top], ty);
903 let b_sign = ahead(func, inst, Opcode::AShr, &[b, top], ty);
904 let a_owes = ahead(func, inst, Opcode::And, &[a_sign, b], ty);
905 let b_owes = ahead(func, inst, Opcode::And, &[b_sign, a], ty);
906 let once = ahead(func, inst, Opcode::Sub, &[high, a_owes], ty);
907 ahead(func, inst, Opcode::Sub, &[once, b_owes], ty)
908}
909
910/// Whether a value's sign bit is set, as a comparison against zero.
911fn negative(func: &mut Func, inst: Inst, value: Value, ty: Type) -> Value {
912 let zero = ahead_const(func, inst, Imm::int(0, ty), ty);
913 compared(func, inst, IntPred::Slt, value, zero)
914}
915
916/// A comparison written in front of an instruction, which [`ahead`] cannot write because a
917/// comparison carries its predicate where everything else carries nothing.
918fn compared(func: &mut Func, inst: Inst, pred: IntPred, lhs: Value, rhs: Value) -> Value {
919 let ty = func[lhs].ty.with_lane(Type::I1);
920 let args = func.push_values(&[lhs, rhs]);
921 let extra = Extra::IntPred(pred);
922 written(func, inst, InstData { args, extra, ..InstData::new(Opcode::ICmp) }, ty)
923}
924
925/// Points every reader of a removed instruction's results at what replaced them.
926///
927/// The arguments of each instruction and the arguments of the blocks it branches to, which between
928/// them are everything an instruction can read. Nothing chases here, the way the same walk in
929/// `rucc_opt::simplify` does, because every value this map answers with is one written above and so
930/// is never itself a key.
931fn substitute(func: &mut Func, forward: &HashMap<Value, Value>) {
932 let with = |value: Value| forward.get(&value).copied().unwrap_or(value);
933 for block in func.blocks().collect::<Vec<_>>() {
934 for inst in func.insts(block).collect::<Vec<Inst>>() {
935 let args = func[inst].args;
936 func.rewrite(args, with);
937 for call in func.successors(inst).collect::<Vec<_>>() {
938 func.rewrite(call.args, with);
939 }
940 }
941 }
942}
943
944/// Whether the arithmetic in this file works correctly at this type.
945///
946/// A whole number of bytes and a power of two of them, which every width the front end can ask about
947/// is. Anything else is left as the instruction it was, so a selector with no rule for it says so
948/// rather than the program getting a number that was counted, or checked, in the wrong shape.
949///
950/// The bit counts need it because a halving sum halves, and the overflow checks need it because
951/// splitting a value into two halves of equal width needs the width to be even and the halves to be
952/// what a shift by half of it separates.
953fn countable(ty: Type) -> bool {
954 ty.is_int()
955 && ty.is_scalar()
956 && ty.bits() >= 8
957 && ty.bits() <= 64
958 && ty.bits().is_power_of_two()
959}
960
961/// The same for an overflow check, which reaches one width further up than the bit counts do.
962///
963/// The arithmetic a check becomes is adds, subtracts, multiplies, shifts and comparisons, and
964/// `crate::wide` splits every one of those into the two registers a value that wide travels in. So
965/// the checks run before that pass and it finishes the job, where the bit counts run after it and
966/// have nothing above sixty four bits to finish. The halving argument the function above makes
967/// holds here for the same reason it holds one width down.
968fn checkable(ty: Type) -> bool {
969 countable(ty) || (ty.is_int() && ty.is_scalar() && ty.bits() == 128)
970}
971
972/// Rounds up the bytes every variable length array asks for, so that the stack pointer stays where
973/// a call can be made from.
974///
975/// The size of one is whatever the program wrote in the brackets times the size of an element, so
976/// it is any number at all, and the bytes come off the stack pointer where the declaration stands.
977/// A stack pointer moved by an odd number is one no call can be made through afterwards: the
978/// convention says a call arrives with the stack pointer on a multiple of `to`, and every argument
979/// passed on the stack, every spill of a vector register and the alignment of every local below the
980/// array is counted from there. So the number that comes off is the size rounded up, which is
981/// `(size + to - 1) & -to` and is three instructions the machine already has.
982///
983/// Here rather than in the front end because `to` is the convention's and the front end writes one
984/// IR for every target. Here rather than in [`crate::lower`] because it is arithmetic, which is the
985/// one thing a lowering rule deliberately cannot do, and that is what this module is for.
986///
987/// An array asking for more alignment than `to` asks for `to` bytes more than it needs and takes
988/// the address it wanted out of the middle of them, which `aligns` below writes. The stack pointer
989/// itself is left where a call can be made from, so nothing about a frame like that is different
990/// from any other frame that grows.
991pub fn rounds(func: &mut Func, to: u32) {
992 let found: Vec<Inst> =
993 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
994 for inst in found {
995 if func[inst].opcode != Opcode::Alloca {
996 continue;
997 }
998 let Some(&size) = func[func[inst].args].first() else { continue };
999 let ty = func[size].ty;
1000 if !ty.is_int() {
1001 continue;
1002 }
1003 let Extra::Mem(mem) = func[inst].extra else { continue };
1004 let align = func[mem].align;
1005 let up = ahead_const(func, inst, Imm::int(i128::from(to) - 1, ty), ty);
1006 let mask = ahead_const(func, inst, Imm::int(-i128::from(to), ty), ty);
1007 let over = ahead(func, inst, Opcode::Add, &[size, up], ty);
1008 let mut rounded = ahead(func, inst, Opcode::And, &[over, mask], ty);
1009 if align > to {
1010 // The whole of the alignment rather than the difference between the two, so that the
1011 // number coming off the stack pointer is still a multiple of `to` and so that the
1012 // room is there wherever the outgoing argument area below the array happens to leave
1013 // the first byte of it.
1014 let slack = ahead_const(func, inst, Imm::int(i128::from(align), ty), ty);
1015 rounded = ahead(func, inst, Opcode::Add, &[rounded, slack], ty);
1016 }
1017 let args = func.push_values(&[rounded]);
1018 func[inst].args = args;
1019 if align > to {
1020 aligns(func, inst, mem, align, to);
1021 }
1022 }
1023}
1024
1025/// Splits an over-aligned variable length array into the bytes it takes and the address it hands
1026/// out, which are not the same address any more.
1027///
1028/// The bytes come off the stack pointer, and a call leaves the stack pointer on a multiple of the
1029/// convention's alignment and no more than that, so an array wanting more has to be given an
1030/// address inside the block rather than the block's own first byte. Rounding the stack pointer
1031/// down again instead would work for the array and for nothing else: the outgoing argument area
1032/// sits below it, the rest of the frame is reached from a register at a constant distance, and a
1033/// register that has been masked is at no constant distance from where it was.
1034///
1035/// So the instruction that was the array becomes `ptr_add` of the offset that rounds the block's
1036/// address up, and a new `alloca` above it takes the block. The value the rest of the function
1037/// reads is the one the `ptr_add` writes, which is the value the `alloca` used to write, so
1038/// nothing that referred to the array has to be pointed anywhere else. The block asked for `to`
1039/// and gets it, which is the truth about it: what wanted the larger alignment is the object, and
1040/// the object is now the offset into the block rather than the block.
1041///
1042/// The offset is `-address & (align - 1)`, which is how far up the next multiple of the alignment
1043/// is, and [`rounds`] took the room for it above. It is computed at the width the size was
1044/// written at, which is `size_t` on the target, and a target whose pointers are wider than its
1045/// `size_t` would be counting the low bits of the address either way: every bit the mask keeps is
1046/// a bit below the alignment, and the alignment is smaller than the narrower of the two.
1047fn aligns(func: &mut Func, inst: Inst, mem: Idx<MemInfo>, align: u32, to: u32) {
1048 let ty = func[func[func[inst].args][0]].ty;
1049 let mut info = func[mem];
1050 info.align = to;
1051 let block = InstData {
1052 args: func[inst].args,
1053 extra: Extra::Mem(func.add_mem(info)),
1054 ..InstData::new(Opcode::Alloca)
1055 };
1056 let raw = written(func, inst, block, Type::PTR);
1057 let address = ahead(func, inst, Opcode::PtrToInt, &[raw], ty);
1058 let zero = ahead_const(func, inst, Imm::int(0, ty), ty);
1059 let below = ahead(func, inst, Opcode::Sub, &[zero, address], ty);
1060 let bits = ahead_const(func, inst, Imm::int(i128::from(align) - 1, ty), ty);
1061 let offset = ahead(func, inst, Opcode::And, &[below, bits], ty);
1062 becomes(func, inst, Opcode::PtrAdd, &[raw, offset]);
1063}
1064
1065/// The most moves a copy or a fill becomes before it is left alone for a call instead.
1066///
1067/// Thirty two, which is two hundred and fifty six bytes at a word a time and is a structure larger
1068/// than almost every one a program writes. What the number is trading is code size against a call,
1069/// and the exchange rate is a machine's rather than a language's, so the number lives here next to
1070/// the code it bounds and not in a target description that would have to be right about it for
1071/// every target at once.
1072///
1073/// It is a count of moves and not a count of bytes because that is what the cost is. A copy of
1074/// sixty four bytes between two addresses aligned to eight is eight moves and a copy of the same
1075/// sixty four bytes between two addresses aligned to one is sixty four, and the second is the
1076/// expensive one whatever the size says.
1077pub const UNROLL: usize = 32;
1078
1079/// Rewrites every bulk copy and bulk fill, into moves when that is worth it and into a call to the
1080/// runtime when it is not.
1081///
1082/// A copy of more than [`UNROLL`] moves becomes a call, and so does a fill whose byte is not a
1083/// constant, which the front end does not write today and which would need the byte spread across
1084/// a word at runtime. A `memmove` is always a call, because the two sides may overlap and a run of
1085/// moves in one direction is only right for one of the two ways they can.
1086///
1087/// `word` is how many bytes the widest move on this machine carries. Nothing here reads a target
1088/// otherwise, and a copy is the same run of loads and stores everywhere.
1089pub fn bulk(func: &mut Func, names: &mut Interner, word: u32) {
1090 let found: Vec<Inst> =
1091 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
1092 for inst in found {
1093 match func[inst].opcode {
1094 Opcode::Memcpy => copy(func, names, inst, word),
1095 Opcode::Memset => fill(func, names, inst, word),
1096 Opcode::Memmove => library(func, names, inst, Opcode::Memmove, word),
1097 _ => {}
1098 }
1099 }
1100}
1101
1102/// One `memcpy`, as a load and a store for each word of it.
1103///
1104/// Each word is read and then written before the next is read, rather than every read being built
1105/// before any write the way [`crate::varargs`] copies a list. A `memcpy` is the copy whose two
1106/// sides the front end promises do not overlap, so what is at the source when the last word is read
1107/// is what was there when the first was, and reading a word at a time costs one register where
1108/// reading all of them first would cost as many registers as the copy has words.
1109fn copy(func: &mut Func, names: &mut Interner, inst: Inst, word: u32) {
1110 let Some(bulk) = func.bulk(inst) else { return };
1111 let (into, from) = (bulk.to, bulk.with);
1112 let Extra::Mem(mem) = func[inst].extra else { return };
1113 let info = func[mem];
1114 // A plan is a list of offsets, so there is none for a copy whose length the program works out.
1115 let Some(plan) = chunks(info, word).filter(|_| bulk.length.is_none()) else {
1116 return library(func, names, inst, Opcode::Memcpy, word);
1117 };
1118 for (at, width) in plan {
1119 let ty = Type::int(width * 8);
1120 let access = MemInfo { size: u64::from(width), align: width.min(info.align), ..info };
1121 let there = stepped(func, inst, from, at);
1122 let word = read(func, inst, there, access, ty);
1123 let here = stepped(func, inst, into, at);
1124 write(func, inst, word, here, access);
1125 }
1126 func.remove_inst(inst);
1127}
1128
1129/// One `memset`, as a store of the byte spread across each word of it.
1130///
1131/// The byte is a constant, so the word it spreads into is a constant too and the spreading is done
1132/// here rather than by the program. The front end writes a `memset` for the part of an object an
1133/// initialiser did not name, where the byte is always zero, and the general case is written anyway
1134/// because the arithmetic is the same and being right about `0xff` costs nothing.
1135fn fill(func: &mut Func, names: &mut Interner, inst: Inst, word: u32) {
1136 let Some(bulk) = func.bulk(inst) else { return };
1137 let (into, byte) = (bulk.to, bulk.with);
1138 let Extra::Mem(mem) = func[inst].extra else { return };
1139 let info = func[mem];
1140 let Some(spelled) = literal(func, byte) else {
1141 return library(func, names, inst, Opcode::Memset, word);
1142 };
1143 // As in [`copy`]: a fill whose length the program works out has no list of offsets to write.
1144 let Some(plan) = chunks(info, word).filter(|_| bulk.length.is_none()) else {
1145 return library(func, names, inst, Opcode::Memset, word);
1146 };
1147 for (at, width) in plan {
1148 let ty = Type::int(width * 8);
1149 let access = MemInfo { size: u64::from(width), align: width.min(info.align), ..info };
1150 let value = ahead_const(func, inst, Imm::int(spread(spelled, width) as i128, ty), ty);
1151 let here = stepped(func, inst, into, at);
1152 write(func, inst, value, here, access);
1153 }
1154 func.remove_inst(inst);
1155}
1156
1157/// One bulk operation as a call to the routine of that name in the runtime.
1158///
1159/// This is what a copy too large to unroll becomes, and what a `memmove` and a fill with a
1160/// computed byte become whatever their size. The routine is `rucc-builtins`' on a freestanding
1161/// target and the C library's on a hosted one, and the call is the same either way because the two
1162/// have the same names and the same signatures on purpose.
1163///
1164/// The arguments are the C ones and not the IR ones. The IR holds the size beside the instruction
1165/// where C passes it, and holds a fill byte as a byte where C passes an `int`, so the size becomes
1166/// a constant in a register and the byte is widened. The value each returns is its first argument,
1167/// which nothing reads, so the call is built as returning nothing rather than as returning a
1168/// pointer nobody looks at.
1169fn library(func: &mut Func, names: &mut Interner, inst: Inst, opcode: Opcode, word: u32) {
1170 // What each of the three is called is in the capability table, since a call standing in for an
1171 // operation the machine has no instruction for is exactly what that table is a list of. A copy
1172 // and a fill answer at the size this pass gives up at and a move answers at any size, which is
1173 // the mode each is written down under there.
1174 let mode = if opcode == Opcode::Memmove { "any" } else { "big" };
1175 let Some(routine) = capability::libcall(opcode, mode) else { return };
1176 let Some(bulk) = func.bulk(inst) else { return };
1177 let (into, second) = (bulk.to, bulk.with);
1178 let Extra::Mem(mem) = func[inst].extra else { return };
1179 let size = func[mem].size;
1180
1181 // `size_t`, which is as wide as a general purpose register on every target here. Taken from
1182 // the machine rather than written as sixty four so that a thirty two bit target gets the
1183 // argument its own C library declares.
1184 let words = Type::int(word * 8);
1185 // The operand where the program worked the length out, and the payload's number otherwise.
1186 // The operand is fitted to `size_t` here rather than by the front end, because how wide that
1187 // is is a fact about the machine and this is the first pass that has been told which one.
1188 let count = match bulk.length {
1189 Some(length) => fitted(func, inst, length, words),
1190 None => ahead_const(func, inst, Imm::int(i128::from(size), words), words),
1191 };
1192 // A fill passes an `int` where the IR passes the byte itself, and the widening is a zero
1193 // extension because the routine looks at the low eight bits and nothing else.
1194 let second = if opcode == Opcode::Memset { widened(func, inst, second) } else { second };
1195
1196 let sig = func.add_signature(Signature::new().with_params(&[
1197 Type::PTR,
1198 if opcode == Opcode::Memset { Type::int(32) } else { Type::PTR },
1199 words,
1200 ]));
1201 let callee = names.intern(routine);
1202 let varargs = func.push_abis(&[]);
1203 let info = func.add_call(CallInfo { callee: Some(callee), signature: sig, varargs });
1204 let args = func.push_values(&[into, second, count]);
1205 let data = &mut func[inst];
1206 data.opcode = Opcode::Call;
1207 data.args = args;
1208 data.extra = Extra::Call(info);
1209 data.flags = data.flags.intersection(Flags::legal_on(Opcode::Call));
1210}
1211
1212/// A count brought to the width the routine takes it in, whichever side of it the value started.
1213///
1214/// The front end builds a length in whatever `size_t` it decided on, so on every target here the
1215/// two already agree and this does nothing. It is written anyway because narrowing and widening
1216/// are different instructions and picking the wrong one is the kind of mistake that shows up as a
1217/// copy of four gigabytes rather than as a build failure. The extension is unsigned, since a
1218/// length is a count of bytes and there is no negative one.
1219fn fitted(func: &mut Func, inst: Inst, value: Value, want: Type) -> Value {
1220 let ty = func[value].ty;
1221 if ty == want {
1222 return value;
1223 }
1224 let opcode = if ty.bits() < want.bits() { Opcode::ZExt } else { Opcode::Trunc };
1225 ahead(func, inst, opcode, &[value], want)
1226}
1227
1228/// A value widened to an `int`, or the value itself when it is one already.
1229fn widened(func: &mut Func, inst: Inst, value: Value) -> Value {
1230 let int = Type::int(32);
1231 let ty = func[value].ty;
1232 if ty == int {
1233 return value;
1234 }
1235 ahead(func, inst, Opcode::ZExt, &[value], int)
1236}
1237
1238/// Where each word of a block of memory starts and how wide it is, or nothing for a block that is
1239/// more words than [`UNROLL`].
1240///
1241/// The widest word is the smaller of what the machine moves at once and what the block is known to
1242/// be aligned to, because a load wider than the alignment is a fault on a machine that checks and
1243/// this pass does not know whether the one it is compiling for does. That costs a copy of a
1244/// character array a move per byte, which is exactly the copy the threshold sends to a call.
1245///
1246/// The width halves whenever what is left is narrower than it, so a block of thirteen bytes aligned
1247/// to eight is eight, four and one rather than thirteen ones. Every offset is a multiple of the
1248/// width at it, since each width divides the sum of the wider ones in front of it, which is what
1249/// lets the alignment of each access be written down as the width.
1250fn chunks(info: MemInfo, word: u32) -> Option<Vec<(u64, u32)>> {
1251 plan(info.size, info.align, word)
1252}
1253
1254/// The same, as the two numbers rather than as an access, for the one caller that has no access to
1255/// ask about.
1256///
1257/// [`crate::abi`] copies a structure passed by value into the argument area, and that copy is not a
1258/// `memcpy` in the IR: it is written straight into the machine IR, because where it goes is an
1259/// offset the placement walk gives and nothing before this pass knows it. The plan has to be the
1260/// same plan either way, so it is one function.
1261pub(crate) fn plan(size: u64, align: u32, word: u32) -> Option<Vec<(u64, u32)>> {
1262 let widest = word.min(align).max(1);
1263 if !widest.is_power_of_two() {
1264 return None;
1265 }
1266 let mut plan = Vec::new();
1267 let mut at = 0;
1268 let mut width = u64::from(widest);
1269 while at < size {
1270 while width > size - at {
1271 width /= 2;
1272 }
1273 plan.push((at, u32::try_from(width).ok()?));
1274 at += width;
1275 if plan.len() > UNROLL {
1276 return None;
1277 }
1278 }
1279 Some(plan)
1280}
1281
1282/// The byte a fill writes, when the program said which one rather than working it out.
1283fn literal(func: &Func, value: Value) -> Option<u8> {
1284 let Def::Result { inst, .. } = func[value].def else { return None };
1285 if func[inst].opcode != Opcode::IConst {
1286 return None;
1287 }
1288 let Extra::Imm(imm) = func[inst].extra else { return None };
1289 u8::try_from(func[imm].bits() & 0xff).ok()
1290}
1291
1292/// One byte repeated across a word of that many bytes, which is what a fill stores.
1293fn spread(byte: u8, width: u32) -> u64 {
1294 (0..width).fold(0, |word, at| word | u64::from(byte) << (at * 8))
1295}
1296
1297/// The address that far into a block, written in front of an instruction, or the block itself for
1298/// the word at the front of it.
1299fn stepped(func: &mut Func, inst: Inst, block: Value, at: u64) -> Value {
1300 if at == 0 {
1301 return block;
1302 }
1303 let step = ahead_const(func, inst, Imm::int(i128::from(at), Type::int(64)), Type::int(64));
1304 ahead(func, inst, Opcode::PtrAdd, &[block, step], Type::PTR)
1305}
1306
1307/// A load put in front of an instruction, and the value it reads.
1308fn read(func: &mut Func, inst: Inst, from: Value, info: MemInfo, ty: Type) -> Value {
1309 let extra = Extra::Mem(func.add_mem(info));
1310 let args = func.push_values(&[from]);
1311 written(func, inst, InstData { args, extra, ..InstData::new(Opcode::Load) }, ty)
1312}
1313
1314/// A store put in front of an instruction, which produces nothing and is only its effect.
1315fn write(func: &mut Func, inst: Inst, value: Value, into: Value, info: MemInfo) {
1316 let span = func.span(inst);
1317 let extra = Extra::Mem(func.add_mem(info));
1318 let args = func.push_values(&[value, into]);
1319 let data = InstData { args, extra, ..InstData::new(Opcode::Store) };
1320 let made = func.create_inst(data, &[], span);
1321 func.insert_before(made, inst);
1322}
1323
1324/// The width the machine converts at that holds every value of an integer of this one.
1325///
1326/// The machine converts between a float and a signed integer at thirty two bits and at sixty four
1327/// and at no other width, so a conversion anywhere else is one of those two with a widening in
1328/// front of it or a narrowing behind it. Which of the two it is, is the narrower one the values
1329/// fit in, and an unsigned integer of `bits` bits needs one more bit than that to be signed in.
1330///
1331/// `None` is a width no signed integer here holds, which is only an unsigned sixty four bit one.
1332fn holder(bits: u32, signed: bool) -> Option<u32> {
1333 match if signed { bits } else { bits + 1 } {
1334 ..=32 => Some(32),
1335 33..=64 => Some(64),
1336 _ => None,
1337 }
1338}
1339
1340/// The type of the one value an instruction produces.
1341///
1342/// Every opcode this pass touches produces exactly one, so an instruction that produces none is
1343/// one the caller has already gone wrong about and the void type says so without panicking.
1344fn produced(func: &Func, inst: Inst) -> Type {
1345 func[inst].first_result.map_or(Type::VOID, |value| func[value].ty)
1346}
1347
1348/// Puts an instruction over these operands in front of another one, and gives back its value.
1349fn ahead(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value], ty: Type) -> Value {
1350 let args = func.push_values(args);
1351 written(func, inst, InstData { args, ..InstData::new(opcode) }, ty)
1352}
1353
1354/// The same for a comparison, which carries the predicate and produces one bit.
1355fn ahead_cmp(func: &mut Func, inst: Inst, opcode: Opcode, extra: Extra, args: &[Value]) -> Value {
1356 let args = func.push_values(args);
1357 written(func, inst, InstData { args, extra, ..InstData::new(opcode) }, Type::I1)
1358}
1359
1360/// The same for a constant, which carries an immediate rather than operands.
1361fn ahead_const(func: &mut Func, inst: Inst, imm: Imm, ty: Type) -> Value {
1362 let extra = Extra::Imm(func.add_imm(imm));
1363 written(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, ty)
1364}
1365
1366/// The same for a float constant, which carries the bits of its format rather than a number.
1367fn ahead_float(func: &mut Func, inst: Inst, bits: u128, ty: Type) -> Value {
1368 let extra = Extra::Imm(func.add_imm(Imm::from_bits(bits)));
1369 written(func, inst, InstData { extra, ..InstData::new(Opcode::FConst) }, ty)
1370}
1371
1372/// Creates the instruction, puts it where those two asked, and reads its value back out.
1373fn written(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
1374 let span = func.span(inst);
1375 let made = func.create_inst(data, &[ty], span);
1376 func.insert_before(made, inst);
1377 func[made].first_result.expect("an instruction created with one result has one")
1378}
1379
1380/// Turns an instruction into a different one over different operands, in place.
1381///
1382/// The last instruction of a rewrite is the original rather than a new one, so the value the rest
1383/// of the function reads is the value it already read and nothing has to be substituted anywhere.
1384/// The type of that value does not change either, because every rewrite here ends at the type it
1385/// started at.
1386fn becomes(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value]) {
1387 let args = func.push_values(args);
1388 let data = &mut func[inst];
1389 data.opcode = opcode;
1390 data.args = args;
1391 data.extra = Extra::None;
1392 // What the program said about rounding and about not a numbers is still true of the
1393 // instructions it became, and what is no longer meaningful is dropped rather than carried.
1394 data.flags = data.flags.intersection(Flags::legal_on(opcode));
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399 use rucc_base::Interner;
1400 use rucc_ir::{Builder, Flags, Float, Func, Module, Opcode, Signature, Type};
1401 use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
1402
1403 use rucc_ir::{Extra, InstData, MemInfo, MemOrder, Restrict};
1404
1405 use super::{
1406 UNROLL, alternating, bulk, bytes, chunks, counts, every, floats, orderings, overflows,
1407 rounds, spread,
1408 };
1409
1410 fn target() -> TargetInfo {
1411 TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
1412 }
1413
1414 fn printed(func: &Func, names: &mut Interner) -> String {
1415 let module = Module::new(names.intern("sw.c"), &target());
1416 rucc_ir::print_func(&module, func, names)
1417 }
1418
1419 /// A function of one parameter and one result, with a body somebody else writes.
1420 ///
1421 /// The float rewrites are each one instruction becoming several in the middle of a block, so
1422 /// what a test needs is a block with something around the instruction rather than a shape.
1423 fn one(
1424 params: &[Type],
1425 returns: &[Type],
1426 body: impl FnOnce(&mut Builder<'_>, &[rucc_ir::Value]),
1427 ) -> (Interner, Func) {
1428 let mut names = Interner::new();
1429 let mut func = Func::new(
1430 names.intern("f"),
1431 Signature::new().with_params(params).with_returns(returns),
1432 );
1433 let entry = func.create_block();
1434 let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
1435 let mut build = Builder::new(&mut func, entry);
1436 body(&mut build, &args);
1437 (names, func)
1438 }
1439
1440 fn f64() -> Type {
1441 Type::float(Float::F64)
1442 }
1443
1444 fn f32() -> Type {
1445 Type::float(Float::F32)
1446 }
1447
1448 fn f80() -> Type {
1449 Type::float(Float::F80)
1450 }
1451
1452 /// The unsigned words both of the widest conversions are checked over.
1453 ///
1454 /// Every boundary is in the list, and so are the values either side of the ones where the two
1455 /// paths of a conversion meet, and the ones at the last width a `double` counts to.
1456 const CASES: &[u64] = &[
1457 0,
1458 1,
1459 2,
1460 0x7FFF_FFFF,
1461 0x8000_0000,
1462 0xFFFF_FFFF,
1463 0x0020_0000_0000_0000,
1464 0x0020_0000_0000_0001,
1465 0x7FFF_FFFF_FFFF_FFFF,
1466 0x8000_0000_0000_0000,
1467 0x8000_0000_0000_0001,
1468 0x8000_0000_0000_0400,
1469 0xFFFF_FFFF_FFFF_F800,
1470 0xFFFF_FFFF_FFFF_FFFF,
1471 ];
1472
1473 /// The obligation every rewrite here has: nothing after this checks the IR again.
1474 fn valid(func: &Func, names: &mut Interner) {
1475 let module = Module::new(names.intern("f.c"), &target());
1476 rucc_ir::verify_func(&module, func, names).expect("the rewrite builds valid IR");
1477 }
1478
1479 /// `double c(void) { return 1.5; }`, which is the constant nothing in the rule set can name.
1480 #[test]
1481 fn a_float_constant_becomes_the_integer_that_spells_it_and_a_reading_of_those_bits() {
1482 let (mut names, mut func) = one(&[], &[f64()], |build, _| {
1483 let k = build.fconst(f64(), 0x3ff8_0000_0000_0000);
1484 build.ret(&[k]);
1485 });
1486 floats(&mut func);
1487
1488 let text = printed(&func, &mut names);
1489 assert!(!text.contains("fconst"), "the float constant is gone: {text}");
1490 assert!(text.contains("iconst.i64 4609434218613702656"), "the bits, as an integer: {text}");
1491 assert!(text.contains("bitcast"), "read back as the float: {text}");
1492 }
1493
1494 /// The width follows the format rather than being the widest one, so a `float` constant is an
1495 /// `i32` and reaches `movd` rather than `movq`.
1496 #[test]
1497 fn a_constant_at_the_narrow_format_is_an_integer_of_the_narrow_width() {
1498 let (mut names, mut func) = one(&[], &[f32()], |build, _| {
1499 let k = build.fconst(f32(), 0x4020_0000);
1500 build.ret(&[k]);
1501 });
1502 floats(&mut func);
1503 assert!(printed(&func, &mut names).contains("iconst.i32"), "an i32, not an i64");
1504 }
1505
1506 /// `double n(double x) { return -x; }`. Flipping the sign bit is what C means and subtracting
1507 /// from zero is not, so what this asserts is the exclusive or and the mask it is given.
1508 #[test]
1509 fn a_negation_flips_the_sign_bit_and_touches_no_other() {
1510 let (mut names, mut func) = one(&[f64()], &[f64()], |build, args| {
1511 let n = build.unary(Opcode::FNeg, args[0], f64());
1512 build.ret(&[n]);
1513 });
1514 floats(&mut func);
1515
1516 let text = printed(&func, &mut names);
1517 assert!(!text.contains("fneg"), "the negation is gone: {text}");
1518 assert!(!text.contains("fsub"), "and it did not become a subtraction: {text}");
1519 assert!(text.contains("iconst.i64 -9223372036854775808"), "the sign bit alone: {text}");
1520 assert_eq!(text.matches("xor").count(), 1, "one exclusive or: {text}");
1521 assert_eq!(text.matches("bitcast").count(), 2, "there and back: {text}");
1522 }
1523
1524 /// `double u(unsigned x) { return x; }`, which is a widening and the signed conversion.
1525 #[test]
1526 fn an_unsigned_integer_becoming_a_float_widens_first_and_then_converts_as_signed() {
1527 let (mut names, mut func) = one(&[Type::int(32)], &[f64()], |build, args| {
1528 let d = build.unary(Opcode::UIToFP, args[0], f64());
1529 build.ret(&[d]);
1530 });
1531 floats(&mut func);
1532
1533 let text = printed(&func, &mut names);
1534 assert!(!text.contains("uitofp"), "the unsigned conversion is gone: {text}");
1535 assert!(text.contains("zext.i64"), "widened with zeroes: {text}");
1536 assert!(text.contains("sitofp.f64"), "converted as signed: {text}");
1537 }
1538
1539 /// `unsigned t(double x) { return x; }`, which is the same argument the other way round.
1540 #[test]
1541 fn a_float_becoming_an_unsigned_integer_converts_as_signed_first_and_then_narrows() {
1542 let (mut names, mut func) = one(&[f64()], &[Type::int(32)], |build, args| {
1543 let n = build.unary(Opcode::FPToUI, args[0], Type::int(32));
1544 build.ret(&[n]);
1545 });
1546 floats(&mut func);
1547
1548 let text = printed(&func, &mut names);
1549 assert!(!text.contains("fptoui"), "the unsigned conversion is gone: {text}");
1550 assert!(text.contains("fptosi.i64"), "converted as signed: {text}");
1551 assert!(text.contains("trunc.i32"), "and narrowed to what was asked: {text}");
1552 }
1553
1554 /// `signed char a(double x) { return (signed char)x; }`, which the front end writes as a
1555 /// conversion straight to eight bits and the machine has no instruction for at that width.
1556 #[test]
1557 fn a_conversion_narrower_than_the_machine_has_is_one_it_has_and_a_narrowing() {
1558 let (mut names, mut func) = one(&[f64()], &[Type::int(8)], |build, args| {
1559 let n = build.unary(Opcode::FPToSI, args[0], Type::int(8));
1560 build.ret(&[n]);
1561 });
1562 floats(&mut func);
1563
1564 let text = printed(&func, &mut names);
1565 assert!(text.contains("fptosi.i32"), "converted at a width there is one at: {text}");
1566 assert!(text.contains("trunc.i8"), "and narrowed to what was asked: {text}");
1567 }
1568
1569 /// The same the other way, where the widening carries the sign because the value has one.
1570 #[test]
1571 fn a_signed_integer_narrower_than_the_machine_converts_from_is_widened_with_its_sign() {
1572 let (mut names, mut func) = one(&[Type::int(8)], &[f64()], |build, args| {
1573 let d = build.unary(Opcode::SIToFP, args[0], f64());
1574 build.ret(&[d]);
1575 });
1576 floats(&mut func);
1577
1578 let text = printed(&func, &mut names);
1579 assert!(text.contains("sext.i32"), "widened with the sign and not with zeroes: {text}");
1580 assert!(!text.contains("zext"), "widened with the sign and not with zeroes: {text}");
1581 assert!(text.contains("sitofp.f64"), "converted at a width there is one at: {text}");
1582 }
1583
1584 /// The table the two of them share, which is where the whole argument about widths lives.
1585 #[test]
1586 fn the_width_a_conversion_happens_at_is_the_narrowest_one_that_holds_the_values() {
1587 use super::holder;
1588 for bits in [1, 8, 16, 32] {
1589 assert_eq!(holder(bits, true), Some(32), "a signed {bits} bit value fits in an int");
1590 }
1591 assert_eq!(holder(64, true), Some(64));
1592 for bits in [1, 8, 16, 31] {
1593 assert_eq!(holder(bits, false), Some(32), "an unsigned {bits} bit value does too");
1594 }
1595 // The one more bit an unsigned value needs is what makes these two the wider width.
1596 assert_eq!(holder(32, false), Some(64));
1597 assert_eq!(holder(64, false), None);
1598 }
1599
1600 /// Sixty four bits is where the widening argument runs out, because an unsigned value of that
1601 /// width is not a signed value of any width the IR has. Each of the two gets a rewrite of its
1602 /// own, and what both leave is the signed conversion the machine has with arithmetic around it.
1603 #[test]
1604 fn the_unsigned_conversions_at_the_widest_width_become_the_signed_one_and_a_correction() {
1605 for float in [f32(), f64()] {
1606 let (mut names, mut func) = one(&[Type::int(64)], &[float], |build, args| {
1607 let d = build.unary(Opcode::UIToFP, args[0], float);
1608 build.ret(&[d]);
1609 });
1610 floats(&mut func);
1611 let text = printed(&func, &mut names);
1612 assert!(!text.contains("uitofp"), "the unsigned conversion is gone: {text}");
1613 assert!(text.contains("sitofp"), "the signed one is what is left: {text}");
1614 // The halving that brings the value under the range the signed conversion has, and the
1615 // bit it would have thrown away put back so that the rounding is still the right one.
1616 assert!(text.contains("lshr"), "the value is halved: {text}");
1617 assert!(text.contains("fadd"), "and doubled again afterwards: {text}");
1618 valid(&func, &mut names);
1619 }
1620
1621 for float in [f32(), f64()] {
1622 let (mut names, mut func) = one(&[float], &[Type::int(64)], |build, args| {
1623 let n = build.unary(Opcode::FPToUI, args[0], Type::int(64));
1624 build.ret(&[n]);
1625 });
1626 floats(&mut func);
1627 let text = printed(&func, &mut names);
1628 assert!(!text.contains("fptoui"), "the unsigned conversion is gone: {text}");
1629 assert!(text.contains("fptosi"), "the signed one is what is left: {text}");
1630 // Half the range taken off before the conversion and put back on after it.
1631 assert!(text.contains("fsub"), "the value is brought down: {text}");
1632 assert!(text.contains("shl"), "and the top bit goes back on: {text}");
1633 valid(&func, &mut names);
1634 }
1635 }
1636
1637 /// Neither of those two has a branch in it, which is the thing about them worth a test of its
1638 /// own. Every rewrite in this pass stays inside the block it started in, so a pass that grew a
1639 /// second block would be one whose callers all have to be looked at again.
1640 #[test]
1641 fn the_widest_unsigned_conversions_are_written_without_a_branch() {
1642 let (_, mut func) = one(&[Type::int(64)], &[f64()], |build, args| {
1643 let d = build.unary(Opcode::UIToFP, args[0], f64());
1644 build.ret(&[d]);
1645 });
1646 floats(&mut func);
1647 assert_eq!(func.blocks().count(), 1, "the conversion did not split the block");
1648
1649 let (_, mut func) = one(&[f64()], &[Type::int(64)], |build, args| {
1650 let n = build.unary(Opcode::FPToUI, args[0], Type::int(64));
1651 build.ret(&[n]);
1652 });
1653 floats(&mut func);
1654 assert_eq!(func.blocks().count(), 1, "nor did the other one");
1655 }
1656
1657 /// The arithmetic of those two rewrites, done here in the same order the instructions do it.
1658 ///
1659 /// This is not the compiler running, it is the sequence written out again in a language that
1660 /// can be asked what the answer should have been. What it checks is the part that is easy to
1661 /// get wrong and impossible to see in the assembly, which is whether the halving rounds the way
1662 /// the conversion would have and whether the subtraction is exact.
1663 #[test]
1664 fn the_arithmetic_the_widest_unsigned_conversions_do_is_the_conversion() {
1665 for &x in CASES {
1666 // What `from_unsigned_word` writes, at `f64`.
1667 let mask = if (x as i64) < 0 { u64::MAX } else { 0 };
1668 let odd = (x >> 1) | (x & 1);
1669 let source = x ^ ((x ^ odd) & mask);
1670 let converted = source as i64 as f64;
1671 let addend = f64::from_bits(converted.to_bits() & mask);
1672 assert_eq!(converted + addend, x as f64, "converting {x:#x} into a double");
1673 }
1674
1675 for &x in CASES {
1676 // And what `to_unsigned_word` writes, at `f64`, over the same values read back.
1677 let d = x as f64;
1678 if d >= 18_446_744_073_709_551_616.0 {
1679 continue;
1680 }
1681 let half = f64::from_bits(0x43E0_0000_0000_0000);
1682 let mask = if d >= half { u64::MAX } else { 0 };
1683 let taken = f64::from_bits(half.to_bits() & mask);
1684 let low = (d - taken) as i64;
1685 let top = u64::from(d >= half) << 63;
1686 assert_eq!(low as u64 ^ top, d as u64, "converting {d} into an unsigned word");
1687 }
1688 }
1689
1690 /// At eighty bits both of them are a different sequence, and the thing to check is that it is
1691 /// the shorter one rather than the one above with an impossible instruction in it.
1692 ///
1693 /// What made the pair above long is the mask, and what makes a mask impossible here is that it
1694 /// is laid over the bits of the float. So no `bitcast` is the assertion that matters, and the
1695 /// rest of the list says the correction is still there and is a multiply now.
1696 #[test]
1697 fn the_unsigned_conversions_at_eighty_bits_correct_with_a_multiply_instead_of_a_mask() {
1698 let (mut names, mut func) = one(&[Type::int(64)], &[f80()], |build, args| {
1699 let d = build.unary(Opcode::UIToFP, args[0], f80());
1700 build.ret(&[d]);
1701 });
1702 floats(&mut func);
1703 let text = printed(&func, &mut names);
1704 assert!(!text.contains("uitofp"), "the unsigned conversion is gone: {text}");
1705 assert!(text.contains("sitofp.f80"), "the signed one is what is left: {text}");
1706 assert!(!text.contains("bitcast"), "and nothing reads the float as an integer: {text}");
1707 assert!(!text.contains("lshr"), "nor is the value halved, since nothing rounds: {text}");
1708 assert!(text.contains("fmul "), "the constant is taken or not by a multiply: {text}");
1709 assert!(text.contains("fadd "), "and added to what the conversion gave: {text}");
1710 assert_eq!(func.blocks().count(), 1, "the conversion did not split the block");
1711 valid(&func, &mut names);
1712
1713 let (mut names, mut func) = one(&[f80()], &[Type::int(64)], |build, args| {
1714 let n = build.unary(Opcode::FPToUI, args[0], Type::int(64));
1715 build.ret(&[n]);
1716 });
1717 floats(&mut func);
1718 let text = printed(&func, &mut names);
1719 assert!(!text.contains("fptoui"), "the unsigned conversion is gone: {text}");
1720 assert!(text.contains("fptosi.i64"), "the signed one is what is left: {text}");
1721 assert!(!text.contains("bitcast"), "and nothing reads the float as an integer: {text}");
1722 assert!(text.contains("fmul "), "the constant is taken or not by a multiply: {text}");
1723 assert!(text.contains("fsub "), "and subtracted before the conversion: {text}");
1724 assert!(text.contains("shl"), "with the top bit going back on after it: {text}");
1725 assert_eq!(func.blocks().count(), 1, "nor did the other one");
1726 valid(&func, &mut names);
1727 }
1728
1729 /// The arithmetic of those two, where the question is a different one from the question above.
1730 ///
1731 /// At the narrower widths the sequence rounds and the thing worth checking is that it rounds
1732 /// the way the conversion would have. Here nothing rounds, and that is the whole reason the
1733 /// sequence is shorter, so what is worth checking is that nothing does: a float of this format
1734 /// is exactly an integer whose odd part fits in sixty four bits, and every value either
1735 /// sequence makes is one. What would break it is a step whose operands are each a value of the
1736 /// format and whose answer is not, which is the ordinary way an exact looking sequence stops
1737 /// being one.
1738 #[test]
1739 fn nothing_in_either_conversion_at_eighty_bits_rounds() {
1740 /// Whether an integer is a value of a float with a sixty four bit significand.
1741 fn exact(v: i128) -> bool {
1742 let mag = v.unsigned_abs();
1743 mag == 0 || (mag >> mag.trailing_zeros()) < 1 << 64
1744 }
1745
1746 for &x in CASES {
1747 // What `from_unsigned_word_wide` writes, in the order it writes it.
1748 let signed = i128::from(x as i64);
1749 let addend = if (x as i64) < 0 { 1i128 << 64 } else { 0 };
1750 assert!(exact(signed), "the conversion of {x:#x} read as signed is exact");
1751 assert!(exact(addend), "and so is the constant it gets");
1752 assert!(exact(signed + addend), "and so is the sum");
1753 assert_eq!(signed + addend, i128::from(x), "converting {x:#x} into a long double");
1754 }
1755
1756 for &x in CASES {
1757 // And what `to_unsigned_word_wide` writes, over the values that conversion gives back.
1758 let value = i128::from(x);
1759 let taken = if value >= 1 << 63 { 1i128 << 63 } else { 0 };
1760 let under = value - taken;
1761 assert!(exact(under), "the subtraction that brings {x:#x} into range is exact");
1762 let top = u64::from(value >= 1 << 63) << 63;
1763 assert_eq!(under as u64 ^ top, x, "converting {x:#x} back into an unsigned word");
1764 }
1765 }
1766
1767 /// The same obligation the `switch` rewrite has, for the same reason: nothing after this
1768 /// checks the IR again and everything after it assumes what the verifier would have said.
1769 #[test]
1770 fn what_the_float_rewrites_leave_is_valid_ir() {
1771 let (mut names, mut func) = one(&[Type::int(32)], &[f64()], |build, args| {
1772 let k = build.fconst(f64(), 0x3ff8_0000_0000_0000);
1773 let d = build.unary(Opcode::UIToFP, args[0], f64());
1774 let n = build.unary(Opcode::FNeg, d, f64());
1775 let s = build.binary(Opcode::FAdd, n, k, Flags::NONE);
1776 build.ret(&[s]);
1777 });
1778 floats(&mut func);
1779 let module = Module::new(names.intern("f.c"), &target());
1780 rucc_ir::verify_func(&module, &func, &names).expect("the rewrite builds valid IR");
1781 }
1782
1783 /// Nothing else is touched, for the same reason the `switch` pass has that test: this runs
1784 /// over every function whether or not one has a float in it.
1785 #[test]
1786 fn a_function_with_no_floats_in_it_is_left_exactly_as_it_was() {
1787 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
1788 build.ret(&[args[0]]);
1789 });
1790 let before = printed(&func, &mut names);
1791 floats(&mut func);
1792 assert_eq!(printed(&func, &mut names), before);
1793 }
1794 fn access(size: u64, align: u32) -> MemInfo {
1795 MemInfo {
1796 size,
1797 align,
1798 order: MemOrder::NotAtomic,
1799 tbaa: None,
1800 owns: 0,
1801 restrict: Restrict::NONE,
1802 }
1803 }
1804
1805 /// `void c(void *to, const void *from) { *(T *)to = *(const T *)from; }` for a `T` of that
1806 /// size and alignment, which is what the front end writes for a structure assignment.
1807 fn moving(opcode: Opcode, size: u64, align: u32, byte: Option<i128>) -> (Interner, Func) {
1808 one(&[Type::PTR, Type::PTR], &[], |build, args| {
1809 let second = match byte {
1810 Some(value) => build.iconst(Type::int(8), value),
1811 None => args[1],
1812 };
1813 let mem = build.func().add_mem(access(size, align));
1814 let operands = build.func().push_values(&[args[0], second]);
1815 let data = InstData { args: operands, extra: Extra::Mem(mem), ..InstData::new(opcode) };
1816 build.inst(data, &[]);
1817 build.ret(&[]);
1818 })
1819 }
1820
1821 fn copying(size: u64, align: u32) -> (Interner, Func) {
1822 moving(Opcode::Memcpy, size, align, None)
1823 }
1824
1825 fn filling(size: u64, align: u32, byte: i128) -> (Interner, Func) {
1826 moving(Opcode::Memset, size, align, Some(byte))
1827 }
1828
1829 /// The plan a copy of that size and alignment becomes, as widths, which is what the offsets
1830 /// follow from.
1831 fn widths(size: u64, align: u32) -> Option<Vec<u32>> {
1832 Some(chunks(access(size, align), 8)?.into_iter().map(|(_, width)| width).collect())
1833 }
1834
1835 /// `struct point { int x, y; } a, b; a = b;`, which is sixteen bytes aligned to eight.
1836 #[test]
1837 fn a_copy_becomes_a_load_and_a_store_for_each_word_of_it() {
1838 let (mut names, mut func) = copying(16, 8);
1839 bulk(&mut func, &mut names, 8);
1840
1841 let text = printed(&func, &mut names);
1842 assert!(!text.contains("memcpy"), "the copy is gone: {text}");
1843 assert_eq!(text.matches("load.i64").count(), 2, "a load per word: {text}");
1844 assert_eq!(text.matches("store").count(), 2, "a store per word: {text}");
1845 assert_eq!(
1846 text.matches("ptr_add").count(),
1847 2,
1848 "no offset for the word at the front: {text}"
1849 );
1850 }
1851
1852 /// A word is as wide as the block is known to be aligned to and no wider, because a load
1853 /// wider than that faults on a machine that checks and this does not know whether the one it
1854 /// is compiling for does.
1855 #[test]
1856 fn a_word_is_as_wide_as_the_block_is_aligned_to() {
1857 assert_eq!(widths(16, 8), Some(vec![8, 8]));
1858 assert_eq!(widths(16, 4), Some(vec![4, 4, 4, 4]));
1859 assert_eq!(widths(4, 1), Some(vec![1, 1, 1, 1]));
1860 }
1861
1862 /// What is left over is narrower words rather than a run of bytes, so thirteen bytes aligned
1863 /// to eight is three moves and not six.
1864 #[test]
1865 fn what_is_left_over_is_narrower_words_and_not_a_run_of_bytes() {
1866 assert_eq!(widths(13, 8), Some(vec![8, 4, 1]));
1867 assert_eq!(widths(3, 8), Some(vec![2, 1]));
1868 assert_eq!(widths(1, 8), Some(vec![1]));
1869 }
1870
1871 /// Every offset is a multiple of the width at it, which is what lets the alignment of each
1872 /// access be written down as its width.
1873 #[test]
1874 fn every_word_starts_somewhere_it_is_aligned_for() {
1875 for (at, width) in chunks(access(13, 8), 8).expect("a plan for thirteen bytes") {
1876 assert_eq!(at % u64::from(width), 0, "{at} is a multiple of {width}");
1877 }
1878 }
1879
1880 /// `struct big b = { 0 };`, where the part the initialiser did not name is zeroed.
1881 #[test]
1882 fn a_fill_is_the_byte_spread_across_each_word() {
1883 let (mut names, mut func) = filling(16, 8, 0);
1884 bulk(&mut func, &mut names, 8);
1885
1886 let text = printed(&func, &mut names);
1887 assert!(!text.contains("memset"), "the fill is gone: {text}");
1888 assert_eq!(text.matches("store").count(), 2, "a store per word: {text}");
1889 assert!(!text.contains("load"), "a fill reads nothing: {text}");
1890 }
1891
1892 /// The spreading is arithmetic on the byte, which is the thing a rule cannot do and the
1893 /// reason this pass exists at all.
1894 #[test]
1895 fn the_byte_is_repeated_across_the_word_it_is_stored_as() {
1896 assert_eq!(spread(0, 8), 0);
1897 assert_eq!(spread(0xff, 1), 0xff);
1898 assert_eq!(spread(0xff, 4), 0xffff_ffff);
1899 assert_eq!(spread(0xab, 2), 0xabab);
1900 assert_eq!(spread(0xab, 8), 0xabab_abab_abab_abab);
1901 }
1902
1903 /// A copy larger than the threshold is a call to the runtime rather than a run of moves.
1904 #[test]
1905 fn a_copy_too_large_to_unroll_becomes_a_call_to_the_runtime() {
1906 let size = u64::try_from(UNROLL).expect("a small threshold") + 1;
1907 let (mut names, mut func) = copying(size, 1);
1908 bulk(&mut func, &mut names, 8);
1909 let text = printed(&func, &mut names);
1910 assert!(text.contains("call @memcpy"), "a call and not a bulk move: {text}");
1911
1912 // And the one word under it is moves, because the threshold counts moves rather than
1913 // bytes and the whole point of the threshold is that a small copy does not pay for a call.
1914 let (mut names, mut func) = copying(size - 1, 1);
1915 bulk(&mut func, &mut names, 8);
1916 assert!(!printed(&func, &mut names).contains("memcpy"), "one word under it is unrolled");
1917 }
1918
1919 /// The call passes what C passes, which is not what the IR holds. The size lives beside the
1920 /// instruction in the IR and travels in a register in the call.
1921 #[test]
1922 fn the_call_passes_the_size_that_the_instruction_carried_beside_it() {
1923 let size = u64::try_from(UNROLL).expect("a small threshold") + 1;
1924 let (mut names, mut func) = copying(size, 1);
1925 bulk(&mut func, &mut names, 8);
1926 let text = printed(&func, &mut names);
1927 assert!(text.contains(&format!("{size}")), "the size is an argument now: {text}");
1928 }
1929
1930 /// A `memmove` is a call whatever its size, because the two sides may overlap and a run of
1931 /// moves in one direction is right for only one of the two ways they can.
1932 #[test]
1933 fn a_move_is_a_call_however_small_it_is() {
1934 let (mut names, mut func) = moving(Opcode::Memmove, 8, 8, None);
1935 bulk(&mut func, &mut names, 8);
1936 let text = printed(&func, &mut names);
1937 assert!(text.contains("call @memmove"), "a call and not a run of moves: {text}");
1938 }
1939
1940 /// A fill whose byte the program works out rather than names. Spreading a value across a
1941 /// word at runtime is a multiply, so this is a call rather than moves however small it is.
1942 #[test]
1943 fn a_fill_whose_byte_is_not_a_constant_becomes_a_call() {
1944 let (mut names, mut func) = one(&[Type::PTR, Type::int(8)], &[], |build, args| {
1945 let mem = build.func().add_mem(access(8, 8));
1946 let operands = build.func().push_values(&[args[0], args[1]]);
1947 let data = InstData {
1948 args: operands,
1949 extra: Extra::Mem(mem),
1950 ..InstData::new(Opcode::Memset)
1951 };
1952 build.inst(data, &[]);
1953 build.ret(&[]);
1954 });
1955 bulk(&mut func, &mut names, 8);
1956 let text = printed(&func, &mut names);
1957 assert!(text.contains("call @memset"), "a call and not a run of stores: {text}");
1958 // Widened, because C passes the byte as an `int` and the IR holds it as a byte.
1959 assert!(text.contains("zext.i32"), "the byte is widened to what C passes: {text}");
1960 }
1961
1962 /// A copy or a fill whose length the program works out, which carries the count as a third
1963 /// operand and nothing beside the instruction.
1964 fn computing(opcode: Opcode, byte: Option<i128>) -> (Interner, Func) {
1965 one(&[Type::PTR, Type::PTR, Type::int(64)], &[], |build, args| {
1966 let second = match byte {
1967 Some(value) => build.iconst(Type::int(8), value),
1968 None => args[1],
1969 };
1970 let mem = build.func().add_mem(access(0, 4));
1971 let operands = build.func().push_values(&[args[0], second, args[2]]);
1972 let data = InstData { args: operands, extra: Extra::Mem(mem), ..InstData::new(opcode) };
1973 build.inst(data, &[]);
1974 build.ret(&[]);
1975 })
1976 }
1977
1978 /// However few bytes it turns out to be, because how many there are is not known here and a
1979 /// plan is a list of offsets somebody has to be able to write down.
1980 #[test]
1981 fn a_bulk_move_of_a_length_the_program_works_out_is_a_call_whatever_the_payload_says() {
1982 for (opcode, name) in
1983 [(Opcode::Memcpy, "memcpy"), (Opcode::Memmove, "memmove"), (Opcode::Memset, "memset")]
1984 {
1985 let byte = (opcode == Opcode::Memset).then_some(0);
1986 let (mut names, mut func) = computing(opcode, byte);
1987 bulk(&mut func, &mut names, 8);
1988 let text = printed(&func, &mut names);
1989 assert!(text.contains(&format!("call @{name}")), "a call and not a plan: {text}");
1990 // The count is the operand it came in with rather than a constant made here, which is
1991 // the whole difference between this and a copy whose size the payload holds.
1992 assert!(!text.contains("iconst.i64"), "no size was invented: {text}");
1993 }
1994 }
1995
1996 #[test]
1997 fn what_a_bulk_move_of_a_length_the_program_works_out_becomes_is_ir_that_verifies() {
1998 for opcode in [Opcode::Memcpy, Opcode::Memmove, Opcode::Memset] {
1999 let byte = (opcode == Opcode::Memset).then_some(0);
2000 let (mut names, mut func) = computing(opcode, byte);
2001 bulk(&mut func, &mut names, 8);
2002 valid(&func, &mut names);
2003 }
2004 }
2005
2006 /// A machine whose widest move is four bytes gets four byte words out of an eight byte block,
2007 /// however well aligned the block is.
2008 #[test]
2009 fn no_word_is_wider_than_the_machine_moves_at_once() {
2010 assert_eq!(chunks(access(8, 8), 4).map(|plan| plan.len()), Some(2));
2011 assert_eq!(chunks(access(8, 8), 8).map(|plan| plan.len()), Some(1));
2012 }
2013
2014 #[test]
2015 fn what_a_copy_becomes_is_ir_that_verifies() {
2016 let (mut names, mut func) = copying(13, 8);
2017 bulk(&mut func, &mut names, 8);
2018 let module = Module::new(names.intern("c.c"), &target());
2019 rucc_ir::verify_func(&module, &func, &names).expect("the rewrite builds valid IR");
2020 }
2021
2022 #[test]
2023 fn what_a_fill_becomes_is_ir_that_verifies() {
2024 let (mut names, mut func) = filling(13, 8, 0xff);
2025 bulk(&mut func, &mut names, 8);
2026 let module = Module::new(names.intern("f.c"), &target());
2027 rucc_ir::verify_func(&module, &func, &names).expect("the rewrite builds valid IR");
2028 }
2029
2030 #[test]
2031 fn what_a_copy_too_large_to_unroll_becomes_is_ir_that_verifies() {
2032 let size = u64::try_from(UNROLL).expect("a small threshold") + 1;
2033 let (mut names, mut func) = copying(size, 1);
2034 bulk(&mut func, &mut names, 8);
2035 let module = Module::new(names.intern("c.c"), &target());
2036 rucc_ir::verify_func(&module, &func, &names).expect("the call is valid IR");
2037 }
2038
2039 /// Nothing else is touched, for the same reason the other two passes have that test.
2040 #[test]
2041 fn a_function_with_no_bulk_move_in_it_is_left_exactly_as_it_was() {
2042 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
2043 build.ret(&[args[0]]);
2044 });
2045 let before = printed(&func, &mut names);
2046 bulk(&mut func, &mut names, 8);
2047 assert_eq!(printed(&func, &mut names), before);
2048 }
2049
2050 /// A function whose body is one byte swap of the given width, which is what a call to
2051 /// `__builtin_bswap16` and its neighbours has become by the time this pass runs.
2052 fn swapping(width: u32) -> (Interner, Func) {
2053 let ty = Type::int(width);
2054 one(&[ty], &[ty], |build, args| {
2055 let s = build.unary(Opcode::Bswap, args[0], ty);
2056 build.ret(&[s]);
2057 })
2058 }
2059
2060 /// The masks are the alternating runs the halving needs, and they are the constants a reader
2061 /// checking this against a byte swap written by hand would expect to see.
2062 ///
2063 /// At thirty two bits the first step swaps sixteen bit halves and so keeps the low half of each
2064 /// pair, which is `0x0000ffff`, and the second swaps bytes within those halves and keeps
2065 /// `0x00ff00ff`. Written as signed because that is what the IR holds an immediate as.
2066 #[test]
2067 fn the_masks_are_the_alternating_runs_of_the_group_being_swapped() {
2068 assert_eq!(alternating(32, 16), 0x0000_ffff);
2069 assert_eq!(alternating(32, 8), 0x00ff_00ff);
2070 assert_eq!(alternating(16, 8), 0x00ff);
2071 assert_eq!(alternating(64, 32), 0x0000_0000_ffff_ffff);
2072 assert_eq!(alternating(64, 16), 0x0000_ffff_0000_ffff);
2073 assert_eq!(alternating(64, 8), 0x00ff_00ff_00ff_00ff);
2074 }
2075
2076 /// The two byte swap is the one step there is, so it is one mask and one pair of shifts.
2077 #[test]
2078 fn a_two_byte_swap_is_one_exchange_of_neighbouring_bytes() {
2079 let (mut names, mut func) = swapping(16);
2080 bytes(&mut func);
2081
2082 let text = printed(&func, &mut names);
2083 assert!(!text.contains("bswap"), "the instruction is gone: {text}");
2084 assert!(text.contains("iconst.i16 255"), "the low byte of the pair: {text}");
2085 assert_eq!(text.matches("shl").count(), 1, "one shift up: {text}");
2086 assert_eq!(text.matches("lshr").count(), 1, "one shift down: {text}");
2087 assert_eq!(text.matches(" or ").count(), 1, "and the two put together: {text}");
2088 }
2089
2090 /// The wider two are the same step done again at half the group, which is what makes the count
2091 /// grow by a fixed amount per doubling rather than per byte.
2092 #[test]
2093 fn a_wider_swap_is_the_same_exchange_once_per_halving() {
2094 for (width, steps) in [(16u32, 1usize), (32, 2), (64, 3)] {
2095 let (mut names, mut func) = swapping(width);
2096 bytes(&mut func);
2097 let text = printed(&func, &mut names);
2098 assert_eq!(text.matches("shl").count(), steps, "at {width}: {text}");
2099 assert_eq!(text.matches("lshr").count(), steps, "at {width}: {text}");
2100 assert_eq!(text.matches(" and ").count(), steps * 2, "at {width}: {text}");
2101 assert_eq!(text.matches(" or ").count(), steps, "at {width}: {text}");
2102 }
2103 }
2104
2105 /// The shift counts are the group being exchanged and nothing else, so a reader can read the
2106 /// halving straight off the constants.
2107 #[test]
2108 fn the_shift_counts_are_the_group_width_halving_as_it_goes() {
2109 let (mut names, mut func) = swapping(64);
2110 bytes(&mut func);
2111 let text = printed(&func, &mut names);
2112 for count in ["iconst.i64 32", "iconst.i64 16", "iconst.i64 8"] {
2113 assert!(text.contains(count), "{count} is a step: {text}");
2114 }
2115 }
2116
2117 /// The rewrite has to leave a function the verifier still accepts, for the reason the switch
2118 /// rewrite has the same test: nothing rechecks it.
2119 #[test]
2120 fn what_a_byte_swap_becomes_is_ir_that_verifies() {
2121 let (mut names, mut func) = swapping(32);
2122 bytes(&mut func);
2123 let module = Module::new(names.intern("b.c"), &target());
2124 rucc_ir::verify_func(&module, &func, &names).expect("the rewrite builds valid IR");
2125 }
2126
2127 /// Nothing else is touched, which matters because this runs over every function in the program
2128 /// and nearly none of them reverses any bytes.
2129 #[test]
2130 fn a_function_with_no_byte_swap_in_it_is_left_exactly_as_it_was() {
2131 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
2132 build.ret(&[args[0]]);
2133 });
2134 let before = printed(&func, &mut names);
2135 bytes(&mut func);
2136 assert_eq!(printed(&func, &mut names), before);
2137 }
2138
2139 /// A function whose body is one bit count of the given opcode and width.
2140 fn counting(op: Opcode, width: u32) -> (Interner, Func) {
2141 let ty = Type::int(width);
2142 one(&[ty], &[ty], |build, args| {
2143 let c = build.unary(op, args[0], ty);
2144 build.ret(&[c]);
2145 })
2146 }
2147
2148 /// The masks the halving sum needs, which are the ones any bit counting routine is written with
2149 /// and are worth being able to read off against one.
2150 #[test]
2151 fn the_counting_masks_are_the_ones_the_halving_sum_is_written_with() {
2152 assert_eq!(alternating(32, 1), 0x5555_5555);
2153 assert_eq!(alternating(32, 2), 0x3333_3333);
2154 assert_eq!(alternating(32, 4), 0x0f0f_0f0f);
2155 assert_eq!(every(32, 8, 1), 0x0101_0101);
2156 assert_eq!(every(64, 8, 1), 0x0101_0101_0101_0101);
2157 }
2158
2159 /// The set bit count is arithmetic and the multiply is what adds the bytes together, which is
2160 /// the step a reader is most likely to want to check.
2161 #[test]
2162 fn a_set_bit_count_is_the_halving_sum_and_a_multiply_that_adds_the_bytes() {
2163 let (mut names, mut func) = counting(Opcode::Ctpop, 32);
2164 counts(&mut func);
2165
2166 let text = printed(&func, &mut names);
2167 assert!(!text.contains("ctpop"), "the instruction is gone: {text}");
2168 assert!(text.contains("iconst.i32 1431655765"), "the pairs mask: {text}");
2169 assert!(text.contains("iconst.i32 858993459"), "the nibbles mask: {text}");
2170 assert!(text.contains("iconst.i32 252645135"), "the bytes mask: {text}");
2171 assert_eq!(text.matches(" mul ").count(), 1, "one multiply: {text}");
2172 assert!(text.contains("iconst.i32 24"), "and the top byte is the answer: {text}");
2173 }
2174
2175 /// At eight bits there are no bytes left to add, so the multiply is not written at all.
2176 #[test]
2177 fn a_count_of_one_byte_stops_before_the_multiply() {
2178 let (mut names, mut func) = counting(Opcode::Ctpop, 8);
2179 counts(&mut func);
2180 let text = printed(&func, &mut names);
2181 assert!(!text.contains("ctpop"), "{text}");
2182 assert!(!text.contains(" mul "), "nothing to add together: {text}");
2183 }
2184
2185 /// A leading zero count smears every set bit downwards and counts what is left unset above it,
2186 /// which is one shift and one or per doubling and then the count.
2187 #[test]
2188 fn a_leading_zero_count_smears_the_value_down_and_counts_the_complement() {
2189 let (mut names, mut func) = counting(Opcode::Ctlz, 32);
2190 counts(&mut func);
2191
2192 let text = printed(&func, &mut names);
2193 assert!(!text.contains("ctlz"), "the instruction is gone: {text}");
2194 assert!(!text.contains("ctpop"), "and so is the count it became: {text}");
2195 for by in ["iconst.i32 1", "iconst.i32 2", "iconst.i32 4", "iconst.i32 8", "iconst.i32 16"]
2196 {
2197 assert!(text.contains(by), "{by} is a smearing step: {text}");
2198 }
2199 assert_eq!(text.matches(" xor ").count(), 1, "one complement: {text}");
2200 }
2201
2202 /// A trailing zero count is the bits below the lowest set one, which is a mask and no smearing.
2203 #[test]
2204 fn a_trailing_zero_count_masks_the_bits_below_the_lowest_set_one() {
2205 let (mut names, mut func) = counting(Opcode::Cttz, 32);
2206 counts(&mut func);
2207
2208 let text = printed(&func, &mut names);
2209 assert!(!text.contains("cttz"), "the instruction is gone: {text}");
2210 assert!(!text.contains("ctpop"), "and so is the count it became: {text}");
2211 assert!(text.contains("iconst.i32 -1"), "the complement and the decrement: {text}");
2212 assert_eq!(text.matches(" xor ").count(), 1, "one complement: {text}");
2213 // Far fewer instructions than the leading count, because there is no smearing to do.
2214 assert!(text.matches(" or ").count() <= 1, "no smearing run: {text}");
2215 }
2216
2217 /// The rewrites have to leave a function the verifier still accepts, at every width and for all
2218 /// three, because nothing rechecks what comes out of here.
2219 #[test]
2220 fn what_a_bit_count_becomes_is_ir_that_verifies() {
2221 for op in [Opcode::Ctpop, Opcode::Ctlz, Opcode::Cttz] {
2222 for width in [8u32, 16, 32, 64] {
2223 let (mut names, mut func) = counting(op, width);
2224 counts(&mut func);
2225 let module = Module::new(names.intern("c.c"), &target());
2226 rucc_ir::verify_func(&module, &func, &names)
2227 .unwrap_or_else(|e| panic!("{op:?} at {width}: {e:?}"));
2228 }
2229 }
2230 }
2231
2232 /// A width the arithmetic is not written for is left as the instruction it was, so a selector
2233 /// with no rule for it says so rather than the program getting a number counted in the wrong
2234 /// shape.
2235 #[test]
2236 fn a_width_the_halving_sum_is_not_written_for_is_left_alone() {
2237 let (mut names, mut func) = counting(Opcode::Ctpop, 24);
2238 counts(&mut func);
2239 assert!(printed(&func, &mut names).contains("ctpop"), "left as it was");
2240 }
2241
2242 /// Nothing else is touched, for the same reason the other passes have that test.
2243 #[test]
2244 fn a_function_with_no_bit_count_in_it_is_left_exactly_as_it_was() {
2245 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
2246 build.ret(&[args[0]]);
2247 });
2248 let before = printed(&func, &mut names);
2249 counts(&mut func);
2250 assert_eq!(printed(&func, &mut names), before);
2251 }
2252
2253 /// One overflow checked instruction whose value and whose flag are both returned, so that the
2254 /// substitution has two readers to find rather than none.
2255 fn checking(op: Opcode, width: u32) -> (Interner, Func) {
2256 let ty = Type::int(width);
2257 let bit = ty.with_lane(Type::I1);
2258 one(&[ty, ty], &[ty, bit], |build, args| {
2259 let (value, flag) = build.checked(op, args[0], args[1]);
2260 build.ret(&[value, flag]);
2261 })
2262 }
2263
2264 /// An unsigned add wraps exactly when the sum came out below an operand, which is one
2265 /// comparison and no arithmetic on the sign bits.
2266 #[test]
2267 fn a_checked_unsigned_add_becomes_an_add_and_one_comparison() {
2268 let (mut names, mut func) = checking(Opcode::UAddOverflow, 32);
2269 overflows(&mut func);
2270
2271 let text = printed(&func, &mut names);
2272 assert!(!text.contains("uadd_overflow"), "the instruction is gone: {text}");
2273 assert_eq!(text.matches(" add ").count(), 1, "one add: {text}");
2274 assert_eq!(text.matches("icmp ult").count(), 1, "and one comparison: {text}");
2275 assert!(!text.contains(" xor "), "nothing about sign bits: {text}");
2276 }
2277
2278 /// A signed add wraps exactly when the operands agreed in sign and the answer did not, which is
2279 /// the sign bit of `(a ^ v) & (b ^ v)`.
2280 #[test]
2281 fn a_checked_signed_add_becomes_an_add_and_the_sign_bit_of_two_exclusive_ors() {
2282 let (mut names, mut func) = checking(Opcode::SAddOverflow, 32);
2283 overflows(&mut func);
2284
2285 let text = printed(&func, &mut names);
2286 assert!(!text.contains("sadd_overflow"), "the instruction is gone: {text}");
2287 assert_eq!(text.matches(" add ").count(), 1, "one add: {text}");
2288 assert_eq!(text.matches(" xor ").count(), 2, "the answer against each operand: {text}");
2289 assert_eq!(text.matches(" and ").count(), 1, "both at once: {text}");
2290 assert!(text.contains("icmp slt"), "and its sign bit: {text}");
2291 }
2292
2293 /// An unsigned subtract wraps exactly when the left operand was below the right, which does not
2294 /// need the answer at all.
2295 #[test]
2296 fn a_checked_unsigned_subtract_compares_the_operands_and_not_the_answer() {
2297 let (mut names, mut func) = checking(Opcode::USubOverflow, 64);
2298 overflows(&mut func);
2299
2300 let text = printed(&func, &mut names);
2301 assert!(!text.contains("usub_overflow"), "the instruction is gone: {text}");
2302 assert_eq!(text.matches(" sub ").count(), 1, "one subtract: {text}");
2303 assert!(text.contains("icmp ult %0, %1"), "the operands, in order: {text}");
2304 }
2305
2306 /// A checked multiply is the ordinary multiply and the high half of the product, which is four
2307 /// multiplies of the halves and the carry between them.
2308 ///
2309 /// This is the expensive one and it is what tamnd/rucc#309 is mostly worth: a machine whose
2310 /// multiply writes the high half into a second register does the whole of it in one
2311 /// instruction.
2312 #[test]
2313 fn a_checked_multiply_becomes_a_multiply_and_the_high_half_of_the_product() {
2314 let (mut names, mut func) = checking(Opcode::UMulOverflow, 64);
2315 overflows(&mut func);
2316
2317 let text = printed(&func, &mut names);
2318 assert!(!text.contains("umul_overflow"), "the instruction is gone: {text}");
2319 assert_eq!(text.matches(" mul ").count(), 5, "the answer and the four halves: {text}");
2320 assert!(text.contains("iconst.i64 32"), "split at half the width: {text}");
2321 assert!(text.contains("iconst.i64 4294967295"), "and masked to it: {text}");
2322 assert!(text.contains("icmp ne"), "the high half against zero: {text}");
2323 assert!(!text.contains("ashr"), "and nothing corrected for sign: {text}");
2324 }
2325
2326 /// The signed multiply is the unsigned one with the sign correction on top, and the test is
2327 /// against the sign extension of the low half rather than against zero.
2328 #[test]
2329 fn a_checked_signed_multiply_corrects_the_high_half_for_each_negative_operand() {
2330 let (mut names, mut func) = checking(Opcode::SMulOverflow, 64);
2331 overflows(&mut func);
2332
2333 let text = printed(&func, &mut names);
2334 assert!(!text.contains("smul_overflow"), "the instruction is gone: {text}");
2335 assert_eq!(
2336 text.matches(" ashr ").count(),
2337 3,
2338 "each operand's sign, and the answer: {text}"
2339 );
2340 assert!(text.contains("iconst.i64 63"), "spread from the top bit: {text}");
2341 assert_eq!(text.matches(" sub ").count(), 2, "one correction per operand: {text}");
2342 }
2343
2344 /// Both results have to reach their readers, which is the one thing this pass has to do that
2345 /// the others do not: the instruction goes away rather than becoming another one, so nothing is
2346 /// left holding the values the rest of the function was reading.
2347 #[test]
2348 fn both_results_are_substituted_into_whoever_was_reading_them() {
2349 let (mut names, mut func) = checking(Opcode::SAddOverflow, 32);
2350 overflows(&mut func);
2351
2352 // The whole of it, because what this is checking is that nothing is left pointing at the
2353 // two values the removed instruction used to define. The return names the add and the
2354 // comparison, which are what replaced them.
2355 let text = printed(&func, &mut names);
2356 assert_eq!(
2357 text,
2358 concat!(
2359 "func @f(i32, i32) -> (i32, i1), linkage(external) {\n",
2360 "block0(%0: i32, %1: i32):\n",
2361 " %2 = add %0, %1\n",
2362 " %3 = xor %0, %2\n",
2363 " %4 = xor %1, %2\n",
2364 " %5 = and %3, %4\n",
2365 " %6 = iconst.i32 0\n",
2366 " %7 = icmp slt %5, %6\n",
2367 " return %2, %7\n",
2368 "}\n",
2369 ),
2370 );
2371 }
2372
2373 /// The rewrites have to leave a function the verifier still accepts, for all six and at every
2374 /// width, because nothing rechecks what comes out of here.
2375 #[test]
2376 fn what_an_overflow_check_becomes_is_ir_that_verifies() {
2377 let all = [
2378 Opcode::UAddOverflow,
2379 Opcode::SAddOverflow,
2380 Opcode::USubOverflow,
2381 Opcode::SSubOverflow,
2382 Opcode::UMulOverflow,
2383 Opcode::SMulOverflow,
2384 ];
2385 for op in all {
2386 for width in [8u32, 16, 32, 64, 128] {
2387 let (mut names, mut func) = checking(op, width);
2388 overflows(&mut func);
2389 let module = Module::new(names.intern("c.c"), &target());
2390 rucc_ir::verify_func(&module, &func, &names)
2391 .unwrap_or_else(|e| panic!("{op:?} at {width}: {e:?}"));
2392 }
2393 }
2394 }
2395
2396 /// A width the arithmetic is not written for is left as the instruction it was, for the same
2397 /// reason the bit counts leave one: a selector with no rule for it says so, which is better
2398 /// than an answer checked in the wrong shape.
2399 #[test]
2400 fn a_width_the_split_is_not_written_for_is_left_alone() {
2401 let (mut names, mut func) = checking(Opcode::UMulOverflow, 24);
2402 overflows(&mut func);
2403 assert!(printed(&func, &mut names).contains("umul_overflow"), "left as it was");
2404 }
2405
2406 /// A check at the width no register holds is rewritten here and split into halves after.
2407 ///
2408 /// This pass runs above `crate::wide` for exactly this, because an overflow check is the one
2409 /// instruction whose result is two things and that pass has no answer for one. What it leaves
2410 /// behind is arithmetic and a comparison, which are both things the splitting understands, so
2411 /// the check reaches the machine as instructions the machine has.
2412 #[test]
2413 fn a_check_at_the_width_no_register_holds_is_rewritten_here() {
2414 let (mut names, mut func) = checking(Opcode::UAddOverflow, 128);
2415 overflows(&mut func);
2416 let text = printed(&func, &mut names);
2417 assert!(!text.contains("uadd_overflow"), "the check is gone: {text}");
2418 assert!(text.contains(" = add "), "into the arithmetic it is: {text}");
2419 assert!(text.contains("icmp ult"), "and the test that says it wrapped: {text}");
2420 }
2421
2422 /// Nothing else is touched, for the same reason the other passes have that test.
2423 #[test]
2424 fn a_function_with_no_overflow_check_in_it_is_left_exactly_as_it_was() {
2425 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
2426 build.ret(&[args[0]]);
2427 });
2428 let before = printed(&func, &mut names);
2429 overflows(&mut func);
2430 assert_eq!(printed(&func, &mut names), before);
2431 }
2432
2433 /// `T x = *p;` with an ordering on it, which is what `__atomic_load_n` becomes.
2434 fn reading(ty: Type, align: u32, order: MemOrder) -> (Interner, Func) {
2435 one(&[Type::PTR], &[ty], |build, args| {
2436 let info = MemInfo { order, ..access(0, align) };
2437 let value = build.atomic_load(ty, args[0], info, Flags::NONE);
2438 build.ret(&[value]);
2439 })
2440 }
2441
2442 /// `*p = x;` with an ordering on it, which is what `__atomic_store_n` becomes.
2443 fn writing(ty: Type, align: u32, order: MemOrder) -> (Interner, Func) {
2444 one(&[Type::PTR, ty], &[], |build, args| {
2445 let info = MemInfo { order, ..access(0, align) };
2446 build.atomic_store(args[1], args[0], info, Flags::NONE);
2447 build.ret(&[]);
2448 })
2449 }
2450
2451 /// Every ordered access below the strongest store is the plain instruction on this machine,
2452 /// and the ordering comes off it when it is.
2453 ///
2454 /// The ordering coming off is not cosmetic: the verifier refuses an ordering on a plain access,
2455 /// because a plain load may be moved, duplicated and dropped and an ordering left on one would
2456 /// be a claim nothing downstream honours.
2457 #[test]
2458 fn an_ordered_access_becomes_the_plain_one_this_machine_already_orders() {
2459 for order in [MemOrder::Relaxed, MemOrder::Acquire, MemOrder::SeqCst] {
2460 let (mut names, mut func) = reading(Type::int(32), 4, order);
2461 orderings(&mut func, 8);
2462 let text = printed(&func, &mut names);
2463 assert!(text.contains("load.i32"), "{order:?}: {text}");
2464 assert!(!text.contains("atomic_load"), "{order:?}: {text}");
2465 assert!(!text.contains(order.name()), "the ordering came off: {text}");
2466 }
2467
2468 for order in [MemOrder::Relaxed, MemOrder::Release] {
2469 let (mut names, mut func) = writing(Type::int(32), 4, order);
2470 orderings(&mut func, 8);
2471 let text = printed(&func, &mut names);
2472 assert!(text.contains("store %1 -> %0"), "{order:?}: {text}");
2473 assert!(!text.contains("atomic_store"), "{order:?}: {text}");
2474 assert!(!text.contains("fence"), "{order:?} costs nothing here: {text}");
2475 }
2476 }
2477
2478 /// The strongest store is the plain store and a barrier behind it, in that order.
2479 ///
2480 /// It is the one thing total store order does not give away: a store followed by a load of
2481 /// another address may be seen the other way round, and sequential consistency is exactly the
2482 /// ordering that forbids it.
2483 #[test]
2484 fn the_strongest_store_keeps_a_barrier_behind_it() {
2485 let (mut names, mut func) = writing(Type::int(32), 4, MemOrder::SeqCst);
2486 orderings(&mut func, 8);
2487 let text = printed(&func, &mut names);
2488 let (before, after) = text.split_once("fence seq_cst").expect("a barrier");
2489 assert!(before.contains("store %1 -> %0"), "the store comes first: {text}");
2490 assert!(!after.contains("store"), "and nothing is between them: {text}");
2491 assert!(!text.contains("atomic_store"), "{text}");
2492 }
2493
2494 /// A barrier the program wrote is left for `crate::lower`, which is where a target says what
2495 /// an ordering costs.
2496 #[test]
2497 fn a_barrier_is_left_for_the_place_that_knows_what_one_costs() {
2498 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
2499 let (mut names, mut func) = one(&[], &[], |build, _| {
2500 build.fence(order);
2501 build.ret(&[]);
2502 });
2503 let before = printed(&func, &mut names);
2504 orderings(&mut func, 8);
2505 assert_eq!(printed(&func, &mut names), before, "{order:?}");
2506 }
2507 }
2508
2509 /// An access the machine cannot do in one go is left as the opcode it was, which is a refusal
2510 /// naming the instruction rather than an answer that is not atomic at all.
2511 ///
2512 /// Two ways it happens: wider than a word, and narrower than a word but at an address the
2513 /// program said less about than the width. Both are `__atomic_is_lock_free` answering no.
2514 #[test]
2515 fn an_access_this_machine_cannot_do_in_one_go_is_left_alone() {
2516 for (ty, align) in [(Type::int(128), 16), (Type::int(64), 4)] {
2517 let (mut names, mut func) = reading(ty, align, MemOrder::SeqCst);
2518 orderings(&mut func, 8);
2519 assert!(printed(&func, &mut names).contains("atomic_load"), "left as it was");
2520 }
2521 }
2522
2523 /// What comes out is IR the verifier takes, which is the check that matters most here: the
2524 /// ordering has to be gone from a plain access or this pass has built something illegal.
2525 #[test]
2526 fn what_the_ordered_accesses_become_verifies() {
2527 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
2528 for (mut names, mut func) in
2529 [reading(Type::int(32), 4, order), writing(Type::int(32), 4, order)]
2530 {
2531 if !order.is_valid_for_load() && !order.is_valid_for_store() {
2532 continue;
2533 }
2534 orderings(&mut func, 8);
2535 let module = Module::new(names.intern("a.c"), &target());
2536 rucc_ir::verify_func(&module, &func, &names)
2537 .unwrap_or_else(|e| panic!("{order:?}: {e:?}"));
2538 }
2539 }
2540 }
2541
2542 /// Nothing else is touched, for the same reason the other passes have that test.
2543 #[test]
2544 fn a_function_with_no_ordered_access_in_it_is_left_exactly_as_it_was() {
2545 let (mut names, mut func) = one(&[Type::int(32)], &[Type::int(32)], |build, args| {
2546 build.ret(&[args[0]]);
2547 });
2548 let before = printed(&func, &mut names);
2549 orderings(&mut func, 8);
2550 assert_eq!(printed(&func, &mut names), before);
2551 }
2552
2553 /// A variable length array, built the way the front end builds one.
2554 fn growing(build: &mut Builder<'_>, size: rucc_ir::Value, align: u32) -> rucc_ir::Value {
2555 let info = MemInfo {
2556 size: 0,
2557 align,
2558 order: MemOrder::NotAtomic,
2559 tbaa: None,
2560 owns: 0,
2561 restrict: Restrict::default(),
2562 };
2563 let mem = build.func().add_mem(info);
2564 let args = build.func().push_values(&[size]);
2565 build.value(
2566 InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
2567 Type::PTR,
2568 )
2569 }
2570
2571 /// The bytes an array asks for are rounded up to what a call leaves the stack pointer on.
2572 #[test]
2573 fn the_bytes_a_variable_length_array_takes_are_a_multiple_of_the_stack_alignment() {
2574 let (mut names, mut func) = one(&[Type::int(64)], &[Type::PTR], |build, args| {
2575 let slot = growing(build, args[0], 8);
2576 build.ret(&[slot]);
2577 });
2578 rounds(&mut func, 16);
2579 let text = printed(&func, &mut names);
2580 assert!(text.contains("%3 = add %0, %1"), "{text}");
2581 assert!(text.contains("%4 = and %3, %2"), "{text}");
2582 assert!(text.contains("%5 = alloca %4, align 8"), "{text}");
2583 // One array and one allocation of it, since nothing here wanted an address the stack
2584 // pointer does not already land on.
2585 assert_eq!(text.matches("alloca").count(), 1, "{text}");
2586 assert!(!text.contains("ptr_add"), "{text}");
2587 }
2588
2589 /// One that wants more alignment than that takes the room for it and lands inside it.
2590 ///
2591 /// The instruction the rest of the function reads is the `ptr_add`, which is the instruction
2592 /// the array was, so the value it writes is the value everything already held. What the
2593 /// `alloca` above it asks for is the convention's alignment, which is the truth about the
2594 /// block: the object wanted thirty two and the object is the offset into the block.
2595 #[test]
2596 fn a_variable_length_array_wanting_more_alignment_is_placed_inside_the_bytes_it_took() {
2597 let (mut names, mut func) = one(&[Type::int(64)], &[Type::PTR], |build, args| {
2598 let slot = growing(build, args[0], 32);
2599 build.ret(&[slot]);
2600 });
2601 rounds(&mut func, 16);
2602 let text = printed(&func, &mut names);
2603 // The size, rounded up and then given the whole of the alignment as room to move in.
2604 assert!(text.contains("%5 = iconst.i64 32"), "{text}");
2605 assert!(text.contains("%6 = add %4, %5"), "{text}");
2606 // The offset, which is how far above the block the next multiple of thirty two is.
2607 assert!(text.contains("ptrtoint"), "{text}");
2608 assert!(text.contains("%11 = iconst.i64 31"), "{text}");
2609 assert!(text.contains("%10 = sub %9, %8"), "{text}");
2610 assert!(text.contains("%12 = and %10, %11"), "{text}");
2611 // The block itself asks for what a call leaves the stack pointer on and no more.
2612 assert!(text.contains("%7 = alloca %6, align 16"), "{text}");
2613 // The last instruction of the rewrite is the array itself, so the value the function
2614 // returns is the value it already returned.
2615 assert!(text.contains("%13 = ptr_add %7, %12"), "{text}");
2616 assert!(text.contains("return %13"), "{text}");
2617 }
2618}