/* AI-assisted (Claude), human review required.
   bruteeq32 — prove two unary functions on 32-bit values identical by checking all 2^32 inputs, on every core.

   Build:  cc -O3 -march=native -std=c11 -pthread -DFUNCS='"myfuncs.h"' -o bruteeq32 bruteeq32.c
           (Apple clang: use -mcpu=native, or drop -march; the default FUNCS is funcs_example.h)
   Run:    ./bruteeq32 [-t threads] [-c log2_chunk] [-l lo] [-h hi] [-q]
   Exit:   0 = identical on the whole range, 1 = counterexample found (the smallest one is printed), 2 = usage.

   The functions file defines
       static inline uint32_t F(uint32_t x);   static inline uint32_t G(uint32_t x);
   and optionally FUNCS_NAME.  They are compiled into the checker (no function pointers), so the compiler can inline
   and vectorize the inner loop.

   Work split.  The range is cut into chunks of 2^c inputs (default c = 20: 4096 chunks for the full range).  Threads
   take chunks from a shared atomic counter, so fast and slow cores balance automatically.  Inside a chunk the inputs are
   checked in blocks of 4096 with a branch-free OR of F(x) ^ G(x) (vectorizable); only a block with a nonzero OR is
   rescanned for its first mismatch.  The compiler may prove F == G itself and drop the loop (it does for SWAR popcount
   vs __builtin_popcount); that is a proof by the compiler, not by evaluation — build with -DBRUTEEQ_OPAQUE to force
   evaluation, or write a hand-written instruction sequence as __asm__ volatile, which the compiler cannot reason about.  The smallest counterexample found so far is kept in an atomic; chunks entirely above
   it are skipped, so the reported counterexample is the smallest one and the run stops early.

   Chunk size trade-off: one atomic fetch per chunk costs ~10–100 ns; at ≥ 1 ns per input a 2^16 chunk already makes that
   overhead < 0.2 %.  Too-large chunks (2^26+) hurt load balance at the end of the run and early stopping.  2^18–2^22 is
   flat in practice; measure with -c.  This is plain exhaustive evaluation — there is nothing to bit-blast: that word
   belongs to SAT/SMT equivalence checking, which is what you need once the input space exceeds ~2^40 (e.g. binary
   functions on 32-bit pairs, 2^64 inputs). */
#define _GNU_SOURCE        /* Linux: sysconf(_SC_NPROCESSORS_ONLN), clock_gettime */
#define _DARWIN_C_SOURCE   /* macOS: the same (a strict _POSIX_C_SOURCE hides _SC_NPROCESSORS_ONLN) */
#include <stdatomic.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef __APPLE__
#include <pthread/qos.h>
#endif

#ifndef FUNCS
#define FUNCS "funcs_example.h"
#endif
#include FUNCS
#ifndef FUNCS_NAME
#define FUNCS_NAME FUNCS
#endif

/* -DBRUTEEQ_OPAQUE hides from the compiler that F and G see the same x, so it cannot prove F == G symbolically and
   skip the loop (clang recognizes SWAR popcount as ctpop and folds F(x) ^ G(x) to 0).  G is evaluated at x + z where z
   is a zero the compiler cannot see through (one empty asm per block), so the loop still vectorizes. */
static inline uint32_t opaque_zero(void) {
    uint32_t z = 0;
#ifdef BRUTEEQ_OPAQUE
    __asm__ volatile("" : "+r"(z));
#endif
    return z;
}

#ifndef BLOCK
#define BLOCK 4096            /* inputs per vectorized block; a power of two dividing every chunk */
#endif

/* OR of F(x) ^ G(x) over one aligned block: constant trip count and a 32-bit induction variable, so the compiler
   vectorizes it (the v1 loop with a 64-bit variable bound stayed scalar under gcc). */
static inline uint32_t block_or(uint32_t base) {
    uint32_t z = opaque_zero(), acc = 0;
#if defined(__clang__)
#pragma clang loop vectorize(enable) interleave(enable)
#elif defined(__GNUC__)
#pragma GCC ivdep
#endif
    for (uint32_t i = 0; i < BLOCK; i++) { uint32_t x = base + i; acc |= F(x) ^ G(x + z); }
    return acc;
}
static inline uint32_t range_or(uint64_t s, uint64_t e) {   /* unaligned edges, scalar */
    uint32_t z = opaque_zero(), acc = 0;
    for (uint64_t x = s; x < e; x++) acc |= F((uint32_t)x) ^ G((uint32_t)x + z);
    return acc;
}
static uint64_t first_mismatch(uint64_t s, uint64_t e) {
    uint32_t z = opaque_zero();
    for (uint64_t x = s; x < e; x++) if (F((uint32_t)x) != G((uint32_t)x + z)) return x;
    return UINT64_MAX;
}
static uint64_t lo = 0, hi = 1ull << 32;        /* half-open range [lo, hi) */
static unsigned logc = 20;
static uint64_t nchunks;
static atomic_uint_fast64_t next_chunk;
static atomic_uint_fast64_t best;               /* smallest mismatching input found, or UINT64_MAX */
static atomic_uint_fast64_t checked;

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

