#!/usr/bin/env python3
"""Generate exact IEEE-754 binary32 stress checkpoints."""

from __future__ import annotations

import argparse
from fractions import Fraction
from pathlib import Path
import re

from llvm_paths import llvm_project_root


MASK16 = (1 << 16) - 1
MASK32 = (1 << 32) - 1
SIGNATURE_SEED = 0x16600137
GROUP_SIGNATURE_SEED = 0xF3200000
ITERATIONS = 128
CHECKPOINT_INTERVAL = 8
EXPRESSION_COUNT = 4
SUITE_ID = 311
SEEDS = (0x1660F32A, 0xC166F32B, 0x5EEDF32C)
EDGES = (
    0x00000000, 0x80000000,
    0x00000001, 0x80000001,
    0x007FFFFF, 0x807FFFFF,
    0x00800000, 0x80800000,
    0x3F000000, 0xBF000000,
    0x3F800000, 0xBF800000,
    0x40000000, 0xC0200000,
    0x7F7FFFFF, 0xFF7FFFFF,
)
UPSTREAM = (
    (0, "addsf3_test.c", "addsf3"),
    (1, "subsf3_test.c", "subsf3"),
    (2, "mulsf3_test.c", "mulsf3"),
    (3, "divsf3_test.c", "divsf3"),
)


def xorshift16(value: int) -> int:
    value ^= value << 7 & MASK16
    value ^= value >> 9
    value ^= value << 8 & MASK16
    return value & MASK16


def next_u32(state: tuple[int, int]) -> tuple[tuple[int, int], int]:
    low = xorshift16(state[0])
    high = xorshift16(state[1])
    if low == 0 and high == 0:
        high = 1
    return (low, high), (high << 16) | low


def finite_bits(state: tuple[int, int]):
    state, bits = next_u32(state)
    if bits >> 23 & 0xFF == 0xFF:
        bits ^= 1 << 23
    return state, bits


def input_pairs(seed_index: int, seed: int):
    state = (seed & MASK16, seed >> 16)
    for iteration in range(ITERATIONS):
        state, a = finite_bits(state)
        state, b = finite_bits(state)
        if iteration & 3 == 0:
            a = EDGES[(iteration + seed_index) & 15]
        if iteration & 3 == 1:
            b = EDGES[(iteration * 3 + seed_index) & 15]
        if b & 0x7FFFFFFF == 0:
            b = 0x3F800000
        yield iteration, a, b


def decode_finite(bits: int) -> Fraction:
    sign = -1 if bits >> 31 else 1
    exponent = bits >> 23 & 0xFF
    fraction = bits & 0x7FFFFF
    if exponent == 0:
        significand = fraction
        power = -149
    else:
        significand = (1 << 23) | fraction
        power = exponent - 127 - 23
    value = Fraction(sign * significand)
    return value * (1 << power) if power >= 0 else value / (1 << -power)


def round_ratio(numerator: int, denominator: int) -> int:
    quotient, remainder = divmod(numerator, denominator)
    doubled = remainder * 2
    if doubled > denominator or doubled == denominator and quotient & 1:
        quotient += 1
    return quotient


def scaled_round(value: Fraction, power: int) -> int:
    numerator = value.numerator
    denominator = value.denominator
    if power >= 0:
        numerator <<= power
    else:
        denominator <<= -power
    return round_ratio(numerator, denominator)


def floor_log2(value: Fraction) -> int:
    numerator = value.numerator
    denominator = value.denominator
    exponent = numerator.bit_length() - denominator.bit_length()
    if exponent >= 0:
        if numerator < denominator << exponent:
            exponent -= 1
    elif numerator << -exponent < denominator:
        exponent -= 1
    return exponent


