#!/usr/bin/env python3
"""
03_why_it_races.py -- the race, in the generated instructions.

[Idea]
  Demo 01 shows that `cnt++` loses updates. The reason is invisible in C and
  obvious in assembly: one `++` on a shared variable compiles to a LOAD, an
  ADD and a STORE, and a thread can be descheduled between any two of them.
  This driver compiles three one-line functions and shows you the instructions,
  on x86-64 (the textbook's target) and on this machine's native arm64.

  It also shows the fix at the instruction level: the atomic version compiles
  to a single read-modify-write (x86 `lock add`, arm64 `ldaddal`/`casal`), with
  no window in between.

[Why bother]
  "cnt++ is not atomic" is a claim. Seeing three instructions where you wrote
  one character is an explanation -- and it ties Lecture 22 straight back to
  Lectures 3-5, where you learned to read exactly this.

Run:   python3 03_why_it_races.py        (identical under Python 3.9 and 3.13)
"""
import os
import re
import subprocess
import sys
import tempfile

SOURCE = r"""
#include <stdatomic.h>

long cnt;
atomic_long acnt;

/* one shared increment: the thing that races */
void increment(void)       { cnt++; }

/* the same work in a local: nothing shared, nothing to race */
long local_sum(long n)     { long s = 0; for (long i = 0; i < n; i++) s++; return s; }

/* the atomic fix: one indivisible read-modify-write */
void increment_atomic(void) { atomic_fetch_add(&acnt, 1); }
"""

# Instruction mnemonics that touch memory or lock, per architecture, used to
# classify what we see rather than just dumping it.
MEMORY_OPS = {
    "x86_64": {"load": ("movq", "movl"), "add": ("addq", "addl", "incq"),
               "atomic": ("lock",)},
    "arm64":  {"load": ("ldr",), "add": ("add",), "store": ("str",),
               "atomic": ("ldadd", "casal", "ldaxr", "stlxr", "swpal")},
}


def compile_asm(arch, opt="-O1"):
    """Compile SOURCE for `arch` and return the assembly text, or None."""
    flags = ["-S", opt, "-std=c11", "-o", "-"]
    if arch == "x86_64":
        flags = ["-arch", "x86_64"] + flags
    with tempfile.TemporaryDirectory() as d:
        src = os.path.join(d, "inc.c")
        with open(src, "w") as f:
            f.write(SOURCE)
        try:
            out = subprocess.run(["cc"] + flags + [src],
                                 capture_output=True, text=True, check=True)
        except (subprocess.CalledProcessError, FileNotFoundError):
            return None
    return out.stdout


def extract(asm, func):
    """Return the instruction lines of one function from assembly text.

    [Idea] A function's body runs from its label to the next label or
    directive-only section. We keep lines that look like instructions
    (a tab-indented mnemonic) and drop directives (.cfi_*, .p2align, ...).
    """
    if asm is None:
        return []
    # the symbol may be `increment:` or `_increment:` depending on the platform
    pattern = re.compile(r"^_?" + re.escape(func) + r":", re.M)
    m = pattern.search(asm)
    if not m:
        return []
    body = asm[m.end():]
    lines = []
    for raw in body.splitlines():
        line = raw.strip()
        if not line:
            continue
        # End of this function: the epilogue marker, or the next GLOBAL symbol.
        if line.startswith(".cfi_endproc") or "-- End function" in line:
            break
        if re.match(r"^_[A-Za-z]\w*:", line):               # next function
            break
        # Skip assembler bookkeeping and compiler-local labels. On arm64 clang
        # emits `Lloh0:` / `LBB0_1:` inside a function; treating those as "the
        # next label" is what made an earlier version of this script give up.
        if re.match(r"^L\w+:", line):
            continue
        if line.startswith("."):
            continue
        if line.startswith((";", "#", "//")):
            continue
        lines.append(re.sub(r"\s+", " ", line))
    return lines


def classify(lines, arch):
    """Count loads / adds / stores / atomic ops in a list of instructions."""
    kinds = MEMORY_OPS[arch]
    counts = {}
    for line in lines:
        mnem = line.split()[0].lower()
        for kind, prefixes in kinds.items():
            if mnem.startswith(tuple(prefixes)):
                counts[kind] = counts.get(kind, 0) + 1
    return counts


def panel(arch, asm, func, note):
    """Print one function's instructions with a short classification."""
    lines = extract(asm, func)
    print(f"  {func}()  -- {note}")
    if not lines:
        print("    (could not locate in the generated assembly)")
        return
    for line in lines:
        print(f"    {line}")
    c = classify(lines, arch)
    parts = [f"{v} {k}" for k, v in sorted(c.items())]
    print(f"    => {len(lines)} instruction(s)"
          + (f": {', '.join(parts)}" if parts else "") + "\n")


def show(arch):
    print(f"== {arch} ==")
    asm0 = compile_asm(arch, "-O0")
    asm2 = compile_asm(arch, "-O2")
    if asm0 is None and asm2 is None:
        print("  (compiler for this architecture unavailable -- skipped)\n")
        return

    print("  --- at -O0 (what the textbook shows) ---")
    panel(arch, asm0, "increment", "cnt++ on a SHARED global")

    print("  --- at -O2 (what you actually ship) ---")
    panel(arch, asm2, "increment", "cnt++ on a SHARED global")
    panel(arch, asm2, "increment_atomic", "atomic_fetch_add on a shared global")
    panel(arch, asm2, "local_sum", "s++ on a LOCAL -- no shared memory at all")


def main():
    for arch in ("x86_64", "arm64"):
        show(arch)

    print("Observations")
    print("------------")
    print("- At -O0, `cnt++` on a shared global is exactly what the textbook")
    print("  promises on BOTH architectures: a LOAD, an ADD and a STORE. A thread")
    print("  can be descheduled between any two of them, so two threads can load")
    print("  the same old value and both store old+1 -- one increase for two")
    print("  increments. That is demo 01's lost updates.")
    print("- At -O2 the two architectures diverge, and the x86-64 result is the")
    print("  subtle one: the three instructions become ONE, `incq (%rax)`.")
    print("  That single instruction is still NOT ATOMIC -- the CPU reads,")
    print("  modifies and writes internally, and another core can interleave.")
    print("  'One instruction' and 'atomic' are different claims; the whole")
    print("  point of the LOCK prefix is the difference between them.")
    print("- arm64 at -O2 still uses separate ldr/add/str: it has no")
    print("  read-modify-write-in-one-instruction form for a plain increment.")
    print("- increment_atomic() is the hardware fix: x86-64 emits a LOCK-prefixed")
    print("  read-modify-write, arm64 an atomic add (ldadd/casal family), so")
    print("  there is no window to interleave into at all.")
    print("- local_sum() touches NO shared memory: its accumulator is private to")
    print("  the thread (on its own stack at -O0, in a register at -O2 -- where")
    print("  the compiler in fact computes the loop's closed form outright, which")
    print("  is Lecture 15's optimizer at work). Nothing shared, nothing to race:")
    print("  that is why demo 02's 'private + combine' needs no lock.")
    print("- A mutex solves the problem differently from an atomic: it does not")
    print("  make the instructions indivisible, it guarantees no other thread is")
    print("  executing that REGION at the same time (mutual exclusion).")


if __name__ == "__main__":
    sys.exit(main())
