/* =============================================================================
 * 05_you_have_to_know_assembly.c  --  Reality #2: you will rarely WRITE
 *     assembly, but to debug/tune/secure code you must READ what your C becomes.
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Does the machine really run "my" loop? (Often not -- the compiler may
 *     replace a summation loop with a one-line formula.)
 *   - Can the SAME C give a DIFFERENT ANSWER at -O0 vs -O2? (Yes, when the C
 *     has undefined behavior -- here, signed integer overflow from demo 01.)
 *   - How do I even look at the generated assembly? (`make asm`.)
 *
 * [How to build & run]
 *   make run         # runs this at BOTH -O2 and -O0 so you can see the flip
 *   make asm         # writes the x86-64 and arm64 assembly of this file
 *   # The default build is -O2; the Makefile also builds a .O0 variant.
 *
 * [How to read the output]
 *   Part 1 prints a sum and how long it took -- near-instant if the compiler
 *   closed-formed the loop. Part 2 prints inc_gt(INT_MAX); its value differs
 *   between the -O2 and -O0 builds. The two builds are run back to back by
 *   `make run`, labelled with their optimization level.
 *
 * [Systems link / CS:APP 3 and 5]
 *   The ISA (instruction set architecture) is the contract between your program
 *   and the hardware. The COMPILER is free to produce any machine code that
 *   honors the C abstract machine's observable behavior -- and it uses that
 *   freedom aggressively. Two consequences every systems programmer must
 *   internalize:
 *     (1) The assembly can be smarter than your source (Part 1): a loop with a
 *         closed form becomes a multiply, so "number of C statements executed"
 *         is not what runs.
 *     (2) If your C has UNDEFINED BEHAVIOR, the compiler may assume it never
 *         happens and optimize on that assumption (Part 2). Signed overflow is
 *         UB (demo 01), so `x + 1 > x` may be folded to constant "true" -- the
 *         answer then depends on the optimizer, not the math. You can only SEE
 *         this by reading the assembly or by testing at multiple -O levels.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <limits.h>     /* INT_MAX                                             */
#include "timer.h"      /* wall_seconds()                                      */

/* ---------------------------------------------------------------------------
 * sum_to_n  --  add up 0 + 1 + ... + (n-1) with an explicit loop.
 *
 * [Idea]
 *   Written as a loop, but mathematically it equals n*(n-1)/2. A good optimizer
 *   recognizes this and emits the formula -- no loop at all. `make asm` shows a
 *   multiply (x86 `mul`/`shld`, arm `mul`/`umulh`) instead of a back-edge jump.
 * [Parameters] n -- how many terms (uses long = 64-bit to avoid overflow here).
 * [Returns] the sum as a long.
 * [Edge cases] n <= 0 returns 0 (the loop body never runs).
 * ------------------------------------------------------------------------- */
__attribute__((noinline, used))
static long sum_to_n(long n) {
    long s = 0;
    for (long i = 0; i < n; i++)
        s += i;
    return s;
}

/* ---------------------------------------------------------------------------
 * inc_gt  --  is x + 1 greater than x?  (mathematically: always, right?)
 *
 * [Idea]
 *   For real integers "x+1 > x" is always true. For a 32-bit int it is FALSE
 *   when x == INT_MAX, because x+1 wraps to INT_MIN (demo 01). BUT the C
 *   standard calls signed overflow undefined, so the compiler is allowed to
 *   assume it never occurs and fold this to constant 1. Whether it does depends
 *   on -O level: the whole point of the demo.
 * [Parameters] x -- an int.
 * [Returns] 1 or 0. At -O2 (typically) always 1; at -O0 it does the real
 *   comparison and returns 0 for x == INT_MAX.
 * [Edge cases] x == INT_MAX is exactly the interesting case.
 * ------------------------------------------------------------------------- */
__attribute__((noinline, used))
static int inc_gt(int x) {
    return x + 1 > x;
}

int main(void) {
    /* COMPILER_OPT_LEVEL is a string the Makefile #defines per build so the    */
    /* output labels itself. If it is not defined, say "unknown".               */
#ifndef COMPILER_OPT_LEVEL
#define COMPILER_OPT_LEVEL "unknown"
#endif
    printf("=== Demo 05: you have to know assembly  [build: %s] ===\n",
           COMPILER_OPT_LEVEL);

    /* ---- Part 1: the loop that is not a loop ----------------------------- */
    /* [C tip] Read n from a volatile so the compiler does NOT know its value   */
    /* at compile time. Otherwise it would precompute the whole answer to a     */
    /* constant; we want it to keep a real (closed-form) computation so that    */
    /* `make asm` shows the loop collapsed into a MULTIPLY, not just a mov.     */
    volatile long nv = 2000000000L;
    long n = nv;                   /* two billion iterations... or are there?  */
    double t0 = wall_seconds();
    long s = sum_to_n(n);
    double dt = (wall_seconds() - t0) * 1e3;    /* milliseconds                 */
    printf("Part 1: sum_to_n(%ld) = %ld in %.3f ms\n", n, s, dt);
    printf("        n*(n-1)/2 = %ld (matches). If dt is ~0 ms, the optimizer\n",
           n * (n - 1) / 2);
    printf("        replaced the 2e9-iteration loop with a multiply. Run\n");
    printf("        `make asm` to see the formula instead of a loop.\n\n");

    /* ---- Part 2: same C, answer depends on -O level ---------------------- */
    volatile int x = INT_MAX;      /* volatile so the CALL happens at runtime   */
    int r = inc_gt(x);
    printf("Part 2: inc_gt(INT_MAX) = %d\n", r);
    printf("        Math over real integers says 1; 32-bit wrap says 0.\n");
    printf("        At -O2 the compiler usually assumes signed overflow cannot\n");
    printf("        happen (it is undefined behavior) and returns 1; at -O0 it\n");
    printf("        does the real comparison and returns 0. Compare the two\n");
    printf("        labelled runs above/below.\n\n");

    printf("Observations:\n");
    printf("  * What runs is the ASSEMBLY, not your source: a summation loop can\n");
    printf("    become a single multiply (Part 1).\n");
    printf("  * Undefined behavior lets the optimizer change the ANSWER (Part 2):\n");
    printf("    inc_gt(INT_MAX) flips between -O0 and -O2. This is why demo 01's\n");
    printf("    integer wrap must be coaxed out with volatile and -fwrapv.\n");
    printf("  * Reading disassembly (gdb/objdump, or `make asm`) is a core skill;\n");
    printf("    Lectures 3-6 and the bomblab are built on it.\n");
    return 0;
}
