m68k 0.18.0

A safe Rust M68000 family CPU emulator
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
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! Extended-precision FPU transcendentals (and the FMOD/FREM remainders).
//!
//! Each function reduces its argument, evaluates a Taylor/atanh series in the
//! double-double layer (`dd.rs`) -- whose coefficients are exact rationals, so
//! no minimax tooling is needed -- and rounds the ~128-bit result to 64-bit
//! extended under the caller's FPCR mode, setting INEX/OPERR/DZ. The test suite
//! checks finite normal results against 200-bit `astro-float` references with a
//! one-ULP tolerance across all FPCR rounding modes. Results are not
//! chip-bit-exact: the 6888x uses its own CORDIC/polynomial microcode, and a
//! bare 68040 traps these operations to a software FPSP. FMOD/FREM are exact.

use super::dd::{self, Df};
use super::softfloat::{self, ExcFlags, FpCmp, RoundCtx, RoundMode};
use super::two_over_pi::TWO_OVER_PI;
use super::types::FloatX80;

// ============================== small helpers ============================

#[inline]
fn one_x80() -> FloatX80 {
    softfloat::from_u64(1, false)
}

#[inline]
fn fx(v: f64) -> FloatX80 {
    FloatX80::from_f64(v)
}

/// 2^k as an exact extended value (or +/-Inf / 0 on overflow/underflow).
#[inline]
fn two_pow(k: i32) -> FloatX80 {
    softfloat::scale(
        one_x80(),
        k,
        RoundCtx::NEAREST_EXT,
        &mut ExcFlags::default(),
    )
}

/// Result for a NaN operand: quiet it and signal SNAN (only) if it was
/// signaling (MC68881/MC68882UM 4.6.4).
fn nan_result(x: FloatX80, f: &mut ExcFlags) -> FloatX80 {
    if x.is_signaling_nan() {
        f.raise(ExcFlags::SNAN);
    }
    x.quiet()
}

#[inline]
fn noflags() -> ExcFlags {
    ExcFlags::default()
}

#[inline]
fn unbiased_exp(x: FloatX80) -> i32 {
    softfloat::to_i64(
        softfloat::getexp(x, &mut noflags()),
        RoundMode::Zero,
        i64::MIN,
        i64::MAX,
        &mut noflags(),
    ) as i32
}

// ============================== tiny operands ============================

/// The result for an operand so small that the function's value is the
/// operand itself, or 1, to within half a unit in the last place:
/// sin x = x - x^3/6 + ..., cos x = 1 - x^2/2 + ..., and
/// e^x - 1 = x + x^2/2 + ... The series cannot be left to show that. Its
/// second term is below the double-double's precision, or underflows
/// beside a denormalized operand, and the sum is then exactly the first
/// term: no INEX2, and nothing for a directed rounding mode to round. The
/// M68040FPSP and M68060SP set INEX2 for such an operand as for any other,
/// and UNFL with it for a denormalized one (t_extdnrm).
fn tiny_operand(opmode: u16, x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> Option<FloatX80> {
    if x.is_nan() || x.is_inf() || x.is_zero() {
        return None;
    }
    // Below 2^bound the second term is under 2^-66 of the first: it is
    // x^2/2 of it at most where the first two terms differ by x^2, and
    // x/2 for e^x - 1 and ln(1 + x).
    let (bound, away, about_one) = match opmode {
        0x0E | 0x0A | 0x09 => (-33, false, false), // sin, atan, tanh
        0x0F | 0x0C | 0x02 | 0x0D => (-33, true, false), // tan, asin, sinh, atanh
        0x08 => (-66, !x.sign(), false),           // e^x - 1 is above x
        0x06 => (-66, x.sign(), false),            // ln(1 + x) is below x
        0x1D => (-33, false, true),                // cos
        0x19 => (-33, true, true),                 // cosh
        _ => return None,
    };
    if unbiased_exp(x) >= bound {
        return None;
    }
    let first_term = if about_one { one_x80() } else { x };
    let result = softfloat::round_inexact(first_term, away, ctx, f);
    // round_inexact rounds a value next to the first term, which is tiny
    // beside 2^-16383 (a biased exponent of 0 with the integer bit set) as
    // well. That operand is normalized, though: a 68060 and a 68882 set only
    // INEX2 for atan of it, and UNFL is for a denormalized operand.
    if !is_denormalized(x) {
        f.0 &= !ExcFlags::UNFL;
    }
    Some(result)
}

/// Denormalized: a biased exponent of 0 and the integer bit clear. A biased
/// exponent of 0 with the integer bit set is 2^-16383 and normalized.
fn is_denormalized(x: FloatX80) -> bool {
    x.biased_exp() == 0 && x.mantissa != 0 && x.mantissa >> 63 == 0
}

// ============================== exp family ===============================

/// exp(r) for a small |r| <= ln2/2 via the Maclaurin series, in Df.
fn exp_reduced(r: Df) -> Df {
    let mut term = Df::from_i32(1);
    let mut sum = Df::from_i32(1);
    let mut k = 1i32;
    loop {
        term = dd::div(dd::mul(term, r), Df::from_i32(k));
        sum = dd::add(sum, term);
        if dd::term_negligible(term, sum) || k > 60 {
            break;
        }
        k += 1;
    }
    sum
}

/// e^p for an arbitrary Df exponent `p`: reduce p = k*ln2 + r (|r| <= ln2/2),
/// then exp(p) = 2^k * exp(r).
fn exp_dd(p: Df) -> Df {
    let k = (p.hi.to_f64() * std::f64::consts::LOG2_E).round();
    let ki = k as i32;
    let r = dd::sub(p, dd::mul_x80(dd::consts().ln2, fx(k)));
    dd::mul_x80(exp_reduced(r), two_pow(ki))
}

/// Beyond this magnitude, e^x is too close to the limits of the extended range
/// for `exp_dd`, whose 2^k overflows to infinity or vanishes.
const EXP_RANGE_LIMIT: f64 = 11000.0;

/// e^x * 2^shift for a large |x|: scale last, so that an overflow or underflow
/// is rounded and reported as one.
fn exp_scaled(x: FloatX80, shift: i32, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    exp_scaled_df(Df::from_x80(x), x.to_f64(), shift, ctx, f)
}

/// The same for e^y, with `v` about the value of `y`, which only matters if
/// that is within the range.
fn exp_scaled_df(y: Df, v: f64, shift: i32, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    // Far outside the range the value does not matter any more.
    let v = v.clamp(-20000.0, 20000.0);
    let k = (v * std::f64::consts::LOG2_E).round();
    let m = if v.abs() < 20000.0 {
        let r = dd::sub(y, dd::mul_x80(dd::consts().ln2, fx(k)));
        exp_reduced(r).to_x80(RoundCtx::NEAREST_EXT, &mut noflags())
    } else {
        one_x80()
    };
    let r = softfloat::scale(m, k as i32 + shift, ctx, f);
    f.raise(ExcFlags::INEX2);
    if r.is_zero() {
        f.raise(ExcFlags::UNFL);
    }
    r
}

fn exp(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        return if x.sign() { FloatX80::zero(false) } else { x };
    }
    if x.is_zero() {
        return one_x80();
    }
    if x.to_f64().abs() > EXP_RANGE_LIMIT {
        return exp_scaled(x, 0, ctx, f);
    }
    exp_dd(Df::from_x80(x)).to_x80(ctx, f)
}

