/* =============================================================================
 * 01_bit_level_ops.c  --  Boolean algebra on bit vectors; & vs &&; shifts
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - What do &, |, ^, ~ do to a whole byte at once?
 *   - How can 8 bits represent a SET, and why are &, |, ^, ~ then exactly
 *     intersection, union, symmetric difference and complement?
 *   - Why is `x & 1 == 0` a bug, and why is `p && *p` safe but `&` is not?
 *   - What is the difference between a logical and an arithmetic right shift?
 *   - What happens when you shift by 32 or more? (undefined in C!)
 *
 * [How to build & run]
 *   make 01_bit_level_ops && ./01_bit_level_ops        (or simply: make run)
 *
 * [How to read the output]
 *   Each PART prints operands and results in hex AND in binary, so you can
 *   check every bit with your own eyes. "Observations" summarizes.
 *
 * [Systems link / CS:APP 2.1.6-2.1.9]
 *   Bit-level operations are the CPU's cheapest instructions (AND, OR, XOR,
 *   NOT, SHL, SHR, SAR -- one cycle each). Masks, flags, sets, hash functions,
 *   checksums, graphics and network protocols are all built from them, and
 *   Lab 1 (datalab) is entirely about reasoning with them.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdint.h>
#include "bits.h"

/* ---------------------------------------------------------------------------
 * shift_by  --  x << k with a count the compiler cannot see in advance.
 *
 * [Idea]
 *   In C, shifting by k >= the width of the type is UNDEFINED BEHAVIOR. To
 *   observe what the HARDWARE does, we hide the count behind `volatile` and
 *   `noinline`, so the compiler must emit a real shift instruction.
 * [Parameters] x -- 32-bit unsigned value; k -- shift count.
 * [Returns] whatever the machine's shift instruction produces.
 * [Edge cases] k >= 32 is undefined in C. x86-64 and arm64 both happen to use
 *   only the low 5 bits of the count for 32-bit shifts (k mod 32), but the
 *   compiler is allowed to assume k < 32 and optimize on that assumption.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static uint32_t shift_by(uint32_t x, volatile int k) {
    return x << k;
}

int main(void) {
    printf("=== Demo 01: bit-level operations ===\n\n");

    /* ---- PART A: &, |, ^, ~ on whole bytes ---------------------------- */
    unsigned char a = 0x69, b = 0x55;      /* the slide's example operands    */
    printf("PART A: Boolean operators work on ALL bits in parallel\n");
    printf("  a     = 0x%02x = %s\n", a, bin(a, 8));
    printf("  b     = 0x%02x = %s\n", b, bin(b, 8));
    /* [C tip] Operands narrower than int are first PROMOTED to int, so ~a is */
    /* an int with 24 extra one-bits on top. We cast back to unsigned char to */
    /* keep only the 8 bits we care about.                                    */
    printf("  a & b = 0x%02x = %s   (1 only where BOTH are 1)\n",
           (unsigned char)(a & b), bin(a & b, 8));
    printf("  a | b = 0x%02x = %s   (1 where EITHER is 1)\n",
           (unsigned char)(a | b), bin(a | b, 8));
    printf("  a ^ b = 0x%02x = %s   (1 where they DIFFER)\n",
           (unsigned char)(a ^ b), bin(a ^ b, 8));
    printf("  ~a    = 0x%02x = %s   (every bit flipped)\n",
           (unsigned char)~a, bin((unsigned char)~a, 8));
    printf("  ~0x41 = 0x%02x,  ~0x00 = 0x%02x\n\n",
           (unsigned char)~0x41, (unsigned char)~0x00);

    /* ---- PART B: bit vectors as sets ----------------------------------- */
    printf("PART B: a w-bit vector is a subset of {0..w-1}  (bit j set <=> j in set)\n");
    printf("  A = %s = %s\n", bin(a, 8), set_string(a, 8));
    printf("  B = %s = %s\n", bin(b, 8), set_string(b, 8));
    printf("  A & B  intersection          = %s\n", set_string(a & b, 8));
    printf("  A | B  union                 = %s\n", set_string(a | b, 8));
    printf("  A ^ B  symmetric difference  = %s\n", set_string(a ^ b, 8));
    printf("  ~A     complement            = %s\n", set_string((unsigned char)~a, 8));
    /* Exhaustive check that the set laws hold bit-wise: De Morgan's law      */
    /* ~(A & B) == ~A | ~B for every pair of bytes.                            */
    int demorgan_fail = 0;
    for (int x = 0; x < 256; x++)
        for (int y = 0; y < 256; y++)
            if ((unsigned char)~(x & y) != (unsigned char)(~x | ~y)) demorgan_fail++;
    printf("  De Morgan ~(A&B) == ~A|~B checked on all 65536 byte pairs: %d failures\n\n",
           demorgan_fail);

    /* ---- PART C: bitwise vs logical operators ------------------------- */
    printf("PART C: logical operators (&&, ||, !) see only zero / non-zero\n");
    printf("  !0x41 = %d   !0x00 = %d   !!0x41 = %d\n", !0x41, !0x00, !!0x41);
    printf("  0x69 && 0x55 = %d   but   0x69 & 0x55 = 0x%02x\n", a && b, a & b);
    printf("  0x69 || 0x55 = %d   but   0x69 | 0x55 = 0x%02x\n", a || b, a | b);
    /* Short-circuit evaluation: in p && *p, *p is evaluated ONLY if p != 0.  */
    int *p = NULL;
    int safe = p && *p;                    /* never dereferences NULL          */
    printf("  int *p = NULL;  p && *p = %d   (right side never evaluated)\n", safe);
    /* The precedence trap: == binds tighter than &. So `x & 1 == 0` means    */
    /* x & (1 == 0) = x & 0 = 0, ALWAYS. We write the parsed form explicitly  */
    /* (writing the trap directly makes -Wall warn, which is exactly why you  */
    /* should always compile with -Wall).                                     */
    int x = 4;
    printf("  x = 4 (even).  intended (x & 1) == 0  -> %d\n", (x & 1) == 0);
    printf("                 written   x & 1 == 0   parses as x & (1 == 0) -> %d\n\n",
           x & (1 == 0));

    /* ---- PART D: shifts ------------------------------------------------ */
    printf("PART D: left shift, logical right shift, arithmetic right shift\n");
    unsigned char vals[] = {0x63, 0x95};   /* CS:APP's examples                */
    for (int i = 0; i < 2; i++) {
        unsigned char u = vals[i];
        signed char   s = (signed char)u;  /* same bits, viewed as signed      */
        unsigned char lsh = (unsigned char)(u << 4);
        unsigned char lrs = (unsigned char)(u >> 4);       /* unsigned: logical */
        unsigned char ars = (unsigned char)(s >> 4);       /* signed: arithmetic*/
        printf("  x = %s   x<<4 = %s   logical x>>4 = %s   arithmetic x>>4 = %s\n",
               bin(u, 8), bin(lsh, 8), bin(lrs, 8), bin(ars, 8));
    }
    printf("  (logical fills with 0s; arithmetic copies the sign bit. In C, >> on\n");
    printf("   an UNSIGNED value is logical; on a SIGNED value gcc/clang use arithmetic.)\n\n");

    /* ---- PART E: shift counts >= width ---------------------------------- */
    printf("PART E: shifting a 32-bit value by k >= 32 is UNDEFINED in C\n");
    int ks[] = {31, 32, 33, 36};
    for (int i = 0; i < 4; i++)
        printf("  1u << %-2d  ->  0x%08x   (this machine's shift instruction)\n",
               ks[i], shift_by(1u, ks[i]));
    printf("  Both x86-64 and arm64 use only k mod 32 for 32-bit shifts, so 1u<<32\n");
    printf("  gives 1, not 0. C does not promise even that; build with\n");
    printf("  -fsanitize=undefined to get a run-time error instead.\n\n");

    printf("Observations:\n");
    printf("  * &, |, ^, ~ act on every bit independently: a byte is 8 parallel booleans.\n");
    printf("  * As sets, they are intersection, union, symmetric difference, complement;\n");
    printf("    all Boolean-algebra laws (e.g. De Morgan) hold bit by bit.\n");
    printf("  * && || ! return only 0 or 1 and short-circuit; & | ~ do neither. Mixing\n");
    printf("    them up, or forgetting that == binds tighter than &, is a classic bug.\n");
    printf("  * Right shift has two flavours: logical (unsigned) and arithmetic (signed).\n");
    printf("  * Shift counts must be in [0, width); anything else is undefined behavior.\n");
    return 0;
}
