"""
07_crosscheck.py -- Lecture 4's functions: simulator vs real hardware
=====================================================================

[Questions this demo answers]
  - Do the traces of demos 02-06 describe what the real CPU does with the
    same machine code? This time the code exercises conditional moves, global
    variables (RIP-relative operands), loops with bt/adc, a jump table with
    32-bit relative entries, and call/ret.

[How to run]
  make                (builds build/oracle and build/oracle_x86)
  python3 07_crosscheck.py

[How to read the output]
  One row per function: number of inputs and the number of disagreements
  with the real x86-64 run (should all be 0). The -O1 column runs the
  simulator on clang -O1 code, a second, different instruction sequence for
  the same C.

[Method]  As in Lecture 3: edge values plus seeded random inputs; switch_eg
  uses z != 0 (division!) and x in -3..9 plus random x; arithmetic that could
  overflow (mult2/multstore) uses small values, because signed overflow is
  undefined behavior in C.
"""

import os
import random
import subprocess
import sys

import course_path
course_path.use("lecture03")
import x86sim                                         # noqa: E402

os.chdir(os.path.dirname(os.path.abspath(__file__)))
M64 = x86sim.MASK[8]
TMIN, TMAX = -(1 << 63), (1 << 63) - 1
EDGE = [0, 1, -1, 2, 7, 64, 100, 199, 200, 1000, 10000, TMIN, TMAX, 0xFF, 1 << 63]


def gen(rng, name, n=300):
    """Argument tuples for function `name`."""
    out = []
    for _ in range(n):
        def any64():
            return rng.choice(EDGE) if rng.random() < 0.3 else rng.randint(TMIN, TMAX)

        def small():
            return rng.randint(-(1 << 20), 1 << 20)
        if name in ("absdiff", "absdiff_se"):
            # |x - y| must not overflow: keep both within +-2^61
            out.append((rng.randint(-(1 << 61), 1 << 61), rng.randint(-(1 << 61), 1 << 61)))
        elif name == "cond_deref":
            out.append((0,) if rng.random() < 0.3 else (rng.randint(1, 1 << 40),))
        elif name.startswith("pcount"):
            out.append((any64(),))
        elif name == "switch_eg":
            x = rng.randint(-3, 9) if rng.random() < 0.8 else any64()
            z = rng.choice([v for v in range(-9, 10) if v != 0])
            out.append((x, rng.randint(-1000, 1000), z))
        elif name == "sparse_switch":
            base = rng.choice([0, 100, 200, 1000, 10000])
            out.append((base + rng.choice([-1, 0, 0, 1]) if rng.random() < 0.7 else any64(),))
        else:                                       # mult2, multstore
            out.append((small(), small()))
    return out


def sim_run(m, name, args):
    """Run one case in the simulator, formatted like oracle.c."""
    if name == "absdiff_se":
        lt, ge = m.prog.address_of("lt_cnt"), m.prog.address_of("ge_cnt")
        m.mem.write(lt, 8, 0)
        m.mem.write(ge, 8, 0)
        r = m.call(name, *[a & M64 for a in args])
        return "%d %d %d" % (x86sim.to_signed(r, 8), m.mem.read(lt, 8), m.mem.read(ge, 8))
    if name == "cond_deref":
        if args[0] == 0:
            return str(x86sim.to_signed(m.call(name, 0), 8))
        m.mem.write(0x9000, 8, args[0])                 # oracle passes &v holding v
        return str(x86sim.to_signed(m.call(name, 0x9000), 8))
    if name == "multstore":
        m.mem.write(0x9100, 8, 0)
        m.call(name, args[0] & M64, args[1] & M64, 0x9100)
        return str(x86sim.to_signed(m.mem.read(0x9100, 8), 8))
    return str(x86sim.to_signed(m.call(name, *[a & M64 for a in args]), 8))


def main():
    print("=== Demo 07: simulator vs real hardware (Lecture 4 functions) ===\n")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "build/oracle", "build/oracle_x86"])
    if not os.path.exists("build/oracle_x86"):
        print("build/oracle_x86 is missing (no x86-64 compiler?) -- cannot cross-check")
        sys.exit(1)
    m_og = x86sim.Machine(x86sim.Program.from_file(x86sim.compile_to_asm("control.c")))
    m_o1 = x86sim.Machine(x86sim.Program.from_file(x86sim.compile_to_asm("control.c", opt="-O1")))
    rng = random.Random(15213)
    names = ["absdiff", "absdiff_se", "cond_deref", "pcount_do", "pcount_while", "pcount_for",
             "switch_eg", "sparse_switch", "mult2", "multstore"]
    print("  %-14s %6s  %-14s %-14s %-14s" % ("function", "cases", "sim -Og != HW",
                                              "sim -O1 != HW", "native != HW"))
    totals = [0, 0, 0]
    for name in names:
        cases = gen(rng, name)
        lines = "".join("%s %s\n" % (name, " ".join(str(a) for a in c)) for c in cases)
        hw = subprocess.run(["build/oracle_x86"], input=lines, capture_output=True,
                            text=True).stdout.splitlines()
        nat = subprocess.run(["build/oracle"], input=lines, capture_output=True,
                             text=True).stdout.splitlines()
        bad = [sum(1 for c, h in zip(cases, hw) if sim_run(m, name, c) != h.strip())
               for m in (m_og, m_o1)]
        bad.append(sum(1 for a, b in zip(nat, hw) if a != b))
        for k in range(3):
            totals[k] += bad[k]
        print("  %-14s %6d  %-14d %-14d %-14d" % (name, len(cases), bad[0], bad[1], bad[2]))
    print()
    print("Observations:")
    print("  * Disagreements in total: simulator at -Og %d, at -O1 %d, native build %d."
          % tuple(totals))
    print("  * Two different instruction sequences per function (-Og and -O1), one")
    print("    real CPU and one other ISA all compute the same results: the traces in")
    print("    this lecture describe what the hardware really does.")


if __name__ == "__main__":
    main()
