#!/usr/bin/env python3
import re
import sys
from pathlib import Path

from llvm_paths import llvm_project_root

MASK32 = 0xFFFFFFFF
SIGNATURE_SEED = 0x1660011E
EVALUATION_PATH_COUNT = 2
OPERATIONS = (
    (0, "add", "adddf3new_test.c", "adddf3"),
    (1, "sub", "subdf3new_test.c", "subdf3"),
    (2, "mul", "muldf3new_test.c", "muldf3"),
    (3, "div", "divdf3new_test.c", "divdf3"),
)
REGRESSION_VECTORS = (
    (0, "add", 0x0000000000000001, 0x7FEFFFFFFFFFFFFF,
     0x7FEFFFFFFFFFFFFF),
    (0, "add", 0x000FFFFFFFFFFFFF, 0x800FFFFFFFFFFFFE,
     0x0000000000000001),
    (0, "add", 0x7FEFFFFFFFFFFFFF, 0xFFEFFFFFFFFFFFFF,
     0x0000000000000000),
    (1, "sub", 0x3FF0000000000001, 0x3FF0000000000000,
     0x3CB0000000000000),
    (2, "mul", 0x69D786CB82A3E7F0, 0x000FFFFFFFFFFFFF,
     0x29F786CB82A3E7EF),
)
def fp_class(bits):
    exponent = (bits >> 52) & 0x7FF
    fraction = bits & 0xFFFFFFFFFFFFF
    if exponent == 0:
        return "zero" if fraction == 0 else "subnormal"
    if exponent == 0x7FF:
        return "infinity" if fraction == 0 else "nan"
    return "normal"


def parse_upstream(filename, helper):
    source = (llvm_project_root() / "compiler-rt" / "test" / "builtins" /
              "Unit" / filename)
    text = source.read_text(encoding="utf-8")
    pattern = re.compile(
        rf"test__{helper}\(\s*0x([0-9a-fA-F]{{16}})\s*,\s*"
        rf"0x([0-9a-fA-F]{{16}})\s*,\s*0x([0-9a-fA-F]{{16}})\s*\)"
    )
    vectors = [tuple(int(word, 16) for word in match)
               for match in pattern.findall(text)]
    if not vectors:
        raise SystemExit(f"no {helper} vectors parsed from {source}")
    return vectors


def selected_vectors():
    result = []
    provenance = []
    for operation, name, filename, helper in OPERATIONS:
        upstream = parse_upstream(filename, helper)
        provenance.append((name, filename, len(upstream)))
        for lhs, rhs, expected in upstream:
            result.append((operation, name, lhs, rhs, expected))
    result.extend(REGRESSION_VECTORS)
    return result, provenance


def words(bits):
    return tuple((bits >> shift) & 0xFFFF for shift in (48, 32, 16, 0))


def signature_step(signature, case_id, actual):
    tag = ((case_id & 0xFFFF) << 16) | (case_id & 0xFFFF)
    return (((signature << 5) | (signature >> 27)) ^ actual ^ tag) & MASK32


def expected_signature():
    signature = SIGNATURE_SEED
    vectors, _ = selected_vectors()
    checks_per_path = len(vectors) * 2
    for path in range(EVALUATION_PATH_COUNT):
        for vector_id, (_, _, _, _, expected) in enumerate(vectors, 1):
            case_id = path * checks_per_path + vector_id * 2
            signature = signature_step(signature, case_id - 1,
                                       (expected >> 32) & MASK32)
            signature = signature_step(signature, case_id,
                                       expected & MASK32)
    return signature


def emit_vectors():
    vectors, provenance = selected_vectors()
    print("#ifndef FLOAT64_MATRIX_VECTORS_INC")
    print("#define FLOAT64_MATRIX_VECTORS_INC")
    print()
    for name, filename, total in provenance:
        print(f"/* {name}: all {total} vectors from "
              f"compiler-rt/test/builtins/Unit/{filename}. */")
    print("/* Explicit regressions cover wide alignment, cancellation, "
          "and sticky. */")
    for operation, name, _, _ in OPERATIONS:
        operation_vectors = [
            vector for vector in vectors
            if vector[0] == operation and vector[1] == name
        ]
        print(f"#define ABI_FLOAT64_{name.upper()}_VECTORS(X) \\")
        for index, (_, _, lhs, rhs, expected) in enumerate(
                operation_vectors, 1):
            fields = (*words(lhs), *words(rhs), *words(expected))
            values = ", ".join(f"0x{value:04x}U" for value in fields)
            nan_ok = int(fp_class(expected) == "nan")
            suffix = " \\" if index != len(operation_vectors) else ""
            print(f"  X({index}, {values}, {nan_ok}U){suffix}")
        print(f"#define ABI_FLOAT64_{name.upper()}_COUNT "
              f"{len(operation_vectors)}U")
    print(f"#define ABI_FLOAT64_VECTOR_COUNT {len(vectors)}U")
    print(f"#define ABI_FLOAT64_EVALUATION_PATH_COUNT "
          f"{EVALUATION_PATH_COUNT}U")
    print(f"#define ABI_FLOAT64_SIGNATURE 0x{expected_signature():08x}UL")
    print()
    print("#endif")


def main():
    if len(sys.argv) != 2 or sys.argv[1] not in {
        "vectors", "signature"
    }:
        raise SystemExit(
            "usage: gen-float64-vectors vectors|signature"
        )
    if sys.argv[1] == "vectors":
        emit_vectors()
    else:
        print(expected_signature())


if __name__ == "__main__":
    main()
