cverif 0.0.6

Verifies that compiled machine code faithfully matches its C source
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
//! IEEE-754 binary32 / binary64 floating point.
//!
//! Floating-point values are ordinary bit-vector terms holding the IEEE bit pattern.  This
//! module provides
//!
//! * a software implementation of the arithmetic (round to nearest, ties to even — the only
//!   mode C code without `<fenv.h>` runs in), used to fold constants, to evaluate
//!   counterexamples and to refine the prover's models;
//! * the term constructors both symbolic executors use, so that the C operator and the runtime
//!   routine a soft-float binary calls for it build the same term.
//!
//! # Model
//!
//! Comparisons, negation, `fabs` and the test against zero are built from plain bit-vector
//! operations and are therefore exact for every input, NaNs included.
//!
//! Addition, multiplication, division and the conversions are [`Node::Fp`] applications.  The
//! prover treats them as functions it knows nothing about except that equal arguments give
//! equal results, plus the true value at every concrete point a candidate counterexample
//! visits (see `Prover::refine_fp`).  A proof therefore never depends on the arithmetic
//! being right; a reported counterexample is always checked against the real arithmetic.
//!
//! The constructors apply only identities of IEEE arithmetic that hold for every non-NaN
//! input, bit for bit: `a - b = a + (-b)`, commutativity, `x * 1 = x`, `x * 2 = x + x`,
//! `x + (-0) = x`, division by a power of two as multiplication by its exact reciprocal,
//! `(-a) * b = -(a * b)` (likewise for division), and the removal of a widening to double
//! around a single operation whose result is narrowed again (double rounding is innocuous
//! there).  No reassociation, no distribution, no contraction into fused operations.
//!
//! # NaN
//!
//! The C standard does not say which NaN an operation produces, and hardware, runtime
//! libraries and compilers disagree.  When the result of an arithmetic operation is a NaN, its
//! sign and payload are therefore whatever the identities above make them: two computations
//! that differ only by those identities are considered equal even though a particular library
//! might give NaNs with different signs or payloads.  Whether a value *is* a NaN, and every
//! comparison involving one, is modelled exactly.

use crate::term::{Node, T, Terms, mask};

/// The operations kept as function applications in terms.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum FpOp {
    Add,
    Mul,
    Div,
    /// Signed / unsigned integer to floating point.
    SToF,
    UToF,
    /// Floating point to signed / unsigned integer, truncating.
    FToS,
    FToU,
    /// binary32 to binary64.
    Ext,
    /// binary64 to binary32.
    Trunc,
}

impl FpOp {
    pub fn is_binary(self) -> bool {
        matches!(self, FpOp::Add | FpOp::Mul | FpOp::Div)
    }

    pub fn is_commutative(self) -> bool {
        matches!(self, FpOp::Add | FpOp::Mul)
    }

    pub fn name(self) -> &'static str {
        match self {
            FpOp::Add => "fadd",
            FpOp::Mul => "fmul",
            FpOp::Div => "fdiv",
            FpOp::SToF => "stof",
            FpOp::UToF => "utof",
            FpOp::FToS => "ftos",
            FpOp::FToU => "ftou",
            FpOp::Ext => "fext",
            FpOp::Trunc => "ftrunc",
        }
    }
}

// ----- software arithmetic ----------------------------------------------------------------------

/// An IEEE binary interchange format.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Fmt {
    ebits: u32,
    mbits: u32,
}

pub const F32: Fmt = Fmt { ebits: 8, mbits: 23 };
pub const F64: Fmt = Fmt { ebits: 11, mbits: 52 };

enum Class {
    Zero,
    Inf,
    Nan,
    /// value = sig * 2^exp, sig != 0
    Fin(u64, i32),
}

impl Fmt {
    pub fn of(width: u8) -> Fmt {
        if width == 32 { F32 } else { F64 }
    }

    pub fn width(self) -> u8 {
        (1 + self.ebits + self.mbits) as u8
    }

    fn bias(self) -> i32 {
        (1 << (self.ebits - 1)) - 1
    }

    fn emax(self) -> u64 {
        (1 << self.ebits) - 1
    }

    pub fn sign_bit(self) -> u64 {
        1 << (self.ebits + self.mbits)
    }

    /// Bit pattern of +infinity; also the mask of the exponent field.
    pub fn inf(self) -> u64 {
        self.emax() << self.mbits
    }

    fn quiet(self) -> u64 {
        1 << (self.mbits - 1)
    }

    /// The default NaN.
    pub fn nan(self) -> u64 {
        self.inf() | self.quiet()
    }

    pub fn one(self) -> u64 {
        (self.bias() as u64) << self.mbits
    }

    /// Bit pattern of `2^k` (for exponents in the normal range).
    pub fn pow2(self, k: u32) -> u64 {
        self.one() + ((k as u64) << self.mbits)
    }

    pub fn is_nan(self, x: u64) -> bool {
        x & !self.sign_bit() > self.inf()
    }

    fn unpack(self, x: u64) -> (bool, Class) {
        let sign = x & self.sign_bit() != 0;
        let e = (x >> self.mbits) & self.emax();
        let m = x & ((1 << self.mbits) - 1);
        let c = if e == self.emax() {
            if m == 0 { Class::Inf } else { Class::Nan }
        } else if e == 0 {
            if m == 0 {
                Class::Zero
            } else {
                Class::Fin(m, 1 - self.bias() - self.mbits as i32)
            }
        } else {
            Class::Fin(m | 1 << self.mbits, e as i32 - self.bias() - self.mbits as i32)
        };
        (sign, c)
    }

    fn signed(self, sign: bool, bits: u64) -> u64 {
        if sign { bits | self.sign_bit() } else { bits }
    }

