"""
02_trace_swap.py -- "Understanding swap()", one instruction at a time
=====================================================================

[Questions this demo answers]
  - The slides animate swap(long *xp, long *yp) with xp = 0x120, yp = 0x100
    holding 123 and 456. What exactly do the registers and memory hold after
    each of the 4 instructions?
  - How can you tell from the assembly alone that %rdi and %rsi are
    POINTERS? (They are used inside parentheses: (%rdi) means *xp.)

[How to run]
  python3 02_trace_swap.py

[How to read the output]
  A table with one row per executed instruction. Columns show the registers
  the function uses and the two memory words it touches. '*' marks the
  value that this instruction changed.

[Systems link / CS:APP 3.4]
  In C, swap reads two memory locations and writes two. x86-64 cannot move
  data memory-to-memory in one instruction, so the compiler routes every
  value through a register: 2 loads, then 2 stores. Registers hold the
  pointers and the temporaries t0, t1; memory holds the data.
"""

import os

import x86sim

os.chdir(os.path.dirname(os.path.abspath(__file__)))


def main():
    print("=== Demo 02: tracing swap(xp, yp) ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    print("The compiler's x86-64 code for swap:")
    print(x86sim.listing(prog, "swap"))
    print()

    # The slide's setup: xp = 0x120 holds 123, yp = 0x100 holds 456.
    m = x86sim.Machine(prog)
    xp, yp = 0x120, 0x100
    m.mem.write(xp, 8, 123)
    m.mem.write(yp, 8, 456)

    regs = ["rdi", "rsi", "rax", "rcx"]
    header = "  %-24s" % "instruction" + "".join("%%%-7s" % r for r in regs) + \
             "  M[0x120]  M[0x100]"
    print(header)
    print("  " + "-" * (len(header) - 2))

    def row(text, changed_regs, changed_mem):
        cells = ""
        for r in regs:
            v = m.regs[r]
            mark = "*" if r in changed_regs else " "
            shown = hex(v) if r in ("rdi", "rsi") else str(v)   # pointers in hex
            cells += ("%s%-7s" % (mark, shown))
        mem_cells = ""
        for a in (xp, yp):
            mark = "*" if a in changed_mem else " "
            mem_cells += "  %s%-7d" % (mark, m.mem.read(a, 8))
        print("  %-24s%s%s" % (text, cells, mem_cells))

    m.regs["rdi"], m.regs["rsi"] = xp, yp           # arguments, as C would pass them
    row("(on entry)", {"rdi", "rsi"}, set())
    m.push(x86sim.RETURN_SENTINEL)
    m.rip, m.halted = prog.address_of("swap"), False
    while not m.halted:
        before = dict(m.regs)
        m.mem.log = []
        ins = prog.instrs[prog.by_addr[m.rip]]
        m.step()
        changed = {r for r in regs if before[r] != m.regs[r]}
        written = {a for a, _, _, _ in m.mem.log}
        m.mem.log = None
        row(ins.text, changed, written)

    print()
    print("Reading it as C (replace each register by a variable name):")
    print("    t0 = *xp;   // movq (%rdi), %rax")
    print("    t1 = *yp;   // movq (%rsi), %rcx   (the slide's gcc uses %rdx; any free")
    print("    *xp = t1;   // movq %rcx, (%rdi)    caller-saved register will do)")
    print("    *yp = t0;   // movq %rax, (%rsi)")
    print()
    print("Observations:")
    print("  * %rdi and %rsi only ever appear INSIDE parentheses, so they hold")
    print("    addresses: the arguments are pointers. Every value is 8 bytes (movq),")
    print("    so they point to long-sized data -- swap(long *xp, long *yp).")
    print("  * Data moves memory -> register -> memory: x86-64 has no single")
    print("    memory-to-memory mov.")
    print("  * The registers keep their values after the stores; only memory")
    print("    changed in the last two steps. The final values are swapped:")
    print("    M[0x120] = %d, M[0x100] = %d." % (m.mem.read(xp, 8), m.mem.read(yp, 8)))


if __name__ == "__main__":
    main()
