softfpu 0.2.0

Correctly rounded software floating point with x87 and SSE semantics, including x87 transcendentals that match Intel hardware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Binary32, binary64 and x87 80-bit encodings. Each format classifies
// operands, normalizes finite nonzero magnitudes, and encodes normal
// numbers, signed zeros and infinities.

/// An IEEE binary32 bit pattern. The sign occupies bit 31, the biased
/// exponent bits 23–30 (bias 127), and the fraction bits 0–22. Finite
/// normal values have 24 significant bits. Equality compares encodings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Single(pub u32);

/// An IEEE binary64 bit pattern. The sign occupies bit 63, the biased
/// exponent bits 52–62 (bias 1023), and the fraction bits 0–51. Finite
/// normal values have 53 significant bits. Equality compares encodings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Double(pub u64);

/// An x87 extended bit pattern with an explicit integer bit. Equality compares
/// all 80 bits. The byte conversions preserve every encoding. Arithmetic takes
/// canonical operands. A zero exponent with the integer bit set is a
/// pseudo-denormal. Normalize it to exponent field one before arithmetic.
/// An all-ones exponent with the integer bit set denotes infinity (zero
/// fraction) or NaN. Handle unsupported encodings in the instruction caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Extended {
    /// Sign in bit 15 and biased exponent in bits 0 through 14 (bias 16383).
    pub sign_exponent: u16,
    /// The explicit integer bit at bit 63 and the 63 fraction bits below it.
    pub significand: u64,
}

impl Single {
    /// Returns the sign bit, including for zero and NaN.
    #[inline]
    pub fn negative(self) -> bool {
        self.0 >> 31 != 0
    }

    /// Returns the raw biased exponent field.
    #[inline]
    pub fn exponent(self) -> i32 {
        ((self.0 >> 23) & 0xFF) as i32
    }

    /// Returns the unsigned fraction field.
    #[inline]
    pub fn fraction(self) -> u32 {
        self.0 & 0x7F_FFFF
    }

    /// Returns true for a NaN encoding.
    #[inline]
    pub fn is_nan(self) -> bool {
        self.0 & 0x7FFF_FFFF > 0x7F80_0000
    }
}

impl Double {
    /// Returns the sign bit, including for zero and NaN.
    #[inline]
    pub fn negative(self) -> bool {
        self.0 >> 63 != 0
    }

    /// Returns the raw biased exponent field.
    #[inline]
    pub fn exponent(self) -> i32 {
        ((self.0 >> 52) & 0x7FF) as i32
    }

    /// Returns the unsigned fraction field.
    #[inline]
    pub fn fraction(self) -> u64 {
        self.0 & 0xF_FFFF_FFFF_FFFF
    }

    /// Returns true for a NaN encoding.
    #[inline]
    pub fn is_nan(self) -> bool {
        self.0 & 0x7FFF_FFFF_FFFF_FFFF > 0x7FF0_0000_0000_0000
    }
}

impl Extended {
    /// Builds a value from its ten-byte little-endian memory form. The
    /// significand comes first, then the sign and exponent. The conversion
    /// round-trips every encoding.
    #[inline]
    pub fn from_bytes(bytes: [u8; 10]) -> Extended {
        let [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9] = bytes;
        Extended {
            sign_exponent: u16::from_le_bytes([b8, b9]),
            significand: u64::from_le_bytes([b0, b1, b2, b3, b4, b5, b6, b7]),
        }
    }

    /// Returns the ten-byte little-endian encoding, with the significand first.
    #[inline]
    pub fn to_bytes(self) -> [u8; 10] {
        let [b0, b1, b2, b3, b4, b5, b6, b7] = self.significand.to_le_bytes();
        let [b8, b9] = self.sign_exponent.to_le_bytes();
        [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9]
    }

    // The exponent bias.
    pub(crate) const BIAS: i32 = 16383;

    // The exponent field's bits in `sign_exponent`. The same value is the
    // field of an infinity or a NaN.
    pub(crate) const EXPONENT_MASK: u16 = 0x7FFF;

    // The exponents of the smallest and largest normal numbers.
    pub(crate) const MIN_EXPONENT: i32 = -16382;
    pub(crate) const MAX_EXPONENT: i32 = 16383;

