/* =============================================================================
 * 04_blocking.c  --  blocking turns a memory-bound multiply cache-friendly
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Even the best loop order re-reads each matrix O(n) times from memory for
 *     large n. BLOCKING reorders the work into small tiles that fit in cache
 *     and are fully reused before eviction. How much does it help, and what
 *     block size is best?
 *
 * [How to build & run]
 *   make && ./build/04_blocking            (native)
 *          ./build/04_blocking 1024        (choose n)
 *
 * [How to read the output]
 *   The naive (kij, already cache-friendly per element) multiply vs the blocked
 *   multiply at several block sizes B, timed, with GFLOP/s and speedup. All
 *   compute the same product (checked). Times vary run to run.
 *
 * [Systems link / CS:APP 6.6]
 *   The slides' analysis: naive multiply has ~(9/8) n^3 misses; blocking with
 *   tile B (chosen so three B x B tiles fit in cache, 3B^2 < C) has ~1/(4B) n^3
 *   -- fewer by a factor of ~B. The inherent temporal locality (each element is
 *   used O(n) times) is only realized if the program keeps the tile resident.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "timer.h"

static int N;
#define A(i, j) a[(i) * N + (j)]
#define B(i, j) b[(i) * N + (j)]
#define C(i, j) c[(i) * N + (j)]

/* [Idea] The textbook baseline: the simple ijk triple loop. Its inner loop
 *   over k walks B DOWN a column (stride n), so for large n almost every B
 *   access misses -- the slides' ~(9/8) n^3 misses. */
static void mm_naive(double *a, double *b, double *c) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) {
            double s = 0;
            for (int k = 0; k < N; k++) s += A(i, k) * B(k, j);
            C(i, j) += s;
        }
}

/* [Idea] Blocked multiply: cover C in bs x bs tiles, and for each tile do the
 *   full bs x bs x bs mini-multiply before moving on, so each tile of A and B
 *   is loaded once and reused bs times while resident. */
static void mm_blocked(double *a, double *b, double *c, int bs) {
    for (int ii = 0; ii < N; ii += bs)
        for (int kk = 0; kk < N; kk += bs)
            for (int jj = 0; jj < N; jj += bs) {
                int imax = ii + bs < N ? ii + bs : N;
                int kmax = kk + bs < N ? kk + bs : N;
                int jmax = jj + bs < N ? jj + bs : N;
                for (int i = ii; i < imax; i++)
                    for (int k = kk; k < kmax; k++) {
                        double r = A(i, k);
                        for (int j = jj; j < jmax; j++) C(i, j) += r * B(k, j);
                    }
            }
}

int main(int argc, char **argv)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    N = argc > 1 ? atoi(argv[1]) : 1536;
    printf("=== Demo 04: blocked matrix multiply, n = %d (%s) ===\n\n", N, arch);
    size_t bytes = (size_t)N * N * sizeof(double);
    double *a = malloc(bytes), *b = malloc(bytes), *c = malloc(bytes), *ref = malloc(bytes);
    if (!a || !b || !c || !ref) { perror("malloc"); return 1; }
    for (int i = 0; i < N * N; i++) { a[i] = (i % 7) - 3; b[i] = (i % 5) - 2; }

    memset(c, 0, bytes);
    double t0 = wall_seconds();
    mm_naive(a, b, c);
    double tn = wall_seconds() - t0;
    memcpy(ref, c, bytes);
    printf("  %-16s %-10s %-10s %s\n", "version", "time (s)", "GFLOP/s", "speedup");
    printf("  %-16s %-10.3f %-10.2f %s\n", "naive (ijk)", tn, 2.0 * N * N * N / tn / 1e9, "1.0x");

    int blocks[] = {8, 16, 32, 64, 128};
    double best = tn;
    int best_bs = 0;
    for (size_t bi = 0; bi < sizeof(blocks) / sizeof(blocks[0]); bi++) {
        int bs = blocks[bi];
        memset(c, 0, bytes);
        t0 = wall_seconds();
        mm_blocked(a, b, c, bs);
        double tb = wall_seconds() - t0;
        if (memcmp(ref, c, bytes) != 0) { printf("  blocked B=%-3d   MISMATCH\n", bs); continue; }
        char lbl[24];
        snprintf(lbl, sizeof lbl, "blocked B=%d", bs);
        printf("  %-16s %-10.3f %-10.2f %.2fx\n", lbl, tb, 2.0 * N * N * N / tb / 1e9, tn / tb);
        if (tb < best) { best = tb; best_bs = bs; }
    }
    printf("\n  Best: block size %d, %.2fx faster than the naive multiply.\n", best_bs, tn / best);
    printf("  A B x B tile of doubles is %d KiB; three tiles (two inputs, one output)\n",
           best_bs * best_bs * (int)sizeof(double) / 1024);
    printf("  should fit in a cache level (the slides' 3B^2 < C). Too-small tiles lose\n");
    printf("  spatial locality; too-large ones no longer fit.\n\n");
    printf("Observations:\n");
    printf("  * Blocking does not change the O(n^3) arithmetic; it reorders it so each\n"
           "    tile is fully reused while resident, cutting misses from ~(9/8)n^3 to\n"
           "    ~1/(4B) n^3 -- about B times fewer.\n");
    printf("  * The win grows with n, where the naive version re-reads matrices from\n"
           "    DRAM; for small n that fits in cache there is little to gain.\n");
    printf("  * The best block size balances 'fits in cache' against 'uses full blocks';\n"
           "    it is found by measuring, as here, not guessed.\n");
    free(a); free(b); free(c); free(ref);
    return 0;
}