    /// The value `mag * 2^exp` (`mag != 0`) rounded to nearest, ties to even.
    fn round_pack(self, sign: bool, mag: u128, exp: i32) -> u64 {
        debug_assert!(mag != 0);
        let mbits = self.mbits as i32;
        let p = 127 - mag.leading_zeros() as i32;
        let e = p + exp; // 2^e <= value < 2^(e+1)
        let emin = 1 - self.bias();
        // Weight of the last place of the result.
        let lsb = if e < emin { emin - mbits } else { e - mbits };
        let shift = lsb - exp;
        let sig: u128 = if shift <= 0 {
            mag << (-shift) as u32
        } else if shift > 128 {
            0
        } else if shift == 128 {
            (mag > 1 << 127) as u128
        } else {
            let q = mag >> shift;
            let rem = mag & ((1u128 << shift) - 1);
            let half = 1u128 << (shift - 1);
            if rem > half || (rem == half && q & 1 == 1) {
                q + 1
            } else {
                q
            }
        };
        if e < emin {
            // Subnormal (or zero, or rounded up to the smallest normal number).
            return self.signed(sign, sig as u64);
        }
        if e + self.bias() >= self.emax() as i32 {
            return self.signed(sign, self.inf());
        }
        // `sig` is in [2^mbits, 2^(mbits+1)]; the top value carries into the exponent.
        let bits = (((e + self.bias()) as u64) << self.mbits) + (sig as u64 - (1 << self.mbits));
        self.signed(sign, bits)
    }

    fn nan_of(self, a: u64, b: u64) -> u64 {
        if self.is_nan(a) {
            a | self.quiet()
        } else {
            b | self.quiet()
        }
    }

    pub fn add(self, a: u64, b: u64) -> u64 {
        if self.is_nan(a) || self.is_nan(b) {
            return self.nan_of(a, b);
        }
        let ((sa, ca), (sb, cb)) = (self.unpack(a), self.unpack(b));
        match (ca, cb) {
            (Class::Inf, Class::Inf) => {
                if sa == sb {
                    a
                } else {
                    self.nan()
                }
            }
            (Class::Inf, _) => a,
            (_, Class::Inf) => b,
            (Class::Zero, Class::Zero) => self.signed(sa && sb, 0),
            (Class::Zero, _) => b,
            (_, Class::Zero) => a,
            (Class::Fin(ma, ea), Class::Fin(mb, eb)) => {
                // Order by exponent, then align; bits shifted out are jammed into the last place,
                // which is far below the rounding position.
                let ((s1, m1, e1), (s2, m2, e2)) = if ea >= eb {
                    ((sa, ma, ea), (sb, mb, eb))
                } else {
                    ((sb, mb, eb), (sa, ma, ea))
                };
                let d = (e1 - e2) as u32;
                let (x, y, e) = if d <= 70 {
                    ((m1 as u128) << d, m2 as u128, e2)
                } else {
                    let s = d - 70;
                    let (y, lost) = if s >= 64 {
                        (0, true)
                    } else {
                        (m2 >> s, m2 & ((1 << s) - 1) != 0)
                    };
                    ((m1 as u128) << 70, y as u128 | lost as u128, e1 - 70)
                };
                if s1 == s2 {
                    self.round_pack(s1, x + y, e)
                } else if x == y {
                    0
                } else if x > y {
                    self.round_pack(s1, x - y, e)
                } else {
                    self.round_pack(s2, y - x, e)
                }
            }
            (Class::Nan, _) | (_, Class::Nan) => unreachable!(),
        }
    }

    pub fn mul(self, a: u64, b: u64) -> u64 {
        if self.is_nan(a) || self.is_nan(b) {
            return self.nan_of(a, b);
        }
        let ((sa, ca), (sb, cb)) = (self.unpack(a), self.unpack(b));
        let sign = sa != sb;
        match (ca, cb) {
            (Class::Inf, Class::Zero) | (Class::Zero, Class::Inf) => self.nan(),
            (Class::Inf, _) | (_, Class::Inf) => self.signed(sign, self.inf()),
            (Class::Zero, _) | (_, Class::Zero) => self.signed(sign, 0),
            (Class::Fin(ma, ea), Class::Fin(mb, eb)) => self.round_pack(sign, ma as u128 * mb as u128, ea + eb),
            (Class::Nan, _) | (_, Class::Nan) => unreachable!(),
        }
    }

    pub fn div(self, a: u64, b: u64) -> u64 {
        if self.is_nan(a) || self.is_nan(b) {
            return self.nan_of(a, b);
        }
        let ((sa, ca), (sb, cb)) = (self.unpack(a), self.unpack(b));
        let sign = sa != sb;
        match (ca, cb) {
            (Class::Inf, Class::Inf) | (Class::Zero, Class::Zero) => self.nan(),
            (Class::Inf, _) | (_, Class::Zero) => self.signed(sign, self.inf()),
            (_, Class::Inf) | (Class::Zero, _) => self.signed(sign, 0),
            (Class::Fin(ma, ea), Class::Fin(mb, eb)) => {
                let lz = ma.leading_zeros();
                let n = ((ma << lz) as u128) << 64;
                let q = (n / mb as u128) | u128::from(!n.is_multiple_of(mb as u128));
                self.round_pack(sign, q, ea - lz as i32 - 64 - eb)
            }
            (Class::Nan, _) | (_, Class::Nan) => unreachable!(),
        }
    }

    /// The integer `(-1)^sign * mag` converted to this format.
    pub fn from_int(self, sign: bool, mag: u64) -> u64 {
        if mag == 0 {
            0
        } else {
            self.round_pack(sign, mag as u128, 0)
        }
    }

    /// The value truncated toward zero; None for NaN, infinities and magnitudes of 2^100 or more.
    pub fn to_int(self, x: u64) -> Option<i128> {
        let (sign, c) = self.unpack(x);
        let mag: i128 = match c {
            Class::Nan | Class::Inf => return None,
            Class::Zero => 0,
            Class::Fin(m, e) if e >= 0 => {
                if e > 100 - 53 {
                    return None;
                }
                (m as i128) << e
            }
            Class::Fin(m, e) => {
                if -e >= 64 {
                    0
                } else {
                    (m >> -e) as i128
                }
            }
        };
        Some(if sign { -mag } else { mag })
    }

    /// Convert a value of format `from` to this format.
    pub fn convert(self, from: Fmt, x: u64) -> u64 {
        let (sign, c) = from.unpack(x);
        match c {
            Class::Zero => self.signed(sign, 0),
            Class::Inf => self.signed(sign, self.inf()),
            Class::Nan => {
                let payload = x & ((1 << from.mbits) - 1);
                let p = if self.mbits >= from.mbits {
                    payload << (self.mbits - from.mbits)
                } else {
                    payload >> (from.mbits - self.mbits)
                };
                self.signed(sign, self.inf() | p | self.quiet())
            }
            Class::Fin(m, e) => self.round_pack(sign, m as u128, e),
        }
    }