    /// Returns the sign bit, including for zero and NaN.
    #[inline]
    pub fn negative(self) -> bool {
        self.sign_exponent >> 15 != 0
    }

    /// Returns the raw biased exponent field.
    #[inline]
    pub fn exponent(self) -> i32 {
        i32::from(self.sign_exponent & Extended::EXPONENT_MASK)
    }

    /// Returns true for either canonical signed zero.
    #[inline]
    pub fn is_zero(self) -> bool {
        self.sign_exponent & Extended::EXPONENT_MASK == 0 && self.significand == 0
    }

    /// Returns true for a NaN encoding.
    #[inline]
    pub fn is_nan(self) -> bool {
        self.sign_exponent & Extended::EXPONENT_MASK == Extended::EXPONENT_MASK
            && self.significand > 1 << 63
    }

    /// Returns true for either canonical infinity.
    #[inline]
    pub fn is_infinity(self) -> bool {
        self.sign_exponent & Extended::EXPONENT_MASK == Extended::EXPONENT_MASK
            && self.significand == 1 << 63
    }

    /// Encodes zero with the given sign.
    #[inline]
    pub fn zero(negative: bool) -> Extended {
        <Extended as Format>::zero(negative)
    }

    /// Encodes infinity with the given sign.
    #[inline]
    pub fn infinity(negative: bool) -> Extended {
        <Extended as Format>::infinity(negative)
    }

