"""
01_cache_sim.py -- cache mechanics: the slides' examples, miss types, matmul
=============================================================================

[Questions this demo answers]
  - An address splits into tag / set index / block offset. Given a tiny cache
    and a trace, which accesses hit and which miss, and what is the cache state?
    (The slides' direct-mapped and 2-way simulations.)
  - How do we separate the three miss kinds (cold / conflict / capacity)?
  - The slides CLAIM average misses per inner-loop iteration of 1.25 (ijk),
    0.5 (kij) and 2.0 (jki) for matrix multiply. Can we confirm those by
    simulating the actual access pattern?

[How to run]
  python3 01_cache_sim.py

[How to read the output]
  PART A replays the slides' two traces and prints the cache state and the
  hit/miss/eviction tally. PART B shows conflict vs capacity misses on a
  thrashing pattern. PART C runs the three matrix-multiply loop orders through
  the simulator and compares the measured miss rate with the slides' numbers.

[About this tool]  cachesim.py is a teaching simulator (see its header). It is
  NOT the cachelab csim.c you are asked to write: it is Python, reads no
  valgrind trace, and has no command-line cache-parameter interface.

[Systems link / CS:APP 6.4-6.6]
  tag/set/offset, direct-mapped vs set-associative, the three misses, and why
  the access PATTERN (not the operation count) sets the miss rate.
"""

import cachesim


def part_a():
    print("PART A: the slides' simulations (4-bit addresses, 1 byte per read)")
    trace = [0, 1, 7, 8, 0]
    print("  (a) Direct-mapped: S=4 sets, E=1 line/set, B=2 bytes/block  (t=1,s=2,b=1)")
    c = cachesim.Cache(4, 1, 2)
    for a in trace:
        t, si, bo = c.split(a)
        r = c.access(a)
        print("    addr %d = %s -> tag %d set %d off %d : %s" % (a, format(a, "04b"), t, si, bo, r))
    print("    " + c.summary())
    print(c.state_table())
    print("  (b) 2-way set associative: S=2, E=2, B=2  (t=2,s=1,b=1)")
    c2 = cachesim.Cache(2, 2, 2)
    for a in trace:
        t, si, bo = c2.split(a)
        print("    addr %d = %s -> tag %d set %d off %d : %s" % (a, format(a, "04b"), t, si, bo, c2.access(a)))
    print("    " + c2.summary())
    print("  The last access to 0 MISSES in the direct-mapped cache (address 8 evicted")
    print("  it from set 0) but HITS in the 2-way cache (set 0 holds both blocks).")
    print("  Associativity trades that conflict miss for a second line per set.\n")


def part_b():
    print("PART B: conflict vs capacity misses")
    print("  A direct-mapped cache, S=8 sets, B=8 bytes. Two addresses 64 bytes apart")
    print("  map to the SAME set; alternating them thrashes a cache that is far from full:")
    c = cachesim.Cache(8, 1, 8)
    for _ in range(4):
        c.access(0)       # block 0  -> set 0
        c.access(64)      # block 8  -> set 0 (64/8=8, 8 mod 8 = 0): same set!
    print("    accesses 0,64,0,64,... : " + c.summary())
    print("    every repeat is a CONFLICT miss: the cache has 8 lines but both blocks")
    print("    insist on set 0. A 2-way cache would hold both and hit:")
    c2 = cachesim.Cache(8, 2, 8)
    for _ in range(4):
        c2.access(0); c2.access(64)
    print("    same trace, 2-way: " + c2.summary())
    print("  A CAPACITY miss is different: scanning more distinct blocks than the cache")
    print("  holds, so even full associativity cannot avoid eviction:")
    c3 = cachesim.Cache(4, 1, 8)            # holds 4 blocks
    for _ in range(3):
        for blk in range(6):               # 6 distinct blocks > 4 lines
            c3.access(blk * 8)
    print("    6 blocks through a 4-block cache, 3 passes: " + c3.summary())
    print()


def matmul_misses(order, n, B_bytes, S, E):
    """
    [Idea] Simulate the memory accesses of one n x n double matrix multiply in
      the given loop order, through a cache (S sets, E lines, B_bytes block),
      and return misses per inner-loop iteration for the A and B reads.
    [Parameters] order -- 'ijk', 'kij' or 'jki'; the three the slides analyze.
    [Returns] (misses, inner_iterations).
    [Edge cases] c[][] accumulation is counted for kij/jki (a store each inner
      step) and held in a register for ijk, matching the slides.
    """
    c = cachesim.Cache(S, E, B_bytes)
    DB = 8                                           # a double is 8 bytes
    base_a, base_b, base_c = 0, n * n * DB, 2 * n * n * DB
    addr = lambda base, r, col: base + (r * n + col) * DB     # noqa: E731
    iters = 0

    def rd(base, r, col):
        c.access(addr(base, r, col))

    if order == "ijk":
        for i in range(n):
            for j in range(n):
                for k in range(n):
                    iters += 1
                    rd(base_a, i, k)                 # a[i][k]: stride 1 in k
                    rd(base_b, k, j)                 # b[k][j]: stride n in k
    elif order == "kij":
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    iters += 1
                    rd(base_b, k, j)                 # b[k][j]: stride 1 in j
                    rd(base_c, i, j)                 # c[i][j]: stride 1 in j (read+write)
    elif order == "jki":
        for j in range(n):
            for k in range(n):
                for i in range(n):
                    iters += 1
                    rd(base_a, i, k)                 # a[i][k]: stride n in i
                    rd(base_c, i, j)                 # c[i][j]: stride n in i
    return c.misses, iters


def part_c():
    print("PART C: confirming the slides' matrix-multiply miss rates")
    print("  A small cache (S=64 sets, E=1, B=32 bytes = 4 doubles = 2 KiB total), far")
    print("  smaller than the 32 KiB matrices but able to keep a few rows resident.")
    n = 64
    print("  n = %d; the slides' asymptotic prediction: ijk 1.25, kij 0.5, jki 2.0\n" % n)
    predicted = {"ijk": 1.25, "kij": 0.5, "jki": 2.0}
    print("    %-6s %-13s %-15s %s" % ("order", "misses/iter", "slides (asympt.)", "inner-loop stride"))
    strides = {"ijk": "a:1  b:n", "kij": "b:1  c:1", "jki": "a:n  c:n"}
    for order in ("ijk", "kij", "jki"):
        misses, iters = matmul_misses(order, n, 32, 64, 1)
        print("    %-6s %-13.2f %-15s %s" % (order, misses / iters, predicted[order], strides[order]))
    print("\n  The RANKING matches the slides exactly -- kij (two stride-1 inner accesses)")
    print("  best, jki (two stride-n accesses) worst at exactly 2.0, ijk in between --")
    print("  and the operation COUNT is identical for all three. The absolute ijk/kij")
    print("  figures depend on how much of a row the finite cache keeps resident; they")
    print("  approach the slides' 1.25 / 0.5 as n grows and the cache shrinks relative")
    print("  to it. Every stride-n access misses (jki = 2.0 exactly); a stride-1 access")
    print("  misses only on the first of each 4-double block.\n")


def main():
    print("=== Demo 01: cache mechanics ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * An address is tag | set index | block offset; the set index picks the")
    print("    set, the tag identifies the block within it, the offset the byte.")
    print("  * Associativity (E > 1) removes conflict misses at the cost of more")
    print("    comparisons per access; capacity misses need a bigger cache, not more E.")
    print("  * For the same O(n^3) work, loop order changes the miss rate 4x (kij vs")
    print("    jki), because it changes the inner-loop stride through each matrix.")


if __name__ == "__main__":
    main()