fn exp2(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        return if x.sign() { FloatX80::zero(false) } else { x };
    }
    if x.is_zero() {
        return one_x80();
    }
    let v = x.to_f64() * std::f64::consts::LN_2;
    if v.abs() > EXP_RANGE_LIMIT {
        return exp_scaled_df(dd::mul_x80(dd::consts().ln2, x), v, 0, ctx, f);
    }
    exp_dd(dd::mul_x80(dd::consts().ln2, x)).to_x80(ctx, f)
}

fn exp10(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        return if x.sign() { FloatX80::zero(false) } else { x };
    }
    if x.is_zero() {
        return one_x80();
    }
    let v = x.to_f64() * std::f64::consts::LN_10;
    if v.abs() > EXP_RANGE_LIMIT {
        return exp_scaled_df(dd::mul_x80(dd::consts().ln10, x), v, 0, ctx, f);
    }
    exp_dd(dd::mul_x80(dd::consts().ln10, x)).to_x80(ctx, f)
}

/// e^x - 1 as Df, accurate near 0 (direct series, no 1+ cancellation).
fn expm1_df(x: FloatX80) -> Df {
    if x.to_f64().abs() <= 0.5 {
        // Series sum_{k>=1} x^k/k!.
        let xd = Df::from_x80(x);
        let mut term = xd;
        let mut sum = xd;
        let mut k = 2i32;
        loop {
            term = dd::div(dd::mul(term, xd), Df::from_i32(k));
            sum = dd::add(sum, term);
            if dd::term_negligible(term, sum) || k > 60 {
                break;
            }
            k += 1;
        }
        sum
    } else {
        dd::sub(exp_dd(Df::from_x80(x)), Df::from_i32(1))
    }
}

fn expm1(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        return if x.sign() {
            softfloat::neg(one_x80())
        } else {
            x
        };
    }
    if x.is_zero() {
        return x; // expm1(+-0) = +-0
    }
    expm1_df(x).to_x80(ctx, f)
}

// ============================== log family ===============================

/// Shared special-case prologue for ln/log2/log10. Returns the special result,
/// or None if `x` is finite and positive (compute the logarithm).
fn log_special(x: FloatX80, f: &mut ExcFlags) -> Option<FloatX80> {
    if x.is_nan() {
        Some(nan_result(x, f))
    } else if x.is_zero() {
        f.raise(ExcFlags::DZ);
        Some(FloatX80::infinity(true)) // log(0) = -inf
    } else if x.sign() {
        f.raise(ExcFlags::OPERR);
        Some(FloatX80::default_nan()) // log(negative)
    } else if x.is_inf() {
        Some(x) // log(+inf) = +inf
    } else {
        None
    }
}

/// Multiply a Df by 2^n exactly (power-of-two scaling of both limbs).
fn scale_df(d: Df, n: i32) -> Df {
    Df {
        hi: softfloat::scale(d.hi, n, RoundCtx::NEAREST_EXT, &mut noflags()),
        lo: softfloat::scale(d.lo, n, RoundCtx::NEAREST_EXT, &mut noflags()),
    }
}

/// ln of a positive Df value, full double-double precision: x = f*2^e with
/// f in [sqrt(1/2), sqrt(2)), ln(x) = e*ln2 + 2*atanh((f-1)/(f+1)). Taking a
/// Df argument (not a rounded x80) is what keeps log1p/atanh faithful.
fn ln_df(x: Df) -> Df {
    let mut e = unbiased_exp(x.hi);
    let mut f = scale_df(x, -e);
    if f.hi.to_f64() > std::f64::consts::SQRT_2 {
        f = scale_df(f, -1);
        e += 1;
    }
    let one = Df::from_i32(1);
    let s = dd::div(dd::sub(f, one), dd::add(f, one));
    dd::add(
        dd::mul_x80(dd::consts().ln2, fx(e as f64)),
        dd::mul_x80(dd::atanh_small(s), fx(2.0)),
    )
}

fn ln_dd(x: FloatX80) -> Df {
    ln_df(Df::from_x80(x))
}

fn ln(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if let Some(r) = log_special(x, f) {
        return r;
    }
    ln_dd(x).to_x80(ctx, f)
}

fn log2(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if let Some(r) = log_special(x, f) {
        return r;
    }
    dd::mul(ln_dd(x), dd::consts().log2e).to_x80(ctx, f)
}

fn log10(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if let Some(r) = log_special(x, f) {
        return r;
    }
    dd::mul(ln_dd(x), dd::consts().log10e).to_x80(ctx, f)
}

/// ln(1+x), accurate near 0.
fn log1p(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_zero() {
        return x; // log1p(+-0) = +-0
    }
    if x.is_inf() {
        return if x.sign() {
            f.raise(ExcFlags::OPERR);
            FloatX80::default_nan()
        } else {
            x
        };
    }
    let one = one_x80();
    // x <= -1: domain boundary.
    if x.sign() {
        let cmp = softfloat::compare(x, softfloat::neg(one), &mut noflags());
        if cmp == FpCmp::Equal {
            f.raise(ExcFlags::DZ);
            return FloatX80::infinity(true);
        }
        if cmp == FpCmp::Less {
            f.raise(ExcFlags::OPERR);
            return FloatX80::default_nan();
        }
    }
    let d = if x.to_f64().abs() <= 0.5 {
        // ln(1+x) = 2*atanh(x/(x+2)), no 1+x cancellation.
        let xd = Df::from_x80(x);
        let s = dd::div(xd, dd::add_x80(xd, fx(2.0)));
        dd::mul_x80(dd::atanh_small(s), fx(2.0))
    } else {
        ln_df(dd::add_x80(Df::from_x80(x), one))
    };
    d.to_x80(ctx, f)
}

// ============================== trig family ==============================

/// Reduce x = k*(pi/2) + r with |r| <= pi/4, returning (k, r). `k` is only
/// meaningful modulo 4. Every finite operand reduces accurately, so results
/// stay in [-1, +1] and are correct for any argument: Motorola only promises
/// the range for arguments above about 10^20 (M68000PM FSIN), and these
/// results are not chip-bit-exact anyway.
fn reduce_quadrant(x: FloatX80) -> (i64, Df) {
    if !x.is_zero() && unbiased_exp(x) >= 0 {
        return reduce_payne_hanek(x);
    }
    // |x| < 1: at most one multiple of pi/2, so a Df pi/2 is plenty.
    let kf = (x.to_f64() * std::f64::consts::FRAC_2_PI).round();
    let k = kf as i64;
    let r = dd::sub(Df::from_x80(x), dd::mul_x80(dd::consts().pi_2, fx(kf)));
    (k, r)
}

