"""
04_loops.py -- do-while, while and for loops in assembly
========================================================

[Questions this demo answers]
  - Assembly has no loops, only jumps. What do C's three loops turn into?
  - What are the "goto versions": do-while, "jump to middle" (gcc -Og, the
    slides) and "guarded do" (gcc -O1, and clang at both levels)?
  - How many instructions does each form execute? (We count them.)
  - Where do new instructions such as bt (bit test) and adc (add with
    carry) come from?

[How to run]
  python3 04_loops.py

[How to read the output]
  Listings of clang's code, then a table of instructions executed per call
  for several inputs, then a side-by-side run of the slides' gcc -Og
  "jump to middle" while loop, which we feed to the simulator as text.

[Systems link / CS:APP 3.6.7]
  A loop is a backward conditional jump: the test at the bottom jumps up to
  the start of the body. A while loop must test BEFORE the first iteration,
  so compilers either jump to the test first (jump to middle) or test once
  up front and then use a do-while (guarded do). The guarded form lets the
  optimizer assume the body runs at least once inside the loop.
"""

import os

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

os.chdir(os.path.dirname(os.path.abspath(__file__)))
M64 = x86sim.MASK[8]

# The slides' gcc -Og code for pcount_while: "jump to middle".
GCC_JUMP_TO_MIDDLE = """
pcount_while_jtm:
        movl   $0, %eax
        jmp    .L2              # jump to the test first
.L3:                            # loop body
        movq   %rdi, %rdx
        andl   $1, %edx
        addq   %rdx, %rax
        shrq   %rdi
.L2:                            # test
        testq  %rdi, %rdi
        jne    .L3
        ret
"""


def count_steps(m, name, x):
    """Run name(x); return (result, number of instructions executed)."""
    r = m.call(name, x & M64)
    return x86sim.to_signed(r, 8), m.steps


def main():
    print("=== Demo 04: loops ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("control.c"))
    prog_o1 = x86sim.Program.from_file(x86sim.compile_to_asm("control.c", opt="-O1"))
    m, m1 = x86sim.Machine(prog), x86sim.Machine(prog_o1)

    print("PART A: pcount_do -- do { result += x & 1; x >>= 1; } while (x);")
    print(x86sim.listing(prog, "pcount_do"))
    print("  The backward jump 'ja LBB3_1' IS the loop. Clang tests the OLD x:")
    print("  cmpq $1, %rdi; ja ...  means 'x > 1 (unsigned)', i.e. 'x >> 1 != 0',")
    print("  and the movq in between does not change the flags.\n")

    x = 0b1011
    m.call("pcount_do", x, trace=True)
    print("  trace for x = 0b1011 (three 1 bits); each block of 7 lines is one iteration:")
    for st in m.trace:
        regs = ", ".join("%%%s=%s" % (r, bin(n) if r in ("rdi", "rcx") else n)
                         for r, o, n in st.reg_changes if r != "rsp")
        note = " (%s)" % st.note if st.note and "Machine.call" not in st.note else ""
        print("    %-22s %s%s" % (st.text, regs, note))
    print()

    print("PART B: pcount_while -- the same body, but the test comes first")
    print(x86sim.listing(prog, "pcount_while"))
    print("  'testq; je LBB4_3' is the GUARD: if x == 0, skip the loop entirely.")
    print("  After the guard the loop is exactly the do-while loop: a 'guarded do'.\n")

    print("PART C: pcount_for -- for (i = 0; i < 64; i++) result += (x >> i) & 1;")
    print("  clang -Og:")
    print(x86sim.listing(prog, "pcount_for"))
    print("  clang -O1:")
    print(x86sim.listing(prog_o1, "pcount_for"))
    print("  bt %rcx, %rdi copies bit number %rcx of %rdi into CF. -Og then uses setb")
    print("  (CF -> byte) and addq; -O1 uses adcq $0, %rax = 'rax += 0 + CF'.")
    print("  The guard disappeared: i < 64 is known to be true the first time.\n")

    print("PART D: instructions executed per call")
    jtm = x86sim.Machine(x86sim.Program(GCC_JUMP_TO_MIDDLE, name="gcc -Og (slides)"))
    inputs = [0, 1, 0b1011, 0xFF, 1 << 63, M64]
    print("  %-20s %8s %8s %8s %8s %10s" % ("x", "do", "while", "while-JTM", "for -Og", "for -O1"))
    for x in inputs:
        r_do, n_do = count_steps(m, "pcount_do", x)
        r_wh, n_wh = count_steps(m, "pcount_while", x)
        r_jt, n_jt = count_steps(jtm, "pcount_while_jtm", x)
        r_f, n_f = count_steps(m, "pcount_for", x)
        r_f1, n_f1 = count_steps(m1, "pcount_for", x)
        assert len({r_do, r_wh, r_jt, r_f, r_f1}) == 1, "the five versions disagree!"
        print("  %-20s %8d %8d %8d %8d %10d   popcount=%d" % (
            hex(x), n_do, n_wh, n_jt, n_f, n_f1, r_wh))
    print("  (all five return the same popcount; counts include the final ret)")
    print("  * x = 0: the do-while still runs its body once (11 instructions); the")
    print("    while versions skip it (5).")
    print("  * x != 0: clang's while = do-while + 2 (the guard testq/je); gcc's")
    print("    jump-to-middle loop body is 6 instructions per iteration vs clang's 7.\n")

    print("PART E: the slides' gcc -Og 'jump to middle' version, run as text")
    print(x86sim.listing(jtm.prog, "pcount_while_jtm"))
    jtm.call("pcount_while_jtm", 0, trace=True)
    print("  x = 0: " + " ; ".join(s.text.split()[0] + ("(%s)" % s.note if s.note and
                                    "Machine" not in s.note else "") for s in jtm.trace))
    print("  -> jump straight to the test, which fails: the body never runs.\n")

    print("Observations:")
    print("  * Every loop is a backward conditional jump. do-while tests at the bottom;")
    print("    while/for must also handle 'zero iterations': gcc -Og jumps to the test")
    print("    first (jump to middle), clang and gcc -O1 test once up front (guarded do).")
    print("  * Instruction counts grow with the number of iterations: pcount_do/while")
    print("    iterate once per bit position up to the highest 1 bit (7 instructions")
    print("    each in clang's code), while the for loop always iterates 64 times")
    print("    (7 instructions each at -Og, 5 at -O1), whatever x is.")
    print("  * Compilers know instructions you may not (bt, adc). When you see an unknown")
    print("    one, look it up -- the C semantics are still the same.")


if __name__ == "__main__":
    main()
