/* =============================================================================
 * 03_branch_prediction.c  --  why compilers like conditional moves
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - A branch costs almost nothing when the CPU guesses its direction right.
 *     What does a WRONG guess cost?
 *   - Why does the same loop run several times faster on SORTED data than on
 *     random data -- with exactly the same instructions and the same answer?
 *   - Why does a branch-free (conditional-move style) loop not care?
 *
 * [How to build & run]
 *   make build/branch_prediction && ./build/branch_prediction
 *   (built NATIVELY at -O1: this measures the CPU you are sitting at. -O1
 *    keeps the compiler from vectorizing the loops, which would hide the
 *    effect behind a different one.)
 *
 * [How to read the output]
 *   Nanoseconds per array element for three versions of "sum the elements
 *   that are >= 128", on random data and on the same data sorted. Timing
 *   varies from run to run; compare the RATIOS.
 *
 * [Systems link / CS:APP 3.6.6, 5.11]
 *   The CPU fetches and starts instructions far ahead of the one it is
 *   finishing (pipelining, out-of-order execution). At a conditional branch
 *   it must GUESS the direction and keep going; a branch predictor learns
 *   from history. On sorted data the branch is "no, no, ..., no, yes, yes,
 *   ..." -- trivially predictable. On random data it is a coin flip, the
 *   guess is wrong half the time, and every wrong guess discards the
 *   speculative work (~15-20 cycles). A conditional move has no direction to
 *   guess: it waits for the data instead.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N (1L << 20)        /* 1 Mi elements = 8 MiB */
#define REPS 7

static long data_random[N], data_sorted[N];

/* ---------------------------------------------------------------------------
 * sum_branchy  --  if (a[i] >= t) s += a[i];   with a guaranteed real branch.
 *
 * [Idea] The empty `asm volatile` inside the if is an instruction with a
 *   side effect as far as the compiler knows, so it may not compute the
 *   'then' part speculatively: the if stays a conditional jump.
 * [Parameters] a -- array; n -- length; t -- threshold.
 * [Returns] the sum of elements >= t.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static long sum_branchy(const long *a, long n, long t) {
    long s = 0;
    for (long i = 0; i < n; i++) {
        if (a[i] >= t) {
            __asm__ volatile("");
            s += a[i];
        }
    }
    return s;
}

/* ---------------------------------------------------------------------------
 * sum_branchless  --  the same sum with NO data-dependent branch.
 *
 * [Idea] mask = -(a[i] >= t) is all ones (-1) when the condition holds and
 *   0 otherwise, so a[i] & mask is a[i] or 0. This is the arithmetic version
 *   of a conditional move. The empty asm on s stops the compiler from
 *   turning the loop back into something clever.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static long sum_branchless(const long *a, long n, long t) {
    long s = 0;
    for (long i = 0; i < n; i++) {
        long mask = -(long)(a[i] >= t);
        s += a[i] & mask;
        __asm__ volatile("" : "+r"(s));
    }
    return s;
}

/* ---------------------------------------------------------------------------
 * sum_plain  --  the natural C; the compiler decides branch vs cmov/csel.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static long sum_plain(const long *a, long n, long t) {
    long s = 0;
    for (long i = 0; i < n; i++)
        if (a[i] >= t)
            s += a[i];
    return s;
}

static double now(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec + 1e-9 * ts.tv_nsec;
}

static int cmp_long(const void *x, const void *y) {
    long a = *(const long *)x, b = *(const long *)y;
    return (a > b) - (a < b);
}

/* best-of-REPS time per element, in nanoseconds; also returns the sum. */
static double time_ns(long (*f)(const long *, long, long), const long *a, long *sum_out) {
    double best = 1e30;
    for (int r = 0; r < REPS; r++) {
        double t0 = now();
        long s = f(a, N, 128);
        double dt = now() - t0;
        if (dt < best) best = dt;
        *sum_out = s;
    }
    return best * 1e9 / N;
}

int main(void) {
    printf("=== Demo 03: the cost of branch mispredictions ===\n");
    printf("sum of the elements >= 128 in %ld random values from 0..255\n\n", N);

    srand(15213);                                  /* fixed seed: same data each run */
    for (long i = 0; i < N; i++)
        data_random[i] = data_sorted[i] = rand() % 256;
    qsort(data_sorted, N, sizeof(long), cmp_long);

    struct { const char *name; long (*f)(const long *, long, long); } v[] = {
        {"branchy (real jump)  ", sum_branchy},
        {"branchless (mask)    ", sum_branchless},
        {"plain C (compiler's) ", sum_plain},
    };
    printf("  %-22s %12s %12s %10s\n", "version", "random ns/el", "sorted ns/el", "ratio");
    double branchy_r = 0, branchy_s = 0;
    for (int k = 0; k < 3; k++) {
        long s1, s2;
        double tr = time_ns(v[k].f, data_random, &s1);
        double ts = time_ns(v[k].f, data_sorted, &s2);
        printf("  %-22s %12.3f %12.3f %9.1fx   (sums equal: %s)\n",
               v[k].name, tr, ts, tr / ts, s1 == s2 ? "yes" : "NO");
        if (k == 0) { branchy_r = tr; branchy_s = ts; }
    }
    /* About half the random elements go each way, so about N/2 guesses are */
    /* wrong per pass (a predictor cannot beat a coin flip on random data). */
    double per_miss = (branchy_r - branchy_s) * N / (N / 2.0);
    printf("\n  extra time of the branchy loop on random data, spread over ~N/2\n");
    printf("  mispredictions: about %.1f ns per misprediction\n", per_miss);
    printf("  (at a clock of 4-4.5 GHz that is roughly %.0f-%.0f cycles)\n\n",
           per_miss * 4.0, per_miss * 4.5);

    printf("Observations:\n");
    printf("  * Same instructions, same answer: the branchy loop is several times\n");
    printf("    slower on random data, because the CPU guesses the branch wrong about\n");
    printf("    half the time and throws away the work it did after each wrong guess.\n");
    printf("  * The branchless loop runs at the same speed on both inputs: there is\n");
    printf("    nothing to guess. That is why compilers turn short, safe if/else\n");
    printf("    statements into conditional moves (cmov on x86-64, csel on arm64).\n");
    printf("  * On sorted (predictable) data the branch is nearly free, so branchless\n");
    printf("    code is not always faster: it always pays for both sides.\n");
    return 0;
}