/// Bits of 2/pi multiplied by the operand in Payne-Hanek reduction. The
/// truncation error is below 2^-254 of a quadrant, so an operand keeps 128
/// significant bits of r unless it lies within about 2^-126 of a multiple of
/// pi/2, far closer than a 64-bit significand is expected to get.
const PH_WINDOW_LIMBS: usize = 5;

/// `count` bits of `limbs` (little-endian) ending just below bit `top`,
/// left-justified in a u64. Bits below bit 0 read as zero.
fn ph_bits(limbs: &[u64], top: i32, count: u32) -> u64 {
    let mut v = 0u64;
    for i in 1..=count as i32 {
        let bit = top - i;
        v <<= 1;
        if bit >= 0 {
            v |= (limbs[(bit / 64) as usize] >> (bit % 64)) & 1;
        }
    }
    v << (64 - count)
}

/// Payne-Hanek reduction for |x| >= 1: multiply the 64-bit significand by the
/// window of 2/pi that matters. Bits of 2/pi above the window only contribute
/// multiples of 4 (whole turns), so even the largest operand needs no more
/// working precision than the smallest.
fn reduce_payne_hanek(x: FloatX80) -> (i64, Df) {
    let ax = softfloat::abs(x);
    let m = softfloat::getman(ax, &mut noflags()).mantissa;
    let e = unbiased_exp(ax) - 63; // |x| = m * 2^e

    // T = bits s+1..=s+W of 2/pi, s chosen so that every higher bit of 2/pi
    // has weight 2^(e-i) >= 4 once multiplied by 2^e.
    let s = (e - 2).max(0) as usize;
    let word = s / 64;
    let off = (s % 64) as u32;
    let mut t = [0u64; PH_WINDOW_LIMBS]; // little-endian
    for i in 0..PH_WINDOW_LIMBS {
        let w = TWO_OVER_PI[word + i];
        let next = TWO_OVER_PI[word + i + 1];
        t[PH_WINDOW_LIMBS - 1 - i] = if off == 0 {
            w
        } else {
            (w << off) | (next >> (64 - off))
        };
    }

    // p = m * T. One spare limb keeps the two quadrant bits in range when
    // e < 0 pushes the binary point above the product.
    let mut p = [0u64; PH_WINDOW_LIMBS + 2];
    let mut carry = 0u128;
    for i in 0..PH_WINDOW_LIMBS {
        let v = t[i] as u128 * m as u128 + carry;
        p[i] = v as u64;
        carry = v >> 64;
    }
    p[PH_WINDOW_LIMBS] = carry as u64;

    // x * 2/pi = p * 2^(e - s - W): the binary point sits above bit `point`.
    let point = (PH_WINDOW_LIMBS as i32 * 64) - (e - s as i32);
    let bit = |n: i32| (p[(n / 64) as usize] >> (n % 64)) & 1;
    let mut q = (bit(point) | (bit(point + 1) << 1)) as i64;

    // Fraction below the binary point, as a signed distance to the nearest
    // quadrant.
    let w = (point as usize).div_ceil(64);
    let mut frac = [0u64; PH_WINDOW_LIMBS + 2];
    frac[..w].copy_from_slice(&p[..w]);
    if point % 64 != 0 {
        frac[w - 1] &= (1u64 << (point % 64)) - 1;
    }
    let negative = bit(point - 1) == 1;
    if negative {
        q += 1;
        // frac = 2^point - frac
        let mut borrow = 0u64;
        for limb in frac.iter_mut().take(w) {
            let (v, b1) = 0u64.overflowing_sub(*limb);
            let (v, b2) = v.overflowing_sub(borrow);
            *limb = v;
            borrow = (b1 | b2) as u64;
        }
        if point % 64 != 0 {
            frac[w - 1] &= (1u64 << (point % 64)) - 1;
        }
    }

    // Normalise the fraction into a Df, then multiply by pi/2.
    let top = frac.iter().enumerate().rev().find(|(_, l)| **l != 0);
    let r = match top {
        None => Df::from_x80(FloatX80::zero(false)),
        Some((i, l)) => {
            let msb = i as i32 * 64 + 64 - l.leading_zeros() as i32; // one past the top bit
            let hi = ph_bits(&frac, msb, 64);
            let lo = ph_bits(&frac, msb - 64, 64);
            let limb = |v: u64, shift: i32| {
                softfloat::scale(
                    softfloat::from_u64(v, false),
                    shift,
                    RoundCtx::NEAREST_EXT,
                    &mut noflags(),
                )
            };
            let f = dd::add_x80(
                Df::from_x80(limb(hi, msb - 64 - point)),
                limb(lo, msb - 128 - point),
            );
            dd::mul(f, dd::consts().pi_2)
        }
    };
    let r = if negative { r.neg() } else { r };
    if x.sign() { (-q, r.neg()) } else { (q, r) }
}

/// sin(r) and cos(r) for |r| <= pi/4 via their Maclaurin series, in Df.
fn sin_cos_kernel(r: Df) -> (Df, Df) {
    let neg_r2 = dd::sqr(r).neg();
    // sin(r) = r - r^3/3! + ...
    let mut t = r;
    let mut s = r;
    let mut k = 1i32;
    loop {
        t = dd::div(dd::mul(t, neg_r2), Df::from_i32((2 * k) * (2 * k + 1)));
        s = dd::add(s, t);
        if dd::term_negligible(t, s) || k > 30 {
            break;
        }
        k += 1;
    }
    // cos(r) = 1 - r^2/2! + ...
    let mut tc = Df::from_i32(1);
    let mut c = Df::from_i32(1);
    let mut k = 1i32;
    loop {
        tc = dd::div(dd::mul(tc, neg_r2), Df::from_i32((2 * k - 1) * (2 * k)));
        c = dd::add(c, tc);
        if dd::term_negligible(tc, c) || k > 30 {
            break;
        }
        k += 1;
    }
    (s, c)
}

/// (sin x, cos x) as Df, plus quadrant handling; specials return Df NaN/etc.
fn sin_cos_df(x: FloatX80, f: &mut ExcFlags) -> Option<(Df, Df)> {
    if x.is_nan() {
        let n = Df::from_x80(nan_result(x, f));
        return Some((n, n));
    }
    if x.is_inf() {
        f.raise(ExcFlags::OPERR);
        let n = Df::from_x80(FloatX80::default_nan());
        return Some((n, n));
    }
    if x.is_zero() {
        return Some((Df::from_x80(x), Df::from_i32(1))); // sin(+-0)=+-0, cos=1
    }
    let (k, r) = reduce_quadrant(x);
    let (sr, cr) = sin_cos_kernel(r);
    let q = ((k % 4) + 4) % 4;
    Some(match q {
        0 => (sr, cr),
        1 => (cr, sr.neg()),
        2 => (sr.neg(), cr.neg()),
        _ => (cr.neg(), sr),
    })
}