    /// Is `x` (in this format) exactly representable in `to`, and not a NaN?
    fn fits(self, to: Fmt, x: u64) -> Option<u64> {
        if self.is_nan(x) {
            return None;
        }
        let y = to.convert(self, x);
        (self.convert(to, y) == x).then_some(y)
    }
}

/// Numeric comparison; None if either operand is a NaN.
pub fn compare(f: Fmt, a: u64, b: u64) -> Option<std::cmp::Ordering> {
    if f.is_nan(a) || f.is_nan(b) {
        return None;
    }
    let key = |x: u64| {
        let m = (x & !f.sign_bit()) as i64;
        if x & f.sign_bit() != 0 { -m } else { m }
    };
    Some(key(a).cmp(&key(b)))
}

/// What the ARM run-time conversions return: saturating, zero for NaN.
fn saturating_int(f: Fmt, x: u64, signed: bool, w: u8) -> u64 {
    if f.is_nan(x) {
        return 0;
    }
    let (lo, hi): (i128, i128) = if signed {
        (-(1i128 << (w - 1)), (1i128 << (w - 1)) - 1)
    } else {
        (0, (1i128 << w) - 1)
    };
    let v = match f.to_int(x) {
        Some(v) => v.clamp(lo, hi),
        None if x & f.sign_bit() != 0 => lo,
        None => hi,
    };
    v as u64 & mask(w)
}

/// The value of an operation on concrete operands.  `w` is the width of the result and `wa`
/// the width of the operands.  Total: conversions to an integer saturate.
pub fn apply(op: FpOp, w: u8, wa: u8, a: u64, b: u64) -> u64 {
    let f = Fmt::of(w);
    match op {
        FpOp::Add => f.add(a, b),
        FpOp::Mul => f.mul(a, b),
        FpOp::Div => f.div(a, b),
        FpOp::SToF => {
            let v = crate::term::sext64(a, wa);
            f.from_int(v < 0, v.unsigned_abs())
        }
        FpOp::UToF => f.from_int(false, a),
        FpOp::FToS => saturating_int(Fmt::of(wa), a, true, w),
        FpOp::FToU => saturating_int(Fmt::of(wa), a, false, w),
        FpOp::Ext | FpOp::Trunc => f.convert(Fmt::of(wa), a),
    }
}

/// Is the truncated value of `x` representable in a `w`-bit integer?  (Otherwise the
/// conversion is undefined in C.)
pub fn int_in_range(f: Fmt, x: u64, signed: bool, w: u8) -> bool {
    match f.to_int(x) {
        None => false,
        Some(v) if signed => v >= -(1i128 << (w - 1)) && v < 1i128 << (w - 1),
        Some(v) => v >= 0 && v < 1i128 << w,
    }
}

// ----- terms ------------------------------------------------------------------------------------

fn fmt_of(tm: &Terms, x: T) -> Fmt {
    Fmt::of(tm.width(x))
}

/// `-x`: flip the sign bit (adding the sign bit is the same thing and normalises better).
pub fn fneg(tm: &mut Terms, x: T) -> T {
    let f = fmt_of(tm, x);
    tm.add_const(x, f.sign_bit())
}

pub fn fabs(tm: &mut Terms, x: T) -> T {
    let w = tm.width(x);
    let lo = tm.extract(x, 0, w - 1);
    tm.zext(lo, w)
}

/// `x != 0` as C tests it: true for everything but the two zeros (true for NaN).
pub fn nonzero(tm: &mut Terms, x: T) -> T {
    let w = tm.width(x);
    let lo = tm.extract(x, 0, w - 1);
    tm.nonzero(lo)
}

pub fn is_nan(tm: &mut Terms, x: T) -> T {
    let f = fmt_of(tm, x);
    let m = fabs(tm, x);
    let inf = tm.konst(f.width(), f.inf());
    tm.ult(inf, m)
}

/// If `x` is visibly the negation of something, that something.
fn negated(tm: &mut Terms, x: T) -> Option<T> {
    let f = fmt_of(tm, x);
    match tm.node(x).clone() {
        Node::Const(v) if v & f.sign_bit() != 0 && !f.is_nan(v) => Some(tm.konst(f.width(), v ^ f.sign_bit())),
        Node::Sum(ts, k) if ts.len() == 1 && ts[0].1 == 1 && k == f.sign_bit() => Some(ts[0].0),
        // A double negated through its high word.
        Node::Concat(h, l) if tm.width(h) == 32 => match tm.node(h).clone() {
            Node::Sum(ts, k) if ts.len() == 1 && ts[0].1 == 1 && k == 1 << 31 => Some(tm.concat(ts[0].0, l)),
            _ => None,
        },
        _ => None,
    }
}

fn split_sign(tm: &mut Terms, x: T) -> (T, bool) {
    match negated(tm, x) {
        Some(y) => (y, true),
        None => (x, false),
    }
}

fn node(tm: &mut Terms, op: FpOp, a: T, b: T, w: u8) -> T {
    if let (Some(x), Some(y)) = (tm.as_const(a), tm.as_const(b)) {
        // Conversions to an integer are only folded where C defines them.
        let wa = tm.width(a);
        let defined = match op {
            FpOp::FToS => int_in_range(Fmt::of(wa), x, true, w),
            FpOp::FToU => int_in_range(Fmt::of(wa), x, false, w),
            _ => true,
        };
        if defined {
            return tm.konst(w, apply(op, w, wa, x, y));
        }
    }
    let (a, b) = if op.is_commutative() && b < a { (b, a) } else { (a, b) };
    tm.fp_node(op, a, b, w)
}

pub fn fadd(tm: &mut Terms, a: T, b: T) -> T {
    let f = fmt_of(tm, a);
    let w = f.width();
    debug_assert_eq!(w, tm.width(b));
    let neg_zero = f.sign_bit();
    match (tm.as_const(a), tm.as_const(b)) {
        (Some(_), Some(_)) => {}
        (_, Some(c)) if c == neg_zero => return a,
        (Some(c), _) if c == neg_zero => return b,
        _ => {}
    }
    // (-x) + (-x) = -(x + x), signed zeros included.
    if a == b
        && tm.as_const(a).is_none()
        && let Some(x) = negated(tm, a)
    {
        let r = node(tm, FpOp::Add, x, x, w);
        return fneg(tm, r);
    }
    node(tm, FpOp::Add, a, b, w)
}

pub fn fsub(tm: &mut Terms, a: T, b: T) -> T {
    let nb = fneg(tm, b);
    fadd(tm, a, nb)
}

