/* =============================================================================
 * 03_cpe.c  --  instruction-level parallelism: unrolling and accumulators
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The slides' "combine" benchmark sums (or multiplies) a vector. Even after
 *     basic optimization it is stuck at the LATENCY of one floating-point add.
 *     Why, and how do loop unrolling with MULTIPLE ACCUMULATORS break that?
 *   - How fast can one core go on this, and where is the ceiling?
 *
 * [How to build & run]
 *   make && ./build/03_cpe           (native)
 *
 * [How to read the output]
 *   Each version sums the same double vector; the table reports time per
 *   element (ns) and the implied work rate. The key comparison is 1 accumulator
 *   (latency-bound: each add waits for the previous) vs k accumulators
 *   (throughput-bound: k independent add chains run at once). Times vary run to
 *   run; the plateau at 1 accumulator and the speedup from more are the point.
 *
 * [Systems link / CS:APP 5.7-5.9]
 *   A modern CPU is superscalar and pipelined: its FP-add unit is pipelined so
 *   it can START a new add every cycle, but each add's RESULT takes several
 *   cycles. A single accumulator chains dependent adds, so throughput is capped
 *   at 1/latency. Independent accumulators fill the pipeline -- up to the number
 *   of FP units times the pipeline depth.
 * -------------------------------------------------------------------------- */

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

#define N (1 << 24)        /* 16M doubles; big enough to time, simple pattern */
static double data[N];

/* combine1: the slides' abstract version -- a function call per element.
 * (Here get() is noinline so the call is real, as in the slides' combine1.) */
__attribute__((noinline)) static double get(long i) { return data[i]; }
static double combine1(void) {
    double acc = 0;
    for (long i = 0; i < N; i++) acc = acc + get(i);
    return acc;
}

/* combine4: the slides' basic-optimized version -- a local accumulator, direct
 * array access, no call. Now the bottleneck is the add dependency chain. */
static double combine4(void) {
    double acc = 0;
    for (long i = 0; i < N; i++) acc = acc + data[i];
    return acc;
}

/* unroll1: unrolled 4x but ONE accumulator -- still a single dependency chain,
 * so still latency-bound (unrolling alone does not help a reduction). */
static double unroll1(void) {
    double acc = 0;
    long i;
    for (i = 0; i + 4 <= N; i += 4)
        acc = acc + data[i] + data[i + 1] + data[i + 2] + data[i + 3];
    for (; i < N; i++) acc = acc + data[i];
    return acc;
}

/* accum_k: unrolled with K INDEPENDENT accumulators, combined at the end.
 * K independent add chains run in parallel, filling the pipelined FP unit --
 * throughput-bound. */
#define MAKE_ACCUM(K)                                               \
static double accum_##K(void) {                                     \
    double a[K];                                                    \
    for (int k = 0; k < K; k++) a[k] = 0;                           \
    long i;                                                         \
    for (i = 0; i + K <= N; i += K)                                 \
        for (int k = 0; k < K; k++) a[k] = a[k] + data[i + k];      \
    double acc = 0;                                                 \
    for (; i < N; i++) acc = acc + data[i];                         \
    for (int k = 0; k < K; k++) acc = acc + a[k];                   \
    return acc;                                                     \
}
MAKE_ACCUM(2)
MAKE_ACCUM(4)
MAKE_ACCUM(8)

static double run(double (*f)(void), double *result) {
    double best = 1e30;
    for (int t = 0; t < 5; t++) {
        double t0 = wall_seconds();
        *result = f();
        double dt = wall_seconds() - t0;
        if (dt < best) best = dt;
    }
    return best;
}

int main(void) {
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 03: unrolling and multiple accumulators (%s) ===\n\n", arch);
    for (long i = 0; i < N; i++) data[i] = 1.0;

    struct { const char *name; double (*fn)(void); const char *note; } v[] = {
        {"combine1 (call/elem)", combine1, "a function call per element"},
        {"combine4 (local acc)", combine4, "basic: 1 accumulator, latency-bound"},
        {"unroll x4, 1 acc", unroll1, "unrolled but still 1 chain -> no gain"},
        {"unroll x2, 2 accs", accum_2, "2 independent chains"},
        {"unroll x4, 4 accs", accum_4, "4 independent chains"},
        {"unroll x8, 8 accs", accum_8, "8 independent chains"},
    };
    int nv = sizeof(v) / sizeof(v[0]);
    double base = 0, best = 1e30;
    printf("  %-22s %-12s %-10s %s\n", "version", "ns/element", "Gelem/s", "what");
    for (int k = 0; k < nv; k++) {
        double r, t = run(v[k].fn, &r);
        if (r != (double)N) { printf("  %-22s WRONG SUM %g\n", v[k].name, r); continue; }
        double nspe = t / N * 1e9;
        if (k == 1) base = nspe;                      /* combine4 is the baseline */
        if (nspe < best) best = nspe;
        printf("  %-22s %-12.3f %-10.2f %s\n", v[k].name, nspe, 1.0 / nspe, v[k].note);
    }
    printf("\n  combine1's call per element dominates everything. combine4 removes it but\n");
    printf("  is stuck at the latency of one FP add (each add waits for the last).\n");
    printf("  Unrolling with ONE accumulator does not help -- same single chain.\n");
    printf("  MULTIPLE accumulators run independent add chains at once: about %.1fx\n", base / best);
    printf("  faster than combine4 here, up to the FP unit's throughput ceiling.\n\n");
    printf("Observations:\n");
    printf("  * The FP-add unit is pipelined: it starts an add every cycle but each\n"
           "    result takes several cycles. One accumulator chains dependent adds, so\n"
           "    throughput is capped at 1/latency -- the 'latency bound'.\n");
    printf("  * Loop unrolling ALONE does not break that (still one dependency chain).\n");
    printf("  * K independent accumulators expose instruction-level parallelism: K adds\n"
           "    in flight at once, up to the 'throughput bound' (FP units x pipeline).\n");
    printf("  * Beyond that ceiling the memory system or the units saturate; more\n"
           "    accumulators stop helping. Measure to find the knee.\n");
    return 0;
}