    /// Returns `None` when the significand is zero. For finite nonzero inputs,
    /// returns the equivalent biased exponent and significand with bit 63 set.
    /// A denormal can have a normalized biased exponent below one.
    /// [`Unrounded::new`](crate::Unrounded::new) takes an unbiased exponent,
    /// so subtract the bias of 16,383 before passing this one to it.
    #[inline]
    pub fn normalized(self) -> Option<(i32, u64)> {
        if self.significand == 0 {
            return None;
        }
        let shift = self.significand.leading_zeros();
        Some((
            self.exponent().max(1) - shift as i32,
            self.significand << shift,
        ))
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Class {
    Zero,
    Finite,
    Infinity,
    Nan,
}

// A decoded operand. For a finite nonzero value the magnitude is
// significand * 2^(exponent - 63), with bit 63 of the significand set.
// `exponent` is then the true exponent of the leading bit, for a denormal
// too. For the other classes the two fields are unspecified.
#[derive(Clone, Copy)]
pub(crate) struct Decoded {
    pub(crate) negative: bool,
    pub(crate) class: Class,
    pub(crate) exponent: i32,
    pub(crate) significand: u64,
}

// A finite, nonzero, positive operand with the value
// significand * 2^(exponent - 63). Bit 63 of the significand is set. A
// binary64 operand has its low 11 significand bits clear, and a binary32
// operand has its low 40 clear.
#[derive(Clone, Copy)]
pub(crate) struct Magnitude {
    pub(crate) exponent: i32,
    pub(crate) significand: u64,
}

pub(crate) trait Format: Copy {
    // Decodes any encoding. The slow paths use this general decoding.
    fn decode(self) -> Decoded;

    // Returns the sign and, for a finite nonzero value, the exponent and
    // normalized significand that `decode` gives. A normal number is decoded
    // inline. A denormal goes through a cold call, so the common path stays
    // in registers.
    fn finite(self) -> (bool, Option<(i32, u64)>);

    // `is_normal` returns whether this is a normal number. For the 80-bit
    // format, a normal number has its integer bit set and an exponent field
    // that is neither zero nor all ones. For a normal number, `normal` returns
    // its sign, exponent and significand as `decode` gives them. For any
    // other value, the result of `normal` is meaningless.
    fn is_normal(self) -> bool;
    fn normal(self) -> (bool, i32, u64);

    // Returns the encoding of significand * 2^(exponent - 63). The
    // significand must be normalized and fit the format's precision, and the
    // exponent must lie in the format's normal range. Otherwise the result is
    // meaningless.
    fn encode(negative: bool, exponent: i32, significand: u64) -> Self;

    fn zero(negative: bool) -> Self;
    fn infinity(negative: bool) -> Self;

    // `words` splits the encoding into its low 64 bits and its remaining top
    // bits, and `from_words` joins them back.
    fn words(self) -> (u64, u16);
    fn from_words(low: u64, top: u16) -> Self;
}

#[cold]
#[inline(never)]
fn normalized(significand: u64, exponent: i32) -> (i32, u64) {
    let shift = significand.leading_zeros();
    (exponent - shift as i32, significand << shift)
}

impl Format for Single {
    fn decode(self) -> Decoded {
        let negative = self.0 >> 31 != 0;
        let field = (self.0 >> 23) & 0xFF;
        let fraction = u64::from(self.0 & 0x7F_FFFF);
        let (class, exponent, significand) = if field == 0xFF {
            (
                if fraction == 0 {
                    Class::Infinity
                } else {
                    Class::Nan
                },
                0,
                0,
            )
        } else if field != 0 {
            (
                Class::Finite,
                field as i32 - 127,
                (fraction | 1 << 23) << 40,
            )
        } else if fraction != 0 {
            // The value is fraction * 2^-149. The leading bit of a 23-bit
            // fraction sits at least 41 places below bit 63.
            let shift = fraction.leading_zeros();
            (Class::Finite, -86 - shift as i32, fraction << shift)
        } else {
            (Class::Zero, 0, 0)
        };
        Decoded {
            negative,
            class,
            exponent,
            significand,
        }
    }

    #[inline]
    fn finite(self) -> (bool, Option<(i32, u64)>) {
        let field = (self.0 >> 23) & 0xFF;
        let fraction = u64::from(self.0 & 0x7F_FFFF);
        let finite = if field.wrapping_sub(1) < 0xFE {
            Some((field as i32 - 127, (fraction | 1 << 23) << 40))
        } else if (field == 0) & (fraction != 0) {
            Some(normalized(fraction, -86))
        } else {
            None
        };
        (self.0 >> 31 != 0, finite)
    }

    fn words(self) -> (u64, u16) {
        (u64::from(self.0), 0)
    }

    fn from_words(low: u64, _: u16) -> Single {
        Single(low as u32)
    }

    fn is_normal(self) -> bool {
        ((self.0 >> 23) & 0xFF).wrapping_sub(1) < 0xFE
    }

    fn normal(self) -> (bool, i32, u64) {
        (
            self.0 >> 31 != 0,
            ((self.0 >> 23) & 0xFF) as i32 - 127,
            u64::from(self.0) << 40 | 1 << 63,
        )
    }

    fn encode(negative: bool, exponent: i32, significand: u64) -> Single {
        Single(
            u32::from(negative) << 31
                | (exponent.wrapping_add(127) as u32 & 0xFF) << 23
                | ((significand << 1) >> 41) as u32,
        )
    }

    fn zero(negative: bool) -> Single {
        Single(u32::from(negative) << 31)
    }

    fn infinity(negative: bool) -> Single {
        Single(u32::from(negative) << 31 | 0x7F80_0000)
    }
}

impl Format for Double {
    fn decode(self) -> Decoded {
        let negative = self.0 >> 63 != 0;
        let field = (self.0 >> 52) & 0x7FF;
        let fraction = self.0 & 0xF_FFFF_FFFF_FFFF;
        let (class, exponent, significand) = if field == 0x7FF {
            (
                if fraction == 0 {
                    Class::Infinity
                } else {
                    Class::Nan
                },
                0,
                0,
            )
        } else if field != 0 {
            (
                Class::Finite,
                field as i32 - 1023,
                (fraction | 1 << 52) << 11,
            )
        } else if fraction != 0 {
            // The value is fraction * 2^-1074.
            let shift = fraction.leading_zeros();
            (Class::Finite, -1011 - shift as i32, fraction << shift)
        } else {
            (Class::Zero, 0, 0)
        };
        Decoded {
            negative,
            class,
            exponent,
            significand,
        }
    }

    #[inline]
    fn finite(self) -> (bool, Option<(i32, u64)>) {
        let field = (self.0 >> 52) & 0x7FF;
        let fraction = self.0 & 0xF_FFFF_FFFF_FFFF;
        let finite = if field.wrapping_sub(1) < 0x7FE {
            Some((field as i32 - 1023, self.0 << 11 | 1 << 63))
        } else if (field == 0) & (fraction != 0) {
            Some(normalized(fraction, -1011))
        } else {
            None
        };
        (self.0 >> 63 != 0, finite)
    }

    fn words(self) -> (u64, u16) {
        (self.0, 0)
    }

    fn from_words(low: u64, _: u16) -> Double {
        Double(low)
    }

    fn is_normal(self) -> bool {
        ((self.0 >> 52) & 0x7FF).wrapping_sub(1) < 0x7FE
    }

    fn normal(self) -> (bool, i32, u64) {
        (
            self.0 >> 63 != 0,
            ((self.0 >> 52) & 0x7FF) as i32 - 1023,
            self.0 << 11 | 1 << 63,
        )
    }

    fn encode(negative: bool, exponent: i32, significand: u64) -> Double {
        Double(
            u64::from(negative) << 63
                | (exponent.wrapping_add(1023) as u64 & 0x7FF) << 52
                | (significand << 1) >> 12,
        )
    }

    fn zero(negative: bool) -> Double {
        Double(u64::from(negative) << 63)
    }

    fn infinity(negative: bool) -> Double {
        Double(u64::from(negative) << 63 | 0x7FF0_0000_0000_0000)
    }
}

impl Format for Extended {
    // Noncanonical encodings have unspecified results, but they decode
    // without panicking:
    // - A field of all ones is an infinity or a NaN, by its fraction.
    // - A zero significand is a zero.
    // - Any other encoding is its significand at the field's exponent.
    fn decode(self) -> Decoded {
        let negative = self.sign_exponent >> 15 != 0;
        let field = i32::from(self.sign_exponent & Extended::EXPONENT_MASK);
        let (class, exponent, significand) = if field == i32::from(Extended::EXPONENT_MASK) {
            (
                if self.significand << 1 == 0 {
                    Class::Infinity
                } else {
                    Class::Nan
                },
                0,
                0,
            )
        } else if self.significand >> 63 != 0 {
            // A field of zero with the integer bit set is a pseudo-denormal.
            // Its exponent is that of field 1.
            (
                Class::Finite,
                field.max(1) - Extended::BIAS,
                self.significand,
            )
        } else if self.significand != 0 {
            let shift = self.significand.leading_zeros();
            (
                Class::Finite,
                field.max(1) - Extended::BIAS - shift as i32,
                self.significand << shift,
            )
        } else {
            (Class::Zero, 0, 0)
        };
        Decoded {
            negative,
            class,
            exponent,
            significand,
        }
    }

    #[inline]
    fn finite(self) -> (bool, Option<(i32, u64)>) {
        let field = i32::from(self.sign_exponent & Extended::EXPONENT_MASK);
        let finite = if field == i32::from(Extended::EXPONENT_MASK) {
            None
        } else if self.significand >> 63 != 0 {
            Some((field.max(1) - Extended::BIAS, self.significand))
        } else if self.significand != 0 {
            Some(normalized(self.significand, field.max(1) - Extended::BIAS))
        } else {
            None
        };
        (self.sign_exponent >> 15 != 0, finite)
    }

    fn words(self) -> (u64, u16) {
        (self.significand, self.sign_exponent)
    }

    fn from_words(low: u64, top: u16) -> Extended {
        Extended {
            sign_exponent: top,
            significand: low,
        }
    }

    fn is_normal(self) -> bool {
        ((self.sign_exponent & Extended::EXPONENT_MASK).wrapping_sub(1)
            < Extended::EXPONENT_MASK - 1)
            & (self.significand >> 63 != 0)
    }

    fn normal(self) -> (bool, i32, u64) {
        (
            self.sign_exponent >> 15 != 0,
            i32::from(self.sign_exponent & Extended::EXPONENT_MASK) - Extended::BIAS,
            self.significand,
        )
    }

    fn encode(negative: bool, exponent: i32, significand: u64) -> Extended {
        Extended {
            sign_exponent: u16::from(negative) << 15
                | (exponent.wrapping_add(Extended::BIAS) as u16 & Extended::EXPONENT_MASK),
            significand,
        }
    }

    fn zero(negative: bool) -> Extended {
        Extended {
            sign_exponent: u16::from(negative) << 15,
            significand: 0,
        }
    }

    fn infinity(negative: bool) -> Extended {
        Extended {
            sign_exponent: u16::from(negative) << 15 | Extended::EXPONENT_MASK,
            significand: 1 << 63,
        }
    }
}