#include "Halide.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var t0("t0"), t1("t1"), t2("t2");

    // Construct a Func RHS that uses Vars with names that collide with those
    // that will be generated by CSE.
    Expr e = cast<uint32_t>(t0 + t1);

    // Add a bunch of reuse of subexpressions so that CSE introduces lets.
    e = e * e;
    e = e * e;
    e = e * e;

    // Add additional uses of t0, t1 that will appear inside the innermost let
    // body, where they're guaranteed to collide with enclosing lets.
    e += cast<uint32_t>(t0) + cast<uint32_t>(t1);

    // CSE should know to not introduce uses of t0, t1 because those already
    // occur in e. It may introduce uses of t2, which is unseen, but that
    // shouldn't confuse things because it's bound by an enclosing let so it
    // should be clear to compiler passes that it's distinct from the Var t2 on
    // the LHS.
    Func f;
    f(t0, t1, t2) = e;

    Buffer<uint32_t> buf = f.realize({32, 32, 32});

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            for (int k = 0; k < 32; k++) {
                uint32_t correct = i + j;
                correct *= correct;
                correct *= correct;
                correct *= correct;
                correct += i + j;
                if (buf(i, j, k) != correct) {
                    printf("buf(%d, %d, %d) = %d instead of %d\n",
                           i, j, k, buf(i, j, k), correct);
                    return 1;
                }
            }
        }
    }

    printf("Success!\n");
    return 0;
}