def encode_fraction(value: Fraction) -> int:
    sign = 0
    if value < 0:
        sign = 1
        value = -value
    if value == 0:
        return sign << 31

    exponent = floor_log2(value)
    if exponent >= -126:
        significand = scaled_round(value, 23 - exponent)
        if significand == 1 << 24:
            significand >>= 1
            exponent += 1
        if exponent > 127:
            return sign << 31 | 0x7F800000
        return (sign << 31 | (exponent + 127) << 23 |
                (significand - (1 << 23)))

    significand = scaled_round(value, 149)
    if significand == 0:
        return sign << 31
    if significand >= 1 << 23:
        return sign << 31 | 0x00800000
    return sign << 31 | significand


def evaluate(operation: int, a_bits: int, b_bits: int) -> int:
    a = decode_finite(a_bits)
    b = decode_finite(b_bits)
    a_zero = a_bits & 0x7FFFFFFF == 0
    b_zero = b_bits & 0x7FFFFFFF == 0
    a_sign = a_bits >> 31
    b_sign = b_bits >> 31
    if operation == 0 or operation == 1:
        effective_b_sign = b_sign ^ (operation == 1)
        if a_zero and b_zero:
            return (a_sign & effective_b_sign) << 31
        result = a + b if operation == 0 else a - b
        return 0 if result == 0 else encode_fraction(result)
    if operation == 2:
        if a_zero or b_zero:
            return (a_sign ^ b_sign) << 31
        return encode_fraction(a * b)
    if a_zero:
        return (a_sign ^ b_sign) << 31
    if b_zero:
        return (a_sign ^ b_sign) << 31 | 0x7F800000
    return encode_fraction(a / b)


def signature_step(signature: int, case_id: int, value: int) -> int:
    case_id &= MASK16
    tag = (case_id << 16) | case_id
    rotated = ((signature << 5) | (signature >> 27)) & MASK32
    return (rotated ^ value ^ tag) & MASK32


def checkpoints():
    result = []
    for seed_index, seed in enumerate(SEEDS):
        pairs = list(input_pairs(seed_index, seed))
        for expression in range(EXPRESSION_COUNT):
            signature = (GROUP_SIGNATURE_SEED ^ ((seed_index + 1) << 8) ^
                         expression)
            for iteration, a, b in pairs:
                signature = signature_step(
                    signature, iteration + 1, evaluate(expression, a, b))
                if (iteration + 1) % CHECKPOINT_INTERVAL == 0:
                    result.append(signature)
    return result


def expected_signature() -> int:
    signature = SIGNATURE_SEED
    for case_id, checkpoint in enumerate(checkpoints(), 1):
        signature = signature_step(signature, case_id, checkpoint)
    return signature


def verify_upstream() -> int:
    verified = 0
    for operation, filename, helper in UPSTREAM:
        source = (llvm_project_root() / "compiler-rt" / "test" / "builtins" /
                  "Unit" / filename)
        pattern = re.compile(
            rf"test__{helper}\(0x([0-9a-fA-F]{{8}}),\s*"
            rf"0x([0-9a-fA-F]{{8}}),\s*0x([0-9a-fA-F]{{8}})\)"
        )
        for match in pattern.findall(source.read_text(encoding="utf-8")):
            a, b, expected = (int(word, 16) for word in match)
            if (a >> 23 & 0xFF) == 0xFF or (b >> 23 & 0xFF) == 0xFF:
                continue
            if operation == 3 and b & 0x7FFFFFFF == 0:
                continue
            actual = evaluate(operation, a, b)
            if actual != expected:
                raise SystemExit(
                    f"oracle mismatch {helper}: {a:08x} {b:08x}: "
                    f"{actual:08x} != {expected:08x}"
                )
            verified += 1
    if verified == 0:
        raise SystemExit("no upstream binary32 vectors verified")
    return verified


def emit_u32_array(name: str, values) -> None:
    values = tuple(values)
    print(f"static const abi_u32 {name}[{len(values)}] = {{")
    for index in range(0, len(values), 4):
        line = ", ".join(
            f"0x{value:08x}UL" for value in values[index:index + 4]
        )
        suffix = "," if index + 4 < len(values) else ""
        print(f"  {line}{suffix}")
    print("};")