pub fn fmul(tm: &mut Terms, a: T, b: T) -> T {
    let f = fmt_of(tm, a);
    let w = f.width();
    debug_assert_eq!(w, tm.width(b));
    if tm.as_const(a).is_some() && tm.as_const(b).is_some() {
        return node(tm, FpOp::Mul, a, b, w);
    }
    let ((a, sa), (b, sb)) = (split_sign(tm, a), split_sign(tm, b));
    let two = f.one() + (1 << f.mbits);
    let r = match (tm.as_const(a), tm.as_const(b)) {
        (_, Some(c)) if c == f.one() => a,
        (Some(c), _) if c == f.one() => b,
        (_, Some(c)) if c == two => fadd(tm, a, a),
        (Some(c), _) if c == two => fadd(tm, b, b),
        _ => node(tm, FpOp::Mul, a, b, w),
    };
    if sa != sb { fneg(tm, r) } else { r }
}

pub fn fdiv(tm: &mut Terms, a: T, b: T) -> T {
    let f = fmt_of(tm, a);
    let w = f.width();
    debug_assert_eq!(w, tm.width(b));
    if tm.as_const(a).is_some() && tm.as_const(b).is_some() {
        return node(tm, FpOp::Div, a, b, w);
    }
    let ((a, sa), (b, sb)) = (split_sign(tm, a), split_sign(tm, b));
    let r = match tm.as_const(b) {
        // Division by a power of two whose reciprocal is an exact normal number.
        Some(c)
            if c & ((1 << f.mbits) - 1) == 0 && c != 0 && c < f.inf() && {
                let r = f.div(f.one(), c);
                r >> f.mbits != 0 && r < f.inf() && f.mul(r, c) == f.one()
            } =>
        {
            let r = tm.konst(w, f.div(f.one(), c));
            fmul(tm, a, r)
        }
        _ => node(tm, FpOp::Div, a, b, w),
    };
    if sa != sb { fneg(tm, r) } else { r }
}

/// Integer `x` to a float of width `w`.
pub fn from_int(tm: &mut Terms, x: T, signed: bool, w: u8) -> T {
    let wx = tm.width(x);
    // Widened operands convert like the original.
    match *tm.node(x) {
        Node::ZExt(y) if tm.width(y) >= 32 => return from_int(tm, y, false, w),
        Node::SExt(y) if signed && tm.width(y) >= 32 => return from_int(tm, y, true, w),
        _ => {}
    }
    // A non-negative value converts the same way either way: use the unsigned conversion.
    let signed = signed && tm.ubound(x, 0) >= 1u64 << (wx - 1);
    let op = if signed { FpOp::SToF } else { FpOp::UToF };
    node(tm, op, x, x, w)
}

/// Float `x` to an integer of width `w`, truncating.
pub fn to_int(tm: &mut Terms, x: T, signed: bool, w: u8) -> T {
    // Widening is exact.
    if let Node::Fp(FpOp::Ext, y, _) = *tm.node(x) {
        return to_int(tm, y, signed, w);
    }
    let op = if signed { FpOp::FToS } else { FpOp::FToU };
    node(tm, op, x, x, w)
}

/// The condition under which C defines the conversion of `x` to a `w`-bit integer type:
/// the truncated value is representable.
pub fn to_int_defined(tm: &mut Terms, x: T, signed: bool, w: u8) -> T {
    let f = fmt_of(tm, x);
    let fw = f.width();
    // Smallest power of two that is too large, as a float (always exact).
    let too_big = f.pow2(if signed { w as u32 - 1 } else { w as u32 });
    let hi = tm.konst(fw, too_big);
    let below = lt(tm, x, hi);
    let above = if signed {
        // x > -(2^(w-1) + 1) when that bound is exact in the format, else x >= -2^(w-1).
        let mag = (1u64 << (w - 1)) + 1;
        let exact = f.from_int(true, mag);
        if f.to_int(exact) == Some(-(mag as i128)) {
            let lo = tm.konst(fw, exact);
            lt(tm, lo, x)
        } else {
            let lo = tm.konst(fw, f.from_int(true, mag - 1));
            le(tm, lo, x)
        }
    } else {
        let lo = tm.konst(fw, f.signed(true, f.one()));
        lt(tm, lo, x)
    };
    tm.and(below, above)
}

/// binary32 to binary64.
pub fn ext(tm: &mut Terms, x: T) -> T {
    node(tm, FpOp::Ext, x, x, 64)
}

/// The binary32 value a binary64 term is the exact widening of, if that is visible.
fn narrowed(tm: &mut Terms, x: T) -> Option<T> {
    match tm.node(x).clone() {
        Node::Fp(FpOp::Ext, y, _) => Some(y),
        Node::Const(v) => F64.fits(F32, v).map(|c| tm.konst(32, c)),
        _ => {
            let y = negated(tm, x)?;
            let n = narrowed(tm, y)?;
            Some(fneg(tm, n))
        }
    }
}

/// binary64 to binary32.
pub fn trunc(tm: &mut Terms, x: T) -> T {
    if tm.as_const(x).is_none() {
        if let Some(y) = narrowed(tm, x) {
            return y;
        }
        match *tm.node(x) {
            // One operation on widened operands, narrowed again: rounding twice gives the same
            // result as the single-precision operation (53 >= 2 * 24 + 2).
            Node::Fp(op @ (FpOp::Add | FpOp::Mul | FpOp::Div), a, b) => {
                if let (Some(a), Some(b)) = (narrowed(tm, a), narrowed(tm, b)) {
                    return match op {
                        FpOp::Add => fadd(tm, a, b),
                        FpOp::Mul => fmul(tm, a, b),
                        _ => fdiv(tm, a, b),
                    };
                }
            }
            // A 32-bit integer is exact in double.
            Node::Fp(op @ (FpOp::SToF | FpOp::UToF), i, _) if tm.width(i) <= 32 => {
                return from_int(tm, i, op == FpOp::SToF, 32);
            }
            _ => {}
        }
        // The negation of one of the above.
        if let Some(y) = negated(tm, x)
            && matches!(tm.node(y), Node::Fp(..))
        {
            let t = trunc(tm, y);
            if !matches!(tm.node(t), Node::Fp(FpOp::Trunc, ..)) {
                return fneg(tm, t);
            }
        }
    }
    node(tm, FpOp::Trunc, x, x, 32)
}