static void note_mismatch(uint64_t x) {
    uint64_t cur = atomic_load(&best);
    while (x < cur && !atomic_compare_exchange_weak(&best, &cur, x)) { }
}

static void *worker(void *arg) {
    (void)arg;
#ifdef __APPLE__
    pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);   /* prefer performance cores */
#endif
    uint64_t done = 0;
    for (;;) {
        uint64_t c = atomic_fetch_add(&next_chunk, 1);
        if (c >= nchunks) break;
        uint64_t a = lo + (c << logc), b = a + (1ull << logc);
        if (b > hi) b = hi;
        if (a >= atomic_load_explicit(&best, memory_order_relaxed)) break;   /* chunks are handed out in order */
        for (uint64_t s = a; s < b; ) {
            uint64_t e;
            uint32_t acc;
            if ((s & (BLOCK - 1)) == 0 && s + BLOCK <= b) { e = s + BLOCK; acc = block_or((uint32_t)s); }
            else { e = (s | (BLOCK - 1)) + 1; if (e > b) e = b; acc = range_or(s, e); }
            done += e - s;
            if (acc) { uint64_t x = first_mismatch(s, e); if (x != UINT64_MAX) note_mismatch(x); goto next; }
            s = e;
        }
    next:;
    }
    atomic_fetch_add(&checked, done);
    return NULL;
}

static uint64_t parse(const char *s) { return strtoull(s, NULL, 0); }

int main(int argc, char **argv) {
    long th = sysconf(_SC_NPROCESSORS_ONLN);
    int quiet = 0, reps = 1;
    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-t") && i + 1 < argc) th = atol(argv[++i]);
        else if (!strcmp(argv[i], "-c") && i + 1 < argc) logc = (unsigned)atoi(argv[++i]);
        else if (!strcmp(argv[i], "-l") && i + 1 < argc) lo = parse(argv[++i]);
        else if (!strcmp(argv[i], "-h") && i + 1 < argc) hi = parse(argv[++i]) + 1;   /* inclusive upper end */
        else if (!strcmp(argv[i], "-q")) quiet = 1;
        else if (!strcmp(argv[i], "-r") && i + 1 < argc) reps = atoi(argv[++i]);   /* benchmark: best of r runs */
        else { fprintf(stderr, "usage: %s [-t threads] [-c log2_chunk (log2 BLOCK..30)] [-l lo] [-h hi] [-q] [-r repeats]\n", argv[0]); return 2; }
    }
    if (th < 1) th = 1;
    if ((1ull << logc) < BLOCK || logc > 30 || lo >= hi || hi > (1ull << 32)) { fprintf(stderr, "bad -c/-l/-h\n"); return 2; }
    nchunks = (hi - lo + (1ull << logc) - 1) >> logc;
    if (reps < 1) reps = 1;
    pthread_t *tid = malloc(sizeof(pthread_t) * (size_t)th);
    double dt = 1e300;
    for (int rep = 0; rep < reps; rep++) {
        atomic_store(&best, UINT64_MAX); atomic_store(&next_chunk, 0); atomic_store(&checked, 0);
        double t0 = now();
        for (long i = 0; i < th; i++) pthread_create(&tid[i], NULL, worker, NULL);
        for (long i = 0; i < th; i++) pthread_join(tid[i], NULL);
        double d = now() - t0; if (d < dt) dt = d;
    }
    uint64_t b = atomic_load(&best), n = atomic_load(&checked);
    if (!quiet) fprintf(stderr, "%s: %" PRIu64 " inputs in %.3f s on %ld threads (%.2f G inputs/s, chunk 2^%u%s)\n",
                        FUNCS_NAME, n, dt, th, n / dt / 1e9, logc, reps > 1 ? ", best of repeats" : "");
    if (b == UINT64_MAX) {
        printf("IDENTICAL on [0x%08" PRIx64 ", 0x%08" PRIx64 "]\n", lo, hi - 1);
        return 0;
    }
    uint32_t x = (uint32_t)b;
    printf("DIFFER: smallest counterexample x = 0x%08" PRIx32 " (%" PRIu32 "): F(x) = 0x%08" PRIx32 ", G(x) = 0x%08" PRIx32 "\n",
           x, x, F(x), G(x));
    return 1;
}