fn sin_cos_x80(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> (FloatX80, FloatX80) {
    let (s, c) = sin_cos_df(x, f).unwrap();
    // A Df -0 rounds to +0 (hi + lo), but sin(-0) must be -0.
    let sin = if x.is_zero() { x } else { s.to_x80(ctx, f) };
    (sin, c.to_x80(ctx, f))
}

fn sin(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_zero() {
        return x; // sin(+-0) = +-0
    }
    let (s, _) = sin_cos_df(x, f).unwrap();
    s.to_x80(ctx, f)
}

fn cos(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    let (_, c) = sin_cos_df(x, f).unwrap();
    c.to_x80(ctx, f)
}

fn tan(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    if x.is_zero() {
        return x; // tan(+-0) = +-0
    }
    let (k, r) = reduce_quadrant(x);
    let (sr, cr) = sin_cos_kernel(r);
    // tan = sin/cos; with the quadrant this is sr/cr (even q) or -cr/sr (odd q).
    let t = if k & 1 == 0 {
        dd::div(sr, cr)
    } else {
        dd::div(cr, sr).neg()
    };
    t.to_x80(ctx, f)
}

// ============================== inverse trig =============================

/// sqrt of a Df via one Newton refinement of the 64-bit seed.
fn sqrt_df(v: Df) -> Df {
    if v.hi.is_zero() {
        return v;
    }
    let x0 = softfloat::sqrt(v.hi, RoundCtx::NEAREST_EXT, &mut noflags());
    let q = dd::div(v, Df::from_x80(x0));
    dd::mul_x80(dd::add_x80(q, x0), fx(0.5))
}

/// atan as a Df: reduce |a| to <= 0.3 via reciprocal (|a|>1) and the
/// half-angle identity atan(a) = 2*atan(a/(1+sqrt(1+a^2))), then series.
fn atan_df(x: Df) -> Df {
    let neg = x.hi.sign();
    let ax = if neg { x.neg() } else { x };
    let (mut a, comp) = if ax.hi.to_f64() > 1.0 {
        (dd::recip(ax), true)
    } else {
        (ax, false)
    };
    let mut halvings = 0u32;
    while a.hi.to_f64() > 0.3 {
        let s = sqrt_df(dd::add_x80(dd::sqr(a), fx(1.0)));
        a = dd::div(a, dd::add_x80(s, fx(1.0)));
        halvings += 1;
    }
    let mut r = dd::atan_small(a);
    for _ in 0..halvings {
        r = dd::mul_x80(r, fx(2.0));
    }
    if comp {
        r = dd::sub(dd::consts().pi_2, r);
    }
    if neg { r.neg() } else { r }
}

fn atan(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_zero() {
        return x; // atan(+-0) = +-0
    }
    if x.is_inf() {
        let pi2 = dd::consts().pi_2;
        return if x.sign() { pi2.neg() } else { pi2 }.to_x80(ctx, f);
    }
    atan_df(Df::from_x80(x)).to_x80(ctx, f)
}

/// True if |x| > 1 (for domain checks).
fn abs_gt_one(x: FloatX80) -> bool {
    softfloat::compare(softfloat::abs(x), one_x80(), &mut noflags()) == FpCmp::Greater
}
fn abs_eq_one(x: FloatX80) -> bool {
    softfloat::compare(softfloat::abs(x), one_x80(), &mut noflags()) == FpCmp::Equal
}

fn asin(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_zero() {
        return x; // asin(+-0) = +-0
    }
    if x.is_inf() || abs_gt_one(x) {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    if abs_eq_one(x) {
        let pi2 = dd::consts().pi_2;
        return if x.sign() { pi2.neg() } else { pi2 }.to_x80(ctx, f);
    }
    // asin(x) = atan(x / sqrt(1 - x^2)).
    let xd = Df::from_x80(x);
    let denom = sqrt_df(dd::sub(Df::from_i32(1), dd::sqr(xd)));
    atan_df(dd::div(xd, denom)).to_x80(ctx, f)
}

fn acos(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() || abs_gt_one(x) {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    if abs_eq_one(x) {
        // acos(1) = +0, acos(-1) = pi.
        return if x.sign() {
            dd::consts().pi.to_x80(ctx, f)
        } else {
            FloatX80::zero(false)
        };
    }
    // acos(x) = pi/2 - asin(x).
    let xd = Df::from_x80(x);
    let denom = sqrt_df(dd::sub(Df::from_i32(1), dd::sqr(xd)));
    let asin_df = atan_df(dd::div(xd, denom));
    dd::sub(dd::consts().pi_2, asin_df).to_x80(ctx, f)
}

// ============================== hyperbolic ===============================

fn sinh(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() || x.is_zero() {
        return x; // sinh(+-inf)=+-inf, sinh(+-0)=+-0
    }
    if x.to_f64().abs() > EXP_RANGE_LIMIT {
        // sinh(x) = sign(x) * e^|x| / 2 this far out.
        let r = exp_scaled(softfloat::abs(x), -1, ctx, f);
        return if x.sign() { softfloat::neg(r) } else { r };
    }
    let d = if x.to_f64().abs() <= 0.5 {
        // Series sum_{k>=0} x^(2k+1)/(2k+1)!.
        let xd = Df::from_x80(x);
        let x2 = dd::sqr(xd);
        let mut term = xd;
        let mut sum = xd;
        let mut k = 1i32;
        loop {
            term = dd::div(dd::mul(term, x2), Df::from_i32((2 * k) * (2 * k + 1)));
            sum = dd::add(sum, term);
            if dd::term_negligible(term, sum) || k > 40 {
                break;
            }
            k += 1;
        }
        sum
    } else {
        let e = exp_dd(Df::from_x80(x));
        dd::mul_x80(dd::sub(e, dd::recip(e)), fx(0.5))
    };
    d.to_x80(ctx, f)
}

fn cosh(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_inf() {
        return FloatX80::infinity(false); // cosh(+-inf) = +inf
    }
    if x.is_zero() {
        return one_x80();
    }
    if x.to_f64().abs() > EXP_RANGE_LIMIT {
        // cosh(x) = e^|x| / 2 this far out.
        return exp_scaled(softfloat::abs(x), -1, ctx, f);
    }
    let e = exp_dd(Df::from_x80(x));
    dd::mul_x80(dd::add(e, dd::recip(e)), fx(0.5)).to_x80(ctx, f)
}

fn tanh(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_zero() {
        return x; // tanh(+-0) = +-0
    }
    if x.is_inf() || x.to_f64().abs() > 32.0 {
        // |x| large: tanh -> +-1 (inexact for finite x).
        let one = if x.sign() {
            softfloat::neg(one_x80())
        } else {
            one_x80()
        };
        if !x.is_inf() {
            f.raise(ExcFlags::INEX2);
        }
        return one;
    }
    // tanh(x) = (e^{2x}-1)/(e^{2x}+1) = u/(u+2), u = expm1(2x).
    let two_x = softfloat::scale(x, 1, RoundCtx::NEAREST_EXT, &mut noflags());
    let u = expm1_df(two_x);
    dd::div(u, dd::add_x80(u, fx(2.0))).to_x80(ctx, f)
}

fn atanh(x: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if x.is_nan() {
        return nan_result(x, f);
    }
    if x.is_zero() {
        return x; // atanh(+-0) = +-0
    }
    if abs_eq_one(x) {
        f.raise(ExcFlags::DZ);
        return FloatX80::infinity(x.sign()); // atanh(+-1) = +-inf
    }
    if x.is_inf() || abs_gt_one(x) {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    let d = if x.to_f64().abs() <= 0.5 {
        dd::atanh_small(Df::from_x80(x))
    } else {
        // atanh(x) = 0.5 * ln((1+x)/(1-x)); ln of the Df ratio (not a rounded
        // x80) keeps the result faithful.
        let xd = Df::from_x80(x);
        let arg = dd::div(dd::add_x80(xd, fx(1.0)), dd::sub(Df::from_i32(1), xd));
        dd::mul_x80(ln_df(arg), fx(0.5))
    };
    d.to_x80(ctx, f)
}

// ============================== dispatch =================================

/// Evaluate a single-operand transcendental by opmode, rounding to `ctx` and
/// accumulating exceptions into `f`. Returns `None` if the opmode is not a
/// transcendental.
pub fn eval_unary(opmode: u16, src: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> Option<FloatX80> {
    if let Some(r) = tiny_operand(opmode, src, ctx, f) {
        return Some(r);
    }
    let r = match opmode {
        // Extended-precision kernels.
        0x10 => exp(src, ctx, f),
        0x08 => expm1(src, ctx, f),
        0x11 => exp2(src, ctx, f),
        0x12 => exp10(src, ctx, f),
        0x14 => ln(src, ctx, f),
        0x06 => log1p(src, ctx, f),
        0x15 => log10(src, ctx, f),
        0x16 => log2(src, ctx, f),
        0x0E => sin(src, ctx, f),
        0x1D => cos(src, ctx, f),
        0x0F => tan(src, ctx, f),
        0x0C => asin(src, ctx, f),
        0x1C => acos(src, ctx, f),
        0x0A => atan(src, ctx, f),
        0x02 => sinh(src, ctx, f),
        0x19 => cosh(src, ctx, f),
        0x09 => tanh(src, ctx, f),
        0x0D => atanh(src, ctx, f),
        _ => return None,
    };
    Some(r)
}

/// FSINCOS: sine and cosine of the same operand.
pub fn sincos(src: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> (FloatX80, FloatX80) {
    if let Some(sin) = tiny_operand(0x0E, src, ctx, f) {
        let cos = tiny_operand(0x1D, src, ctx, f).unwrap_or_else(one_x80);
        return (sin, cos);
    }
    sin_cos_x80(src, ctx, f)
}

/// Result of FMOD/FREM: the exact remainder, the low 7 bits of |quotient|,
/// and the quotient's sign.
pub struct Remainder {
    pub value: FloatX80,
    pub quotient: u8,
    pub quotient_sign: bool,
}

/// Exact extended remainder of `dst` by `src`. `ieee` selects FREM (quotient
/// rounded to nearest) vs FMOD (truncated quotient). The remainder is computed
/// exactly by shift-subtract long division of the significands.
pub fn remainder(dst: FloatX80, src: FloatX80, ieee: bool, f: &mut ExcFlags) -> Remainder {
    let none = |v: FloatX80| Remainder {
        value: v,
        quotient: 0,
        quotient_sign: false,
    };
    if dst.is_nan() || src.is_nan() {
        // The destination NaN is the result when both are NaNs, but a
        // signaling NaN in either operand raises SNAN.
        return none(softfloat::propagate_nan(dst, src, f));
    }
    let quotient_sign = dst.sign() ^ src.sign();
    if dst.is_inf() || src.is_zero() {
        f.raise(ExcFlags::OPERR);
        return none(FloatX80::default_nan());
    }
    if src.is_inf() || dst.is_zero() {
        // x mod inf = x; 0 mod y = 0.
        return Remainder {
            value: dst,
            quotient: 0,
            quotient_sign,
        };
    }

    let ax = softfloat::abs(dst);
    let ay = softfloat::abs(src);
    let ex = unbiased_exp(ax);
    let ey = unbiased_exp(ay);
    let mx = softfloat::getman(ax, &mut noflags()).mantissa;
    let my = softfloat::getman(ay, &mut noflags()).mantissa as u128;
    let ediff = ex - ey;

    // Floor remainder magnitude `rfloor` and the low bits of floor(|x|/|y|).
    let (mut rfloor, mut q, rem_int): (FloatX80, u64, u128) = if ediff < 0 {
        (ax, 0, u128::MAX) // |x| < |y|: remainder = |x| (rem_int unused)
    } else {
        // Long division of M = mx << ediff by my (bit by bit, MSB first).
        let mut rem: u128 = 0;
        let mut q: u64 = 0;
        let total = 64 + ediff;
        for j in (0..total).rev() {
            rem <<= 1;
            if j >= ediff {
                rem |= ((mx >> (j - ediff)) & 1) as u128;
            }
            q <<= 1;
            if rem >= my {
                rem -= my;
                q |= 1;
            }
        }
        let rv = if rem == 0 {
            FloatX80::zero(false)
        } else {
            softfloat::scale(
                softfloat::from_u64(rem as u64, false),
                ey - 63,
                RoundCtx::NEAREST_EXT,
                &mut noflags(),
            )
        };
        (rv, q, rem)
    };

    let mut sign = dst.sign();
    if ieee {
        // FREM: round the quotient to nearest. Compare 2*rfloor with |y|.
        let two_rfloor = softfloat::scale(rfloor, 1, RoundCtx::NEAREST_EXT, &mut noflags());
        let c = softfloat::compare(two_rfloor, ay, &mut noflags());
        let round_up = c == FpCmp::Greater || (c == FpCmp::Equal && (q & 1) == 1);
        if round_up {
            q += 1;
            // Remainder crosses zero: new magnitude = |y| - rfloor, sign flips.
            rfloor = if ediff >= 0 && rem_int != u128::MAX {
                let nr = my - rem_int;
                softfloat::scale(
                    softfloat::from_u64(nr as u64, false),
                    ey - 63,
                    RoundCtx::NEAREST_EXT,
                    &mut noflags(),
                )
            } else {
                softfloat::sub(ay, rfloor, RoundCtx::NEAREST_EXT, &mut noflags())
            };
            sign = !sign;
        }
    }

    let value = if rfloor.is_zero() {
        FloatX80::zero(sign)
    } else if sign {
        softfloat::neg(rfloor)
    } else {
        rfloor
    };
    Remainder {
        value,
        quotient: (q & 0x7F) as u8,
        quotient_sign,
    }
}

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

    fn rn() -> RoundCtx {
        RoundCtx::NEAREST_EXT
    }
    fn ev(opmode: u16, x: f64) -> f64 {
        eval_unary(opmode, FloatX80::from_f64(x), rn(), &mut noflags())
            .unwrap()
            .to_f64()
    }
    fn close(a: f64, b: f64, rel: f64) -> bool {
        if b == 0.0 {
            a.abs() < rel
        } else {
            ((a - b) / b).abs() < rel
        }
    }

    #[test]
    fn exp_log_anchors() {
        // Exact / near-exact anchors.
        assert_eq!(ev(0x10, 0.0), 1.0); // exp(0)
        assert_eq!(ev(0x14, 1.0), 0.0); // ln(1)
        assert!(close(ev(0x11, 10.0), 1024.0, 1e-18)); // 2^10
        assert!(close(ev(0x12, 3.0), 1000.0, 1e-18)); // 10^3
        assert!(close(ev(0x16, 1024.0), 10.0, 1e-18)); // log2(1024)
        assert!(close(ev(0x15, 1000.0), 3.0, 1e-18)); // log10(1000)
        // exp(1) matches the e constant ROM pattern to within 1 ULP (faithful
        // rounding; last-bit-correct would need a TMD/Ziv test beyond 128 bits).
        let e = exp(fx(1.0), rn(), &mut noflags());
        let rom = softfloat::const_rom(0x0C);
        assert_eq!(e.sign_exp, rom.sign_exp);
        assert!(
            (e.mantissa as i128 - rom.mantissa as i128).abs() <= 1,
            "exp(1) {e:?} vs {rom:?}"
        );
    }

    #[test]
    fn exp_log_identities() {
        // exp(ln x) == x and ln(exp x) == x to ~2^-62.
        for &x in &[0.5_f64, 1.5, 2.0, 7.3, 100.0, 1e8] {
            let lx = ln(fx(x), rn(), &mut noflags());
            assert!(
                close(exp(lx, rn(), &mut noflags()).to_f64(), x, 1e-18),
                "exp(ln {x})"
            );
        }
        for &x in &[-3.0_f64, -0.5, 0.0, 0.7, 5.0] {
            let ex = exp(fx(x), rn(), &mut noflags());
            assert!(
                close(ln(ex, rn(), &mut noflags()).to_f64(), x, 1e-15),
                "ln(exp {x})"
            );
        }
        // 2^x == exp(x*ln2).
        for &x in &[-4.0_f64, 0.3, 1.0, 13.5] {
            assert!(close(ev(0x11, x), 2.0_f64.powf(x), 1e-15), "2^{x}");
        }
    }

    #[test]
    fn expm1_log1p_near_zero() {
        for &x in &[1e-6_f64, -1e-7, 0.01, -0.02, 1e-10] {
            assert!(close(ev(0x08, x), x.exp_m1(), 1e-14), "expm1 {x}");
            assert!(close(ev(0x06, x), x.ln_1p(), 1e-14), "log1p {x}");
        }
    }

    #[test]
    fn trig_anchors_and_identities() {
        assert_eq!(ev(0x0E, 0.0), 0.0); // sin(0)
        assert_eq!(ev(0x1D, 0.0), 1.0); // cos(0)
        assert_eq!(ev(0x0F, 0.0), 0.0); // tan(0)
        // sin^2 + cos^2 == 1 across quadrants and a large argument.
        for &x in &[0.3_f64, 1.2, 3.0, -2.5, 7.0, 100.0, 1000.0] {
            let s = ev(0x0E, x);
            let c = ev(0x1D, x);
            assert!((s * s + c * c - 1.0).abs() < 1e-15, "sin^2+cos^2 at {x}");
            // tan == sin/cos.
            let t = ev(0x0F, x);
            assert!(close(t, s / c, 1e-14), "tan at {x}");
            // agreement with libm to ~f64 precision.
            assert!((s - x.sin()).abs() < 1e-14, "sin {x}");
            assert!((c - x.cos()).abs() < 1e-14, "cos {x}");
        }
    }

    /// True when `got` is within one ULP of `want` (sign_exp, mantissa).
    fn near(got: FloatX80, want: (u16, u64)) -> bool {
        got.sign_exp == want.0 && got.mantissa.abs_diff(want.1) <= 1
    }

    #[test]
    fn trig_large_arguments_match_references() {
        // References: mpmath at 17000 bits, rounded to 64-bit extended.
        // (operand, sin, cos, tan)
        type W = (u16, u64);
        let cases: [(FloatX80, W, W, W); 4] = [
            (
                fx(1e22),
                (0xBFFE, 0xDA29D5BB5F9CB87D),
                (0x3FFE, 0x85F167780E479C9A),
                (0xBFFF, 0xD07BCE0DB592BBA5),
            ),
            (
                fx(9223372036854775808.0), // 2^63
                (0x3FFE, 0xFFFB6FEA16E2A218),
                (0x3FF8, 0xC1551BAD9E19F383),
                (0x4005, 0xA97A873ABCA0E600),
            ),
            (
                fx(f64::MAX),
                (0x3FF7, 0xA297E4C59A74B5B1),
                (0xBFFE, 0xFFFF31767D5BA9E0),
                (0xBFF7, 0xA29867F394A41DC7),
            ),
            (
                FloatX80 {
                    sign_exp: 0x7FFE,
                    mantissa: u64::MAX,
                },
                (0x3FFE, 0xFDFD9D4B6D0E5F7C),
                (0xBFFC, 0x800BBD0061D4F543),
                (0xC001, 0xFDE654994CE86FDB),
            ),
        ];
        for (x, s, c, t) in cases {
            assert!(near(sin(x, rn(), &mut noflags()), s), "sin {x:?}");
            assert!(near(cos(x, rn(), &mut noflags()), c), "cos {x:?}");
            assert!(near(tan(x, rn(), &mut noflags()), t), "tan {x:?}");
        }
    }

    #[test]
    fn trig_results_stay_in_range() {
        let mut e = 0;
        while e < 16383 {
            let x = FloatX80 {
                sign_exp: 0x3FFF + e as u16,
                mantissa: 0xC90F_DAA2_2168_C235 ^ (e as u64) << 7,
            };
            let (s, c) = sincos(x, rn(), &mut noflags());
            assert!(s.to_f64().abs() <= 1.0 && c.to_f64().abs() <= 1.0, "{x:?}");
            let sum = s.to_f64() * s.to_f64() + c.to_f64() * c.to_f64();
            assert!((sum - 1.0).abs() < 1e-14, "sin^2+cos^2 at {x:?}");
            e += 97;
        }
    }

    #[test]
    fn exp_family_at_the_limits_of_the_range() {
        let mut f = ExcFlags::default();
        for v in [11500.0, 20000.0, 1e300, f64::MAX] {
            assert!(exp(fx(v), rn(), &mut f).is_inf(), "exp {v}");
            assert!(sinh(fx(v), rn(), &mut f).is_inf(), "sinh {v}");
            assert!(cosh(fx(v), rn(), &mut f).is_inf(), "cosh {v}");
            assert!(sinh(fx(-v), rn(), &mut f).sign(), "sinh {}", -v);
            assert!(exp(fx(-v), rn(), &mut f).is_zero(), "exp {}", -v);
        }
        assert_ne!(f.0 & ExcFlags::OVFL, 0);
        assert_ne!(f.0 & ExcFlags::UNFL, 0);

        // Still in range, close to the top: e^11356 is about 2^16383.24.
        let e = exp(fx(11356.0), rn(), &mut noflags());
        assert_eq!(e.sign_exp, 0x7FFE);
    }

    /// The neighbour of a finite nonzero `x` one unit in the last place
    /// further from zero, or nearer to it.
    fn neighbour(x: FloatX80, away: bool) -> FloatX80 {
        let (sign_exp, m) = x.to_extended();
        let (sign, exp) = (sign_exp & 0x8000, sign_exp & 0x7FFF);
        let (exp, m) = if away {
            match m.checked_add(1) {
                Some(m) => (exp, m),
                None => (exp + 1, 1 << 63),
            }
        } else if m == 1 << 63 && exp > 0 {
            (exp - 1, u64::MAX)
        } else {
            (exp, m - 1)
        };
        FloatX80::from_extended(sign | exp, m)
    }

    #[test]
    fn a_tiny_operand_is_inexact_and_rounds_off_the_first_term() {
        // (opmode, the value is further from zero than a positive operand,
        // and than a negative one).
        let ops = [
            (0x0E, false, false), // sin
            (0x0A, false, false), // atan
            (0x09, false, false), // tanh
            (0x0F, true, true),   // tan
            (0x0C, true, true),   // asin
            (0x02, true, true),   // sinh
            (0x0D, true, true),   // atanh
            (0x08, true, false),  // e^x - 1
            (0x06, false, true),  // ln(1 + x)
        ];
        // Denormalized, 2^-16383 (a biased exponent of 0 with the integer
        // bit set), the smallest with a biased exponent of 1, one in the
        // middle of the range and one just below 2^-66.
        let operands = [
            (0x0000, 0x4000_0000_0000_0000),
            (0x0000, 0x0000_0000_0000_0001),
            (0x0000, 0x8000_0000_0000_0000),
            (0x0001, 0x8000_0000_0000_0000),
            (0x3000, 0xC000_0000_0000_0001),
            (0x3FBC, 0xFFFF_FFFF_FFFF_FFFF),
        ];
        let modes = [
            RoundMode::Nearest,
            RoundMode::Zero,
            RoundMode::NegInf,
            RoundMode::PosInf,
        ];
        for (opmode, away_pos, away_neg) in ops {
            for (exp, m) in operands {
                for sign in [0, 0x8000] {
                    for mode in modes {
                        let x = FloatX80::from_extended(sign | exp, m);
                        let away = if sign == 0 { away_pos } else { away_neg };
                        // Only a mode that rounds the way the value lies
                        // moves the result off the operand.
                        let outward = match mode {
                            RoundMode::Nearest => false,
                            RoundMode::Zero => !away,
                            RoundMode::PosInf => away == (sign == 0),
                            RoundMode::NegInf => away == (sign != 0),
                        };
                        let want = if outward { neighbour(x, away) } else { x };
                        let unfl = if is_denormalized(x) {
                            ExcFlags::UNFL
                        } else {
                            0
                        };
                        let ctx = RoundCtx {
                            mode,
                            ..RoundCtx::NEAREST_EXT
                        };
                        let mut f = noflags();
                        let got = eval_unary(opmode, x, ctx, &mut f).unwrap();
                        let what = format!("opmode {opmode:#x} of {:x?} {mode:?}", x.to_extended());
                        assert_eq!(got.to_extended(), want.to_extended(), "{what}");
                        assert_eq!(f.0, ExcFlags::INEX2 | unfl, "{what}");
                    }
                }
            }
        }
    }

    #[test]
    fn cos_and_cosh_of_a_tiny_operand_are_inexactly_one() {
        let one = one_x80();
        for (exp, m) in [
            (0x0000, 0x0000_0000_0000_0001),
            (0x8001, 0x8000_0000_0000_0000),
            (0x3FDD, 0xFFFF_FFFF_FFFF_FFFF),
        ] {
            let x = FloatX80::from_extended(exp, m);
            // cos x is just below 1 and cosh x just above it.
            for (opmode, mode, want) in [
                (0x1D, RoundMode::Nearest, one),
                (0x1D, RoundMode::Zero, neighbour(one, false)),
                (0x1D, RoundMode::NegInf, neighbour(one, false)),
                (0x1D, RoundMode::PosInf, one),
                (0x19, RoundMode::Nearest, one),
                (0x19, RoundMode::Zero, one),
                (0x19, RoundMode::NegInf, one),
                (0x19, RoundMode::PosInf, neighbour(one, true)),
            ] {
                let ctx = RoundCtx {
                    mode,
                    ..RoundCtx::NEAREST_EXT
                };
                let mut f = noflags();
                let got = eval_unary(opmode, x, ctx, &mut f).unwrap();
                let what = format!("opmode {opmode:#x} of {:x?} {mode:?}", x.to_extended());
                assert_eq!(got.to_extended(), want.to_extended(), "{what}");
                assert_eq!(f.0, ExcFlags::INEX2, "{what}");
            }
        }
        // FSINCOS takes both from the same operand.
        let x = FloatX80::from_extended(0x8000, 0x4000_0000_0000_0000);
        let mut f = noflags();
        let (s, c) = sincos(x, rn(), &mut f);
        assert_eq!(s.to_extended(), x.to_extended());
        assert_eq!(c.to_extended(), one.to_extended());
        assert_eq!(f.0, ExcFlags::INEX2 | ExcFlags::UNFL);
    }

    #[test]
    fn trig_signed_zero() {
        let nz = FloatX80::zero(true);
        assert!(sin(nz, rn(), &mut noflags()).sign());
        assert!(sincos(nz, rn(), &mut noflags()).0.sign());
        assert_eq!(cos(nz, rn(), &mut noflags()).to_f64(), 1.0);
    }

    #[test]
    fn sincos_pair() {
        let (s, c) = sincos(fx(1.0), rn(), &mut noflags());
        assert!((s.to_f64() - 1.0_f64.sin()).abs() < 1e-15);
        assert!((c.to_f64() - 1.0_f64.cos()).abs() < 1e-15);
    }

    #[test]
    fn inverse_trig() {
        // atan(1)*4 == pi.
        assert!(close(ev(0x0A, 1.0) * 4.0, std::f64::consts::PI, 1e-15));
        assert_eq!(ev(0x0A, 0.0), 0.0);
        // asin(sin r) == r, acos(cos r) == r over the principal range.
        for &x in &[-0.9_f64, -0.4, 0.0, 0.25, 0.8, 0.999] {
            assert!(close(ev(0x0C, x.sin()), x, 1e-13), "asin(sin {x})");
        }
        for &x in &[0.1_f64, 0.7, 1.5, 3.0] {
            assert!(close(ev(0x1C, x.cos()), x, 1e-13), "acos(cos {x})");
        }
        // libm agreement.
        for &x in &[-5.0_f64, -0.3, 0.6, 42.0] {
            assert!((ev(0x0A, x) - x.atan()).abs() < 1e-14, "atan {x}");
        }
        // domain errors.
        let mut f = ExcFlags::default();
        assert!(asin(fx(2.0), rn(), &mut f).is_nan());
        assert!(f.has(ExcFlags::OPERR));
    }

    #[test]
    fn hyperbolic() {
        for &x in &[-3.0_f64, -0.3, 0.0, 0.2, 1.0, 5.0] {
            assert!(
                (ev(0x02, x) - x.sinh()).abs() < 1e-12 * (1.0 + x.sinh().abs()),
                "sinh {x}"
            );
            assert!(
                (ev(0x19, x) - x.cosh()).abs() < 1e-12 * (1.0 + x.cosh().abs()),
                "cosh {x}"
            );
            assert!((ev(0x09, x) - x.tanh()).abs() < 1e-14, "tanh {x}");
            // cosh^2 - sinh^2 == 1.
            let s = ev(0x02, x);
            let c = ev(0x19, x);
            assert!((c * c - s * s - 1.0).abs() < 1e-12, "cosh^2-sinh^2 at {x}");
        }
        // atanh near 0 and mid-range.
        for &x in &[-0.5_f64, -0.1, 0.0, 0.3, 0.9] {
            assert!((ev(0x0D, x) - x.atanh()).abs() < 1e-14, "atanh {x}");
        }
        let mut f = ExcFlags::default();
        assert!(atanh(fx(1.0), rn(), &mut f).is_inf());
        assert!(f.has(ExcFlags::DZ));
    }

    #[test]
    fn remainder_signals_a_signaling_nan_in_either_operand() {
        let snan = FloatX80 {
            sign_exp: 0x7fff,
            mantissa: 0xa000_0000_0000_0000,
        };
        let qnan = FloatX80 {
            sign_exp: 0x7fff,
            mantissa: 0xc000_0000_0000_0000,
        };
        for ieee in [false, true] {
            // Destination quiet NaN, source signaling NaN: the result is
            // the destination NaN and SNAN is still raised.
            let mut f = ExcFlags::default();
            let r = remainder(qnan, snan, ieee, &mut f);
            assert_eq!(r.value.mantissa, qnan.mantissa);
            assert!(f.has(ExcFlags::SNAN));
            let mut f = ExcFlags::default();
            let r = remainder(snan, qnan, ieee, &mut f);
            assert_eq!(r.value.mantissa, 0xe000_0000_0000_0000);
            assert!(f.has(ExcFlags::SNAN));
        }
    }

    #[test]
    fn fmod_frem_exact() {
        let r = |a: f64, b: f64, ieee: bool| remainder(fx(a), fx(b), ieee, &mut noflags());
        // FMOD basics.
        let m = r(7.5, 2.0, false);
        assert_eq!(m.value.to_f64(), 1.5);
        assert_eq!(m.quotient, 3); // 7.5 = 3*2 + 1.5
        assert!(!m.quotient_sign);
        // Negative dividend: remainder takes the sign of x.
        let m = r(-7.5, 2.0, false);
        assert_eq!(m.value.to_f64(), -1.5);
        assert!(m.quotient_sign); // -/+ -> negative quotient
        // FREM rounds the quotient to nearest: 7.5/2 = 3.75 -> 4, rem = -0.5.
        let q = r(7.5, 2.0, true);
        assert_eq!(q.value.to_f64(), -0.5);
        assert_eq!(q.quotient, 4);
        // Exactness beyond f64: 1e300 mod 3 via the f64 path would be wrong;
        // here it is exact (result in [0,3)).
        let big = r(1e18, 3.0, false);
        assert!(big.value.to_f64() >= 0.0 && big.value.to_f64() < 3.0);
        // src = 0 -> OPERR + NaN.
        let mut f = ExcFlags::default();
        let z = remainder(fx(1.0), fx(0.0), false, &mut f);
        assert!(z.value.is_nan() && f.has(ExcFlags::OPERR));
    }

    #[test]
    fn fpcr_mode_and_inex_threaded() {
        use super::super::softfloat::{Precision, RoundMode};
        let rz = RoundCtx {
            mode: RoundMode::Zero,
            prec: Precision::Extended,
        };
        let rp = RoundCtx {
            mode: RoundMode::PosInf,
            prec: Precision::Extended,
        };
        let mut fz = ExcFlags::default();
        let mut fp = ExcFlags::default();
        let lo = eval_unary(0x14, fx(3.0), rz, &mut fz).unwrap(); // ln(3) toward zero
        let hi = eval_unary(0x14, fx(3.0), rp, &mut fp).unwrap(); // ln(3) toward +inf
        // ln(3) is irrational: rounding up gives a mantissa one ULP above
        // rounding toward zero, and both are inexact.
        assert_eq!(hi.mantissa, lo.mantissa + 1);
        assert!(fz.has(ExcFlags::INEX2) && fp.has(ExcFlags::INEX2));
    }

    #[test]
    fn exp_log_specials() {
        assert!(exp(FloatX80::infinity(false), rn(), &mut noflags()).is_inf());
        assert!(exp(FloatX80::infinity(true), rn(), &mut noflags()).is_zero());
        let mut f = ExcFlags::default();
        assert!(ln(FloatX80::zero(false), rn(), &mut f).is_inf());
        assert!(f.has(ExcFlags::DZ));
        let mut f = ExcFlags::default();
        assert!(ln(fx(-1.0), rn(), &mut f).is_nan());
        assert!(f.has(ExcFlags::OPERR));
    }

    #[test]
    fn exp2_and_exp10_at_the_limits_of_the_range() {
        let c = RoundCtx::NEAREST_EXT;
        let mut f = ExcFlags::default();
        assert!(exp2(softfloat::scale(fx(1.0), 14, c, &mut f), c, &mut f).is_inf());
        assert!(f.0 & ExcFlags::OVFL != 0);
        let mut f = ExcFlags::default();
        let big = softfloat::sub(softfloat::scale(fx(1.0), 14, c, &mut f), fx(1.0), c, &mut f);
        let r = exp2(big, c, &mut f);
        assert!(!r.is_nan() && !r.is_inf());
        assert_eq!(r.sign_exp & 0x7FFF, 0x7FFE);
        let mut f = ExcFlags::default();
        assert!(exp10(fx(5000.0), c, &mut f).is_inf());
        let mut f = ExcFlags::default();
        assert!(exp10(fx(-5000.0), c, &mut f).is_zero());
        assert!(f.0 & ExcFlags::UNFL != 0);
    }
}