/// Convert between the two formats (or not at all).
pub fn convert(tm: &mut Terms, x: T, w: u8) -> T {
    match (tm.width(x), w) {
        (32, 64) => ext(tm, x),
        (64, 32) => trunc(tm, x),
        _ => x,
    }
}

/// Two doubles that are both visible widenings compare like the originals.
fn narrow_pair(tm: &mut Terms, a: T, b: T) -> (T, T) {
    if tm.width(a) == 64
        && (matches!(tm.node(a), Node::Fp(FpOp::Ext, ..)) || matches!(tm.node(b), Node::Fp(FpOp::Ext, ..)))
        && let (Some(x), Some(y)) = (narrowed(tm, a), narrowed(tm, b))
    {
        return (x, y);
    }
    (a, b)
}

/// A key that orders non-NaN values like the numbers they stand for (both zeros map to 0).
fn key(tm: &mut Terms, x: T) -> T {
    let w = tm.width(x);
    let m = fabs(tm, x);
    let s = tm.extract(x, w - 1, 1);
    let n = tm.neg(m);
    tm.ite(s, n, m)
}

fn ordered(tm: &mut Terms, a: T, b: T) -> T {
    let (na, nb) = (is_nan(tm, a), is_nan(tm, b));
    let n = tm.or(na, nb);
    tm.not(n)
}

/// `a < b` (false if either is a NaN).
pub fn lt(tm: &mut Terms, a: T, b: T) -> T {
    let (a, b) = narrow_pair(tm, a, b);
    let o = ordered(tm, a, b);
    let (ka, kb) = (key(tm, a), key(tm, b));
    let c = tm.slt(ka, kb);
    tm.and(o, c)
}

/// `a <= b` (false if either is a NaN).
pub fn le(tm: &mut Terms, a: T, b: T) -> T {
    let (a, b) = narrow_pair(tm, a, b);
    let o = ordered(tm, a, b);
    let (ka, kb) = (key(tm, a), key(tm, b));
    let c = tm.slt(kb, ka);
    let c = tm.not(c);
    tm.and(o, c)
}

/// `a == b` (false if either is a NaN; the two zeros are equal).
pub fn eq(tm: &mut Terms, a: T, b: T) -> T {
    let (a, b) = narrow_pair(tm, a, b);
    let o = ordered(tm, a, b);
    let (ka, kb) = (key(tm, a), key(tm, b));
    let c = tm.eq(ka, kb);
    tm.and(o, c)
}

pub fn unordered(tm: &mut Terms, a: T, b: T) -> T {
    let (a, b) = narrow_pair(tm, a, b);
    let o = ordered(tm, a, b);
    tm.not(o)
}

/// Do these ELF build attributes (`.ARM.attributes`) declare the hard-float calling convention
/// (Tag_ABI_VFP_args other than "base AAPCS")?
pub fn vfp_args(attrs: &[u8]) -> bool {
    // One parser for build attributes: the one that names every tag for the build report.
    crate::detect::build_attributes(attrs)
        .iter()
        .any(|a| a.0 == "Tag_ABI_VFP_args" && a.1 != "soft")
}

// ----- run-time library ---------------------------------------------------------------------------

/// What a soft-float run-time routine leaves behind.
pub enum Outcome {
    /// A value in r0 (32 bits) or r1:r0 (64 bits).
    Value(T),
    /// The Z and C flags; every core register but ip and lr is preserved.
    Flags { z: T, c: T },
}