def emit_corpus() -> None:
    expected = checkpoints()
    print("#ifndef SEEDED_F32_CORPUS_INC")
    print("#define SEEDED_F32_CORPUS_INC")
    print()
    print(f"#define ABI_SEEDED_F32_SUITE_ID {SUITE_ID}U")
    print(f"#define ABI_SEEDED_F32_ITERATIONS {ITERATIONS}U")
    print(f"#define ABI_SEEDED_F32_SEED_COUNT {len(SEEDS)}U")
    print(f"#define ABI_SEEDED_F32_EXPRESSION_COUNT {EXPRESSION_COUNT}U")
    print(f"#define ABI_SEEDED_F32_CHECKPOINT_INTERVAL {CHECKPOINT_INTERVAL}U")
    print(f"#define ABI_SEEDED_F32_CHECKPOINTS_PER_GROUP "
          f"{ITERATIONS // CHECKPOINT_INTERVAL}U")
    print(f"#define ABI_SEEDED_F32_CHECKPOINT_COUNT {len(expected)}U")
    print(f"#define ABI_SEEDED_F32_RESULT_COUNT "
          f"{len(SEEDS) * EXPRESSION_COUNT * ITERATIONS}UL")
    print(f"#define ABI_SEEDED_F32_GROUP_SIGNATURE_SEED "
          f"0x{GROUP_SIGNATURE_SEED:08x}UL")
    print()
    emit_u32_array("abi_seeded_f32_seeds", SEEDS)
    emit_u32_array("abi_seeded_f32_edges", EDGES)
    emit_u32_array("abi_seeded_f32_expected", expected)
    print()
    print("#endif")


def main() -> None:
    global ITERATIONS, CHECKPOINT_INTERVAL, SEEDS, SUITE_ID

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mode", choices=("corpus", "signature", "check-count",
                         "result-count", "verify-upstream"))
    parser.add_argument("--iterations", type=int, default=ITERATIONS)
    parser.add_argument("--checkpoint-interval", type=int,
                        default=CHECKPOINT_INTERVAL)
    parser.add_argument("--suite-id", type=int, default=SUITE_ID)
    parser.add_argument("--seed", action="append",
                        type=lambda value: int(value, 0), default=[])
    args = parser.parse_args()
    seeds = tuple(args.seed) if args.seed else SEEDS
    if not 1 <= args.iterations <= 32767:
        parser.error("--iterations must be in 1..32767")
    if (args.checkpoint_interval <= 0 or
            args.checkpoint_interval & (args.checkpoint_interval - 1)):
        parser.error("--checkpoint-interval must be a power of two")
    if args.iterations % args.checkpoint_interval:
        parser.error("--iterations must be divisible by --checkpoint-interval")
    if not seeds or any(not 1 <= seed <= MASK32 for seed in seeds):
        parser.error("each --seed must be a nonzero unsigned 32-bit value")
    checkpoint_count = (len(seeds) * EXPRESSION_COUNT *
                        (args.iterations // args.checkpoint_interval))
    if checkpoint_count > 4095:
        parser.error("checkpoint table must fit one 16 KiB Classic far object")
    if not 0 <= args.suite_id <= MASK16:
        parser.error("--suite-id must fit unsigned 16 bits")
    ITERATIONS = args.iterations
    CHECKPOINT_INTERVAL = args.checkpoint_interval
    SEEDS = seeds
    SUITE_ID = args.suite_id

    if args.mode == "corpus":
        emit_corpus()
    elif args.mode == "signature":
        print(expected_signature())
    elif args.mode == "check-count":
        print(checkpoint_count)
    elif args.mode == "result-count":
        print(len(SEEDS) * EXPRESSION_COUNT * ITERATIONS)
    else:
        print(verify_upstream())


if __name__ == "__main__":
    main()