/// The effect of the AEABI / libgcc / compiler-rt floating-point routine `name` called with the
/// given values of r0..r3, or None if `name` is not one.
pub fn runtime_call(tm: &mut Terms, name: &str, r: [T; 4]) -> Option<Outcome> {
    // Operand layout: single precision in r0, r1; double precision in r1:r0, r3:r2.
    let (double, base) = if let Some(n) = name.strip_prefix("__aeabi_") {
        let n = n.strip_prefix('c').filter(|m| m.starts_with(['f', 'd'])).unwrap_or(n);
        (n.starts_with('d'), name)
    } else {
        (name.contains("df"), name)
    };
    let d0 = tm.concat(r[1], r[0]);
    let d1 = tm.concat(r[3], r[2]);
    let (a, b) = if double { (d0, d1) } else { (r[0], r[1]) };
    let b32 = |tm: &mut Terms, c: T| tm.zext(c, 32);
    // libgcc's three-way comparisons: -1, 0, 1, and `nan` when unordered.
    let three_way = |tm: &mut Terms, nan: u64| {
        let (l, e) = (lt(tm, a, b), eq(tm, a, b));
        let g = lt(tm, b, a);
        let (m1, z, p1, n) = (
            tm.konst(32, 0xffff_ffff),
            tm.konst(32, 0),
            tm.konst(32, 1),
            tm.konst(32, nan),
        );
        let x = tm.ite(g, p1, n);
        let x = tm.ite(e, z, x);
        tm.ite(l, m1, x)
    };
    let int_to = |tm: &mut Terms, x: T, signed: bool, w: u8| from_int(tm, x, signed, w);
    let v = match base {
        "__aeabi_fadd" | "__aeabi_dadd" | "__addsf3" | "__adddf3" => fadd(tm, a, b),
        "__aeabi_fsub" | "__aeabi_dsub" | "__subsf3" | "__subdf3" => fsub(tm, a, b),
        "__aeabi_frsub" | "__aeabi_drsub" => fsub(tm, b, a),
        "__aeabi_fmul" | "__aeabi_dmul" | "__mulsf3" | "__muldf3" => fmul(tm, a, b),
        "__aeabi_fdiv" | "__aeabi_ddiv" | "__divsf3" | "__divdf3" => fdiv(tm, a, b),
        "__negsf2" | "__negdf2" | "__aeabi_fneg" | "__aeabi_dneg" => fneg(tm, a),
        "fabsf" => fabs(tm, r[0]),
        "fabs" | "fabsl" => fabs(tm, d0),
        "__aeabi_fcmpeq" | "__aeabi_dcmpeq" => {
            let c = eq(tm, a, b);
            b32(tm, c)
        }
        "__aeabi_fcmplt" | "__aeabi_dcmplt" => {
            let c = lt(tm, a, b);
            b32(tm, c)
        }
        "__aeabi_fcmple" | "__aeabi_dcmple" => {
            let c = le(tm, a, b);
            b32(tm, c)
        }
        "__aeabi_fcmpge" | "__aeabi_dcmpge" => {
            let c = le(tm, b, a);
            b32(tm, c)
        }
        "__aeabi_fcmpgt" | "__aeabi_dcmpgt" => {
            let c = lt(tm, b, a);
            b32(tm, c)
        }
        "__aeabi_fcmpun" | "__aeabi_dcmpun" | "__unordsf2" | "__unorddf2" => {
            let c = unordered(tm, a, b);
            b32(tm, c)
        }
        // Z: equal.  C: clear exactly when the first operand is less.
        "__aeabi_cfcmpeq" | "__aeabi_cfcmple" | "__aeabi_cdcmpeq" | "__aeabi_cdcmple" => {
            let l = lt(tm, a, b);
            return Some(Outcome::Flags {
                z: eq(tm, a, b),
                c: tm.not(l),
            });
        }
        "__aeabi_cfrcmple" | "__aeabi_cdrcmple" => {
            let l = lt(tm, b, a);
            return Some(Outcome::Flags {
                z: eq(tm, a, b),
                c: tm.not(l),
            });
        }
        "__eqsf2" | "__nesf2" | "__ltsf2" | "__lesf2" | "__cmpsf2" | "__eqdf2" | "__nedf2" | "__ltdf2" | "__ledf2"
        | "__cmpdf2" => three_way(tm, 1),
        "__gesf2" | "__gtsf2" | "__gedf2" | "__gtdf2" => three_way(tm, 0xffff_ffff),
        "__aeabi_i2f" | "__floatsisf" => int_to(tm, r[0], true, 32),
        "__aeabi_ui2f" | "__floatunsisf" => int_to(tm, r[0], false, 32),
        "__aeabi_l2f" | "__floatdisf" => int_to(tm, d0, true, 32),
        "__aeabi_ul2f" | "__floatundisf" => int_to(tm, d0, false, 32),
        "__aeabi_i2d" | "__floatsidf" => int_to(tm, r[0], true, 64),
        "__aeabi_ui2d" | "__floatunsidf" => int_to(tm, r[0], false, 64),
        "__aeabi_l2d" | "__floatdidf" => int_to(tm, d0, true, 64),
        "__aeabi_ul2d" | "__floatundidf" => int_to(tm, d0, false, 64),
        "__aeabi_f2iz" | "__fixsfsi" => to_int(tm, r[0], true, 32),
        "__aeabi_f2uiz" | "__fixunssfsi" => to_int(tm, r[0], false, 32),
        "__aeabi_f2lz" | "__fixsfdi" => to_int(tm, r[0], true, 64),
        "__aeabi_f2ulz" | "__fixunssfdi" => to_int(tm, r[0], false, 64),
        "__aeabi_d2iz" | "__fixdfsi" => to_int(tm, d0, true, 32),
        "__aeabi_d2uiz" | "__fixunsdfsi" => to_int(tm, d0, false, 32),
        "__aeabi_d2lz" | "__fixdfdi" => to_int(tm, d0, true, 64),
        "__aeabi_d2ulz" | "__fixunsdfdi" => to_int(tm, d0, false, 64),
        "__aeabi_f2d" | "__extendsfdf2" => ext(tm, r[0]),
        "__aeabi_d2f" | "__truncdfsf2" => trunc(tm, d0),
        _ => return None,
    };
    Some(Outcome::Value(v))
}

/// Parse a C floating constant (without suffix) to the nearest value of `f`.
pub fn parse_literal(f: Fmt, s: &str) -> Option<u64> {
    let lower = s.to_ascii_lowercase();
    if let Some(hex) = lower.strip_prefix("0x") {
        let (mant, exp) = hex.split_once('p')?;
        let exp: i32 = exp.parse().ok()?;
        let (int, frac) = mant.split_once('.').unwrap_or((mant, ""));
        if int.is_empty() && frac.is_empty() {
            return None;
        }
        let mut mag: u128 = 0;
        let mut e = exp;
        let mut sticky = false;
        for (i, c) in int.chars().chain(frac.chars()).enumerate() {
            let d = c.to_digit(16)? as u128;
            if mag >> 120 == 0 {
                mag = mag << 4 | d;
                if i >= int.len() {
                    e -= 4;
                }
            } else {
                sticky |= d != 0;
                if i < int.len() {
                    e += 4;
                }
            }
        }
        if mag == 0 {
            return Some(0);
        }
        return Some(f.round_pack(false, mag | sticky as u128, e));
    }
    // The standard library's decimal conversions are correctly rounded.
    if f == F32 {
        lower.parse::<f32>().ok().map(|v| v.to_bits() as u64)
    } else {
        lower.parse::<f64>().ok().map(|v| v.to_bits())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        /// A bit pattern biased towards the interesting corners of the format.
        fn float(&mut self, f: Fmt) -> u64 {
            let r = self.next();
            let w = f.width() as u32;
            let m = mask(w as u8);
            let mant = (1u64 << f.mbits) - 1;
            match r % 16 {
                0 => self.next() & f.sign_bit(),                                        // zeros
                1 => f.inf() | (self.next() & f.sign_bit()),                            // infinities
                2 => f.inf() | (self.next() & m),                                       // mostly NaN
                3 => self.next() & (mant | f.sign_bit()),                               // subnormals
                4 => (self.next() & f.sign_bit()) | (1 + self.next() % 4),              // tiny subnormals
                5 => (self.next() & f.sign_bit()) | (f.inf() - 1 - self.next() % 4),    // near overflow
                6 => (self.next() & f.sign_bit()) | (1 << f.mbits) | (self.next() % 4), // smallest normals
                7 | 8 => {
                    // Small integers and halves.
                    let v = (self.next() % 2048) as f64 / 2.0 - 512.0;
                    if f == F32 {
                        (v as f32).to_bits() as u64
                    } else {
                        v.to_bits()
                    }
                }
                9 | 10 => {
                    // Exponents close to one another, sparse mantissas.
                    let e = (f.bias() as u64 + self.next() % 64 - 32) << f.mbits;
                    let bits = (1u64 << (self.next() % (f.mbits as u64 + 1))) - 1;
                    (self.next() & f.sign_bit()) | e | (bits & mant & self.next())
                }
                _ => self.next() & m,
            }
        }
    }

    fn same(f: Fmt, got: u64, want: u64) -> bool {
        got == want || (f.is_nan(got) && f.is_nan(want))
    }

    #[test]
    fn single_precision_matches_the_host() {
        let mut r = Rng(0x9e3779b97f4a7c15);
        for i in 0..1_500_000 {
            let (a, b) = (r.float(F32), r.float(F32));
            let (x, y) = (f32::from_bits(a as u32), f32::from_bits(b as u32));
            let cases = [
                ("add", F32.add(a, b), (x + y).to_bits() as u64),
                ("mul", F32.mul(a, b), (x * y).to_bits() as u64),
                ("div", F32.div(a, b), (x / y).to_bits() as u64),
            ];
            for (name, got, want) in cases {
                assert!(
                    same(F32, got, want),
                    "{i}: {name}({a:#x}, {b:#x}) = {got:#x}, host {want:#x}"
                );
            }
            let want = (x as f64).to_bits();
            assert!(same(F64, F64.convert(F32, a), want), "ext({a:#x})");
            assert_eq!(F32.is_nan(a), x.is_nan());
            // Conversions to integers saturate on the host exactly like the ARM routines.
            assert_eq!(
                apply(FpOp::FToS, 32, 32, a, a),
                (x as i32) as u32 as u64,
                "f2iz({a:#x})"
            );
            assert_eq!(apply(FpOp::FToU, 32, 32, a, a), (x as u32) as u64, "f2uiz({a:#x})");
            assert_eq!(apply(FpOp::FToS, 64, 32, a, a), (x as i64) as u64, "f2lz({a:#x})");
            assert_eq!(apply(FpOp::FToU, 64, 32, a, a), x as u64, "f2ulz({a:#x})");
            assert_eq!(
                int_in_range(F32, a, true, 32),
                x > -2147483904.0 && x < 2147483648.0,
                "{a:#x}"
            );
        }
    }

    #[test]
    fn double_precision_matches_the_host() {
        let mut r = Rng(0xdeadbeefcafef00d);
        for i in 0..1_500_000 {
            let (a, b) = (r.float(F64), r.float(F64));
            let (x, y) = (f64::from_bits(a), f64::from_bits(b));
            let cases = [
                ("add", F64.add(a, b), (x + y).to_bits()),
                ("mul", F64.mul(a, b), (x * y).to_bits()),
                ("div", F64.div(a, b), (x / y).to_bits()),
            ];
            for (name, got, want) in cases {
                assert!(
                    same(F64, got, want),
                    "{i}: {name}({a:#x}, {b:#x}) = {got:#x}, host {want:#x}"
                );
            }
            let want = (x as f32).to_bits() as u64;
            assert!(same(F32, F32.convert(F64, a), want), "trunc({a:#x})");
            assert_eq!(
                apply(FpOp::FToS, 32, 64, a, a),
                (x as i32) as u32 as u64,
                "d2iz({a:#x})"
            );
            assert_eq!(apply(FpOp::FToU, 32, 64, a, a), (x as u32) as u64, "d2uiz({a:#x})");
            assert_eq!(apply(FpOp::FToS, 64, 64, a, a), (x as i64) as u64, "d2lz({a:#x})");
            assert_eq!(apply(FpOp::FToU, 64, 64, a, a), x as u64, "d2ulz({a:#x})");
            assert_eq!(
                int_in_range(F64, a, true, 32),
                x > -2147483649.0 && x < 2147483648.0,
                "{a:#x}"
            );
            assert_eq!(int_in_range(F64, a, false, 32), x > -1.0 && x < 4294967296.0, "{a:#x}");
        }
    }

    #[test]
    fn integer_conversions_match_the_host() {
        let mut r = Rng(0x1234567887654321);
        for _ in 0..1_000_000 {
            let mut v = r.next();
            // Many values with long runs of ones (rounding carries) or few significant bits.
            match r.next() % 4 {
                0 => v >>= r.next() % 64,
                1 => v = (v | (v >> 1)) >> (r.next() % 40),
                2 => v = (1u64 << (r.next() % 64)).wrapping_add(r.next() % 3).wrapping_sub(1),
                _ => {}
            }
            assert_eq!(
                apply(FpOp::SToF, 32, 64, v, v),
                (v as i64 as f32).to_bits() as u64,
                "l2f({v:#x})"
            );
            assert_eq!(
                apply(FpOp::UToF, 32, 64, v, v),
                (v as f32).to_bits() as u64,
                "ul2f({v:#x})"
            );
            assert_eq!(
                apply(FpOp::SToF, 64, 64, v, v),
                (v as i64 as f64).to_bits(),
                "l2d({v:#x})"
            );
            assert_eq!(apply(FpOp::UToF, 64, 64, v, v), (v as f64).to_bits(), "ul2d({v:#x})");
            let w = v & 0xffff_ffff;
            assert_eq!(
                apply(FpOp::SToF, 32, 32, w, w),
                (w as u32 as i32 as f32).to_bits() as u64,
                "i2f({w:#x})"
            );
            assert_eq!(
                apply(FpOp::UToF, 32, 32, w, w),
                (w as u32 as f32).to_bits() as u64,
                "ui2f({w:#x})"
            );
            assert_eq!(
                apply(FpOp::SToF, 64, 32, w, w),
                (w as u32 as i32 as f64).to_bits(),
                "i2d({w:#x})"
            );
        }
    }

    #[test]
    fn literals() {
        assert_eq!(parse_literal(F32, "0.1"), Some(0.1f32.to_bits() as u64));
        assert_eq!(parse_literal(F64, "0.1"), Some(0.1f64.to_bits()));
        assert_eq!(parse_literal(F64, "1e-320"), Some(1e-320f64.to_bits()));
        assert_eq!(parse_literal(F32, "0x1.8p1"), Some(3.0f32.to_bits() as u64));
        assert_eq!(parse_literal(F64, "0x.8p0"), Some(0.5f64.to_bits()));
        assert_eq!(parse_literal(F64, "0X1P-1074"), Some(1));
        assert_eq!(parse_literal(F32, "0x1.fffffffp127"), Some(F32.inf()));
        assert_eq!(parse_literal(F32, "0x1.000001p0"), Some(1.0f32.to_bits() as u64));
        assert_eq!(parse_literal(F32, "0x1.000003p0"), Some(1.0f32.to_bits() as u64 + 2));
    }

    /// The identities the constructors rely on, checked on the software arithmetic.
    #[test]
    fn constructor_identities() {
        let mut r = Rng(0x0f0f0f0f12345678);
        for _ in 0..400_000 {
            for f in [F32, F64] {
                let (a, b) = (r.float(f), r.float(f));
                if f.is_nan(a) || f.is_nan(b) {
                    continue;
                }
                let s = f.sign_bit();
                let two = f.one() + (1 << f.mbits);
                assert_eq!(f.add(a, b), f.add(b, a));
                assert_eq!(f.mul(a, b), f.mul(b, a));
                assert_eq!(f.add(a, s), a, "x + -0");
                assert_eq!(f.mul(a, f.one()), a);
                assert_eq!(f.mul(a, two), f.add(a, a));
                let (p, q) = (f.mul(a ^ s, b), f.mul(a, b));
                assert!(p == q ^ s || f.is_nan(q), "(-a) * b");
                let (p, q) = (f.div(a ^ s, b), f.div(a, b));
                assert!(p == q ^ s || f.is_nan(q), "(-a) / b");
                let (p, q) = (f.div(a, b ^ s), f.div(a, b));
                assert!(p == q ^ s || f.is_nan(q), "a / (-b)");
                // Division by a power of two with an exact reciprocal.
                let c = (r.next() % (f.emax() - 1) + 1) << f.mbits;
                let rc = f.div(f.one(), c);
                if rc >> f.mbits != 0 && rc < f.inf() && f.mul(rc, c) == f.one() {
                    assert_eq!(f.div(a, c), f.mul(a, rc), "{a:#x} / {c:#x}");
                }
            }
            // Double rounding is innocuous for one operation on widened operands.
            let (a, b) = (r.float(F32), r.float(F32));
            if F32.is_nan(a) || F32.is_nan(b) {
                continue;
            }
            let (x, y) = (F64.convert(F32, a), F64.convert(F32, b));
            let narrow = |v: u64| F32.convert(F64, v);
            let ok = |p: u64, q: u64| p == q || (F32.is_nan(p) && F32.is_nan(q));
            assert!(ok(narrow(F64.add(x, y)), F32.add(a, b)));
            assert!(ok(narrow(F64.mul(x, y)), F32.mul(a, b)));
            assert!(ok(narrow(F64.div(x, y)), F32.div(a, b)), "{a:#x} / {b:#x}");
            assert_eq!(narrow(x), a);
            assert_eq!(F64.fits(F32, x), Some(a));
            // Truncation toward zero commutes with widening.
            assert_eq!(apply(FpOp::FToS, 32, 32, a, a), apply(FpOp::FToS, 32, 64, x, x));
            // A 32-bit integer rounds to single precision the same way through double.
            let i = r.next() & 0xffff_ffff;
            assert_eq!(narrow(apply(FpOp::SToF, 64, 32, i, i)), apply(FpOp::SToF, 32, 32, i, i));
            assert_eq!(narrow(apply(FpOp::UToF, 64, 32, i, i)), apply(FpOp::UToF, 32, 32, i, i));
        }
    }

    #[test]
    fn runtime_routines() {
        let mut tm = Terms::new();
        let nan = F32.nan();
        let f = |x: f32| x.to_bits() as u64;
        let mut call = |name: &str, a: u64, b: u64| -> (u64, u64) {
            let r = [tm.konst(32, a), tm.konst(32, b), tm.konst(32, 0), tm.konst(32, 0)];
            match runtime_call(&mut tm, name, r).unwrap() {
                Outcome::Value(v) => (tm.as_const(v).unwrap(), 0),
                Outcome::Flags { z, c } => (tm.as_const(z).unwrap(), tm.as_const(c).unwrap()),
            }
        };
        assert_eq!(call("__aeabi_fadd", f(1.5), f(2.25)).0, f(3.75));
        assert_eq!(call("__aeabi_frsub", f(1.5), f(2.25)).0, f(0.75));
        assert_eq!(call("__divsf3", f(1.0), f(4.0)).0, f(0.25));
        assert_eq!(call("__aeabi_fcmplt", f(1.0), f(2.0)).0, 1);
        assert_eq!(call("__aeabi_fcmpge", f(1.0), f(2.0)).0, 0);
        assert_eq!(call("__aeabi_fcmpge", nan, f(2.0)).0, 0);
        assert_eq!(call("__aeabi_fcmpun", nan, f(2.0)).0, 1);
        assert_eq!(call("__aeabi_fcmpeq", f(0.0), f(-0.0)).0, 1);
        // libgcc's three-way results: unordered must make the intended test fail.
        assert_eq!(call("__ltsf2", f(1.0), f(2.0)).0, 0xffff_ffff);
        assert_eq!(call("__lesf2", f(2.0), f(2.0)).0, 0);
        assert_eq!(call("__lesf2", nan, f(2.0)).0, 1);
        assert_eq!(call("__gesf2", f(3.0), f(2.0)).0, 1);
        assert_eq!(call("__gesf2", nan, f(2.0)).0, 0xffff_ffff);
        assert_eq!(call("__unordsf2", f(1.0), nan).0, 1);
        // Flags: Z when equal, C clear exactly when less.
        assert_eq!(call("__aeabi_cfcmple", f(1.0), f(2.0)), (0, 0));
        assert_eq!(call("__aeabi_cfcmple", f(2.0), f(2.0)), (1, 1));
        assert_eq!(call("__aeabi_cfcmple", f(3.0), f(2.0)), (0, 1));
        assert_eq!(call("__aeabi_cfcmpeq", nan, f(2.0)), (0, 1));
        assert_eq!(call("__aeabi_cfrcmple", f(3.0), f(2.0)), (0, 0));
        assert_eq!(call("__aeabi_i2f", 0xffff_fffe, 0).0, f(-2.0));
        assert_eq!(call("__floatunsisf", 0x8000_0000, 0).0, f(2147483648.0));
        assert_eq!(call("__aeabi_f2iz", f(-7.9), 0).0, 0xffff_fff9);
        assert_eq!(call("__fixunssfsi", f(7.9), 0).0, 7);
        assert_eq!(call("__aeabi_f2d", f(0.1), 0).0, (0.1f32 as f64).to_bits());
        // Doubles arrive in register pairs, low word first.
        let d = 2.5f64.to_bits();
        assert_eq!(call("__aeabi_d2f", d & 0xffff_ffff, d >> 32).0, f(2.5));
        assert_eq!(call("__aeabi_d2iz", d & 0xffff_ffff, d >> 32).0, 2);
    }
